file_id
int64
1
215k
content
stringlengths
7
454k
repo
stringlengths
6
113
path
stringlengths
6
251
2,089
/* * Copyright (C) 2010 The Guava 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.common.base; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.logging.Level.WARNING; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import com.google.errorprone.annotations.InlineMe; import com.google.errorprone.annotations.InlineMeValidationDisabled; import java.util.logging.Logger; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods pertaining to {@code String} or {@code CharSequence} instances. * * @author Kevin Bourrillion * @since 3.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Strings { private Strings() {} /** * Returns the given string if it is non-null; the empty string otherwise. * * @param string the string to test and possibly return * @return {@code string} itself if it is non-null; {@code ""} if it is null */ public static String nullToEmpty(@CheckForNull String string) { return Platform.nullToEmpty(string); } /** * Returns the given string if it is nonempty; {@code null} otherwise. * * @param string the string to test and possibly return * @return {@code string} itself if it is nonempty; {@code null} if it is empty or null */ @CheckForNull public static String emptyToNull(@CheckForNull String string) { return Platform.emptyToNull(string); } /** * Returns {@code true} if the given string is null or is the empty string. * * <p>Consider normalizing your string references with {@link #nullToEmpty}. If you do, you can * use {@link String#isEmpty()} instead of this method, and you won't need special null-safe forms * of methods like {@link String#toUpperCase} either. Or, if you'd like to normalize "in the other * direction," converting empty strings to {@code null}, you can use {@link #emptyToNull}. * * @param string a string reference to check * @return {@code true} if the string is null or is the empty string */ public static boolean isNullOrEmpty(@CheckForNull String string) { return Platform.stringIsNullOrEmpty(string); } /** * Returns a string, of length at least {@code minLength}, consisting of {@code string} prepended * with as many copies of {@code padChar} as are necessary to reach that length. For example, * * <ul> * <li>{@code padStart("7", 3, '0')} returns {@code "007"} * <li>{@code padStart("2010", 3, '0')} returns {@code "2010"} * </ul> * * <p>See {@link java.util.Formatter} for a richer set of formatting capabilities. * * @param string the string which should appear at the end of the result * @param minLength the minimum length the resulting string must have. Can be zero or negative, in * which case the input string is always returned. * @param padChar the character to insert at the beginning of the result until the minimum length * is reached * @return the padded string */ public static String padStart(String string, int minLength, char padChar) { checkNotNull(string); // eager for GWT. if (string.length() >= minLength) { return string; } StringBuilder sb = new StringBuilder(minLength); for (int i = string.length(); i < minLength; i++) { sb.append(padChar); } sb.append(string); return sb.toString(); } /** * Returns a string, of length at least {@code minLength}, consisting of {@code string} appended * with as many copies of {@code padChar} as are necessary to reach that length. For example, * * <ul> * <li>{@code padEnd("4.", 5, '0')} returns {@code "4.000"} * <li>{@code padEnd("2010", 3, '!')} returns {@code "2010"} * </ul> * * <p>See {@link java.util.Formatter} for a richer set of formatting capabilities. * * @param string the string which should appear at the beginning of the result * @param minLength the minimum length the resulting string must have. Can be zero or negative, in * which case the input string is always returned. * @param padChar the character to append to the end of the result until the minimum length is * reached * @return the padded string */ public static String padEnd(String string, int minLength, char padChar) { checkNotNull(string); // eager for GWT. if (string.length() >= minLength) { return string; } StringBuilder sb = new StringBuilder(minLength); sb.append(string); for (int i = string.length(); i < minLength; i++) { sb.append(padChar); } return sb.toString(); } /** * Returns a string consisting of a specific number of concatenated copies of an input string. For * example, {@code repeat("hey", 3)} returns the string {@code "heyheyhey"}. * * <p><b>Java 11+ users:</b> use {@code string.repeat(count)} instead. * * @param string any non-null string * @param count the number of times to repeat it; a nonnegative integer * @return a string containing {@code string} repeated {@code count} times (the empty string if * {@code count} is zero) * @throws IllegalArgumentException if {@code count} is negative */ @InlineMe(replacement = "string.repeat(count)") @InlineMeValidationDisabled("Java 11+ API only") public static String repeat(String string, int count) { checkNotNull(string); // eager for GWT. if (count <= 1) { checkArgument(count >= 0, "invalid count: %s", count); return (count == 0) ? "" : string; } // IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark final int len = string.length(); final long longSize = (long) len * (long) count; final int size = (int) longSize; if (size != longSize) { throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize); } final char[] array = new char[size]; string.getChars(0, len, array, 0); int n; for (n = len; n < size - n; n <<= 1) { System.arraycopy(array, 0, array, n, n); } System.arraycopy(array, 0, array, n, size - n); return new String(array); } /** * Returns the longest string {@code prefix} such that {@code a.toString().startsWith(prefix) && * b.toString().startsWith(prefix)}, taking care not to split surrogate pairs. If {@code a} and * {@code b} have no common prefix, returns the empty string. * * @since 11.0 */ public static String commonPrefix(CharSequence a, CharSequence b) { checkNotNull(a); checkNotNull(b); int maxPrefixLength = Math.min(a.length(), b.length()); int p = 0; while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) { p++; } if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) { p--; } return a.subSequence(0, p).toString(); } /** * Returns the longest string {@code suffix} such that {@code a.toString().endsWith(suffix) && * b.toString().endsWith(suffix)}, taking care not to split surrogate pairs. If {@code a} and * {@code b} have no common suffix, returns the empty string. * * @since 11.0 */ public static String commonSuffix(CharSequence a, CharSequence b) { checkNotNull(a); checkNotNull(b); int maxSuffixLength = Math.min(a.length(), b.length()); int s = 0; while (s < maxSuffixLength && a.charAt(a.length() - s - 1) == b.charAt(b.length() - s - 1)) { s++; } if (validSurrogatePairAt(a, a.length() - s - 1) || validSurrogatePairAt(b, b.length() - s - 1)) { s--; } return a.subSequence(a.length() - s, a.length()).toString(); } /** * True when a valid surrogate pair starts at the given {@code index} in the given {@code string}. * Out-of-range indexes return false. */ @VisibleForTesting static boolean validSurrogatePairAt(CharSequence string, int index) { return index >= 0 && index <= (string.length() - 2) && Character.isHighSurrogate(string.charAt(index)) && Character.isLowSurrogate(string.charAt(index + 1)); } /** * Returns the given {@code template} string with each occurrence of {@code "%s"} replaced with * the corresponding argument value from {@code args}; or, if the placeholder and argument counts * do not match, returns a best-effort form of that string. Will not throw an exception under * normal conditions. * * <p><b>Note:</b> For most string-formatting needs, use {@link String#format String.format}, * {@link java.io.PrintWriter#format PrintWriter.format}, and related methods. These support the * full range of <a * href="https://docs.oracle.com/javase/9/docs/api/java/util/Formatter.html#syntax">format * specifiers</a>, and alert you to usage errors by throwing {@link * java.util.IllegalFormatException}. * * <p>In certain cases, such as outputting debugging information or constructing a message to be * used for another unchecked exception, an exception during string formatting would serve little * purpose except to supplant the real information you were trying to provide. These are the cases * this method is made for; it instead generates a best-effort string with all supplied argument * values present. This method is also useful in environments such as GWT where {@code * String.format} is not available. As an example, method implementations of the {@link * Preconditions} class use this formatter, for both of the reasons just discussed. * * <p><b>Warning:</b> Only the exact two-character placeholder sequence {@code "%s"} is * recognized. * * @param template a string containing zero or more {@code "%s"} placeholder sequences. {@code * null} is treated as the four-character string {@code "null"}. * @param args the arguments to be substituted into the message template. The first argument * specified is substituted for the first occurrence of {@code "%s"} in the template, and so * forth. A {@code null} argument is converted to the four-character string {@code "null"}; * non-null values are converted to strings using {@link Object#toString()}. * @since 25.1 */ // TODO(diamondm) consider using Arrays.toString() for array parameters public static String lenientFormat( @CheckForNull String template, @CheckForNull @Nullable Object... args) { template = String.valueOf(template); // null -> "null" if (args == null) { args = new Object[] {"(Object[])null"}; } else { for (int i = 0; i < args.length; i++) { args[i] = lenientToString(args[i]); } } // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template, templateStart, placeholderStart); builder.append(args[i++]); templateStart = placeholderStart + 2; } builder.append(template, templateStart, template.length()); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append(']'); } return builder.toString(); } private static String lenientToString(@CheckForNull Object o) { if (o == null) { return "null"; } try { return o.toString(); } catch (Exception e) { // Default toString() behavior - see Object.toString() String objectToString = o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o)); // Logger is created inline with fixed name to avoid forcing Proguard to create another class. Logger.getLogger("com.google.common.base.Strings") .log(WARNING, "Exception during lenientFormat for " + objectToString, e); return "<" + objectToString + " threw " + e.getClass().getName() + ">"; } } }
google/guava
guava/src/com/google/common/base/Strings.java
2,092
/* * Copyright (C) 2007 The Guava 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.common.io; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.CheckForNull; /** * Utility methods for working with {@link Closeable} objects. * * @author Michael Lancaster * @since 1.0 */ @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public final class Closeables { @VisibleForTesting static final Logger logger = Logger.getLogger(Closeables.class.getName()); private Closeables() {} /** * Closes a {@link Closeable}, with control over whether an {@code IOException} may be thrown. * This is primarily useful in a finally block, where a thrown exception needs to be logged but * not propagated (otherwise the original exception will be lost). * * <p>If {@code swallowIOException} is true then we never throw {@code IOException} but merely log * it. * * <p>Example: * * <pre>{@code * public void useStreamNicely() throws IOException { * SomeStream stream = new SomeStream("foo"); * boolean threw = true; * try { * // ... code which does something with the stream ... * threw = false; * } finally { * // If an exception occurs, rethrow it only if threw==false: * Closeables.close(stream, threw); * } * } * }</pre> * * @param closeable the {@code Closeable} object to be closed, or null, in which case this method * does nothing * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code close} * methods * @throws IOException if {@code swallowIOException} is false and {@code close} throws an {@code * IOException}. */ public static void close(@CheckForNull Closeable closeable, boolean swallowIOException) throws IOException { if (closeable == null) { return; } try { closeable.close(); } catch (IOException e) { if (swallowIOException) { logger.log(Level.WARNING, "IOException thrown while closing Closeable.", e); } else { throw e; } } } /** * Closes the given {@link InputStream}, logging any {@code IOException} that's thrown rather than * propagating it. * * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing an * I/O resource, it should generally be safe in the case of a resource that's being used only for * reading, such as an {@code InputStream}. Unlike with writable resources, there's no chance that * a failure that occurs when closing the stream indicates a meaningful problem such as a failure * to flush all bytes to the underlying resource. * * @param inputStream the input stream to be closed, or {@code null} in which case this method * does nothing * @since 17.0 */ public static void closeQuietly(@CheckForNull InputStream inputStream) { try { close(inputStream, true); } catch (IOException impossible) { throw new AssertionError(impossible); } } /** * Closes the given {@link Reader}, logging any {@code IOException} that's thrown rather than * propagating it. * * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing an * I/O resource, it should generally be safe in the case of a resource that's being used only for * reading, such as a {@code Reader}. Unlike with writable resources, there's no chance that a * failure that occurs when closing the reader indicates a meaningful problem such as a failure to * flush all bytes to the underlying resource. * * @param reader the reader to be closed, or {@code null} in which case this method does nothing * @since 17.0 */ public static void closeQuietly(@CheckForNull Reader reader) { try { close(reader, true); } catch (IOException impossible) { throw new AssertionError(impossible); } } }
google/guava
guava/src/com/google/common/io/Closeables.java
2,096
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.index.get; import org.apache.lucene.index.SortedSetDocValues; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.document.DocumentField; import org.elasticsearch.common.lucene.uid.Versions; import org.elasticsearch.common.lucene.uid.VersionsAndSeqNoResolver.DocIdAndVersion; import org.elasticsearch.common.metrics.CounterMetric; import org.elasticsearch.common.metrics.MeanMetric; import org.elasticsearch.core.Nullable; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.IndexVersion; import org.elasticsearch.index.IndexVersions; import org.elasticsearch.index.VersionType; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.fieldvisitor.LeafStoredFieldLoader; import org.elasticsearch.index.fieldvisitor.StoredFieldLoader; import org.elasticsearch.index.mapper.IgnoredFieldMapper; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.MappingLookup; import org.elasticsearch.index.mapper.RoutingFieldMapper; import org.elasticsearch.index.mapper.SourceFieldMapper; import org.elasticsearch.index.mapper.SourceLoader; import org.elasticsearch.index.shard.AbstractIndexShardComponent; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.MultiEngineGet; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import org.elasticsearch.search.lookup.Source; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM; import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO; public final class ShardGetService extends AbstractIndexShardComponent { private final MapperService mapperService; private final MeanMetric existsMetric = new MeanMetric(); private final MeanMetric missingMetric = new MeanMetric(); private final CounterMetric currentMetric = new CounterMetric(); private final IndexShard indexShard; public ShardGetService(IndexSettings indexSettings, IndexShard indexShard, MapperService mapperService) { super(indexShard.shardId(), indexSettings); this.mapperService = mapperService; this.indexShard = indexShard; } public GetStats stats() { return new GetStats( existsMetric.count(), TimeUnit.NANOSECONDS.toMillis(existsMetric.sum()), missingMetric.count(), TimeUnit.NANOSECONDS.toMillis(missingMetric.sum()), currentMetric.count() ); } public GetResult get( String id, String[] gFields, boolean realtime, long version, VersionType versionType, FetchSourceContext fetchSourceContext, boolean forceSyntheticSource ) throws IOException { return get( id, gFields, realtime, version, versionType, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, fetchSourceContext, forceSyntheticSource, indexShard::get ); } public GetResult get( String id, String[] gFields, boolean realtime, long version, VersionType versionType, FetchSourceContext fetchSourceContext, boolean forceSyntheticSource, MultiEngineGet mget ) throws IOException { return get( id, gFields, realtime, version, versionType, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, fetchSourceContext, forceSyntheticSource, mget::get ); } private GetResult get( String id, String[] gFields, boolean realtime, long version, VersionType versionType, long ifSeqNo, long ifPrimaryTerm, FetchSourceContext fetchSourceContext, boolean forceSyntheticSource, Function<Engine.Get, Engine.GetResult> engineGetOperator ) throws IOException { currentMetric.inc(); try { long now = System.nanoTime(); GetResult getResult = innerGet( id, gFields, realtime, version, versionType, ifSeqNo, ifPrimaryTerm, fetchSourceContext, forceSyntheticSource, engineGetOperator ); if (getResult != null && getResult.isExists()) { existsMetric.inc(System.nanoTime() - now); } else { missingMetric.inc(System.nanoTime() - now); } return getResult; } finally { currentMetric.dec(); } } public GetResult getFromTranslog( String id, String[] gFields, boolean realtime, long version, VersionType versionType, FetchSourceContext fetchSourceContext, boolean forceSyntheticSource ) throws IOException { return get( id, gFields, realtime, version, versionType, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, fetchSourceContext, forceSyntheticSource, indexShard::getFromTranslog ); } public GetResult getForUpdate(String id, long ifSeqNo, long ifPrimaryTerm) throws IOException { return get( id, new String[] { RoutingFieldMapper.NAME }, true, Versions.MATCH_ANY, VersionType.INTERNAL, ifSeqNo, ifPrimaryTerm, FetchSourceContext.FETCH_SOURCE, false, indexShard::get ); } /** * Returns {@link GetResult} based on the specified {@link org.elasticsearch.index.engine.Engine.GetResult} argument. * This method basically loads specified fields for the associated document in the engineGetResult. * This method load the fields from the Lucene index and not from transaction log and therefore isn't realtime. * <p> * Note: Call <b>must</b> release engine searcher associated with engineGetResult! */ public GetResult get(Engine.GetResult engineGetResult, String id, String[] fields, FetchSourceContext fetchSourceContext) throws IOException { if (engineGetResult.exists() == false) { return new GetResult(shardId.getIndexName(), id, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, -1, false, null, null, null); } currentMetric.inc(); try { long now = System.nanoTime(); fetchSourceContext = normalizeFetchSourceContent(fetchSourceContext, fields); GetResult getResult = innerGetFetch(id, fields, fetchSourceContext, engineGetResult, false); if (getResult.isExists()) { existsMetric.inc(System.nanoTime() - now); } else { missingMetric.inc(System.nanoTime() - now); // This shouldn't happen... } return getResult; } finally { currentMetric.dec(); } } /** * decides what needs to be done based on the request input and always returns a valid non-null FetchSourceContext */ private static FetchSourceContext normalizeFetchSourceContent(@Nullable FetchSourceContext context, @Nullable String[] gFields) { if (context != null) { return context; } if (gFields == null) { return FetchSourceContext.FETCH_SOURCE; } for (String field : gFields) { if (SourceFieldMapper.NAME.equals(field)) { return FetchSourceContext.FETCH_SOURCE; } } return FetchSourceContext.DO_NOT_FETCH_SOURCE; } private GetResult innerGet( String id, String[] gFields, boolean realtime, long version, VersionType versionType, long ifSeqNo, long ifPrimaryTerm, FetchSourceContext fetchSourceContext, boolean forceSyntheticSource, Function<Engine.Get, Engine.GetResult> engineGetOperator ) throws IOException { fetchSourceContext = normalizeFetchSourceContent(fetchSourceContext, gFields); var engineGet = new Engine.Get(realtime, realtime, id).version(version) .versionType(versionType) .setIfSeqNo(ifSeqNo) .setIfPrimaryTerm(ifPrimaryTerm); try (Engine.GetResult get = engineGetOperator.apply(engineGet)) { if (get == null) { return null; } if (get.exists() == false) { return new GetResult(shardId.getIndexName(), id, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, -1, false, null, null, null); } // break between having loaded it from translog (so we only have _source), and having a document to load return innerGetFetch(id, gFields, fetchSourceContext, get, forceSyntheticSource); } } private GetResult innerGetFetch( String id, String[] storedFields, FetchSourceContext fetchSourceContext, Engine.GetResult get, boolean forceSyntheticSource ) throws IOException { assert get.exists() : "method should only be called if document could be retrieved"; // check first if stored fields to be loaded don't contain an object field MappingLookup mappingLookup = mapperService.mappingLookup(); if (storedFields != null) { for (String field : storedFields) { Mapper fieldMapper = mappingLookup.getMapper(field); if (fieldMapper == null) { if (mappingLookup.objectMappers().get(field) != null) { // Only fail if we know it is a object field, missing paths / fields shouldn't fail. throw new IllegalArgumentException("field [" + field + "] isn't a leaf field"); } } } } Map<String, DocumentField> documentFields = null; Map<String, DocumentField> metadataFields = null; DocIdAndVersion docIdAndVersion = get.docIdAndVersion(); SourceLoader loader = forceSyntheticSource ? new SourceLoader.Synthetic(mappingLookup.getMapping()) : mappingLookup.newSourceLoader(); StoredFieldLoader storedFieldLoader = buildStoredFieldLoader(storedFields, fetchSourceContext, loader); LeafStoredFieldLoader leafStoredFieldLoader = storedFieldLoader.getLoader(docIdAndVersion.reader.getContext(), null); try { leafStoredFieldLoader.advanceTo(docIdAndVersion.docId); } catch (IOException e) { throw new ElasticsearchException("Failed to get id [" + id + "]", e); } // put stored fields into result objects final IndexVersion indexVersion = indexSettings.getIndexVersionCreated(); if (leafStoredFieldLoader.storedFields().isEmpty() == false) { Set<String> needed = new HashSet<>(); if (storedFields != null) { Collections.addAll(needed, storedFields); } needed.add(RoutingFieldMapper.NAME); // we always return _routing if we see it, even if you don't ask for it..... documentFields = new HashMap<>(); metadataFields = new HashMap<>(); for (Map.Entry<String, List<Object>> entry : leafStoredFieldLoader.storedFields().entrySet()) { if (false == needed.contains(entry.getKey())) { continue; } if (IgnoredFieldMapper.NAME.equals(entry.getKey()) && indexVersion.onOrAfter(IndexVersions.DOC_VALUES_FOR_IGNORED_META_FIELD)) { continue; } MappedFieldType ft = mapperService.fieldType(entry.getKey()); if (ft == null) { continue; // user asked for a non-existent field, ignore it } List<Object> values = entry.getValue().stream().map(ft::valueForDisplay).toList(); if (mapperService.isMetadataField(entry.getKey())) { metadataFields.put(entry.getKey(), new DocumentField(entry.getKey(), values)); } else { documentFields.put(entry.getKey(), new DocumentField(entry.getKey(), values)); } } } // NOTE: when _ignored is requested via `stored_fields` we need to load it from doc values instead of loading it from stored fields. // The _ignored field used to be stored, but as a result of supporting aggregations on it, it moved from using a stored field to // using doc values. if (indexVersion.onOrAfter(IndexVersions.DOC_VALUES_FOR_IGNORED_META_FIELD) && storedFields != null && Arrays.asList(storedFields).contains(IgnoredFieldMapper.NAME)) { final DocumentField ignoredDocumentField = loadIgnoredMetadataField(docIdAndVersion); if (ignoredDocumentField != null) { if (metadataFields == null) { metadataFields = new HashMap<>(); } metadataFields.put(IgnoredFieldMapper.NAME, ignoredDocumentField); } } BytesReference sourceBytes = null; if (mapperService.mappingLookup().isSourceEnabled() && fetchSourceContext.fetchSource()) { Source source = loader.leaf(docIdAndVersion.reader, new int[] { docIdAndVersion.docId }) .source(leafStoredFieldLoader, docIdAndVersion.docId); if (fetchSourceContext.hasFilter()) { source = source.filter(fetchSourceContext.filter()); } sourceBytes = source.internalSourceRef(); } return new GetResult( shardId.getIndexName(), id, get.docIdAndVersion().seqNo, get.docIdAndVersion().primaryTerm, get.version(), get.exists(), sourceBytes, documentFields, metadataFields ); } private static DocumentField loadIgnoredMetadataField(final DocIdAndVersion docIdAndVersion) throws IOException { final SortedSetDocValues ignoredDocValues = docIdAndVersion.reader.getContext() .reader() .getSortedSetDocValues(IgnoredFieldMapper.NAME); if (ignoredDocValues == null || ignoredDocValues.advanceExact(docIdAndVersion.docId) == false || ignoredDocValues.docValueCount() <= 0) { return null; } final List<Object> ignoredValues = new ArrayList<>(ignoredDocValues.docValueCount()); for (int i = 0; i < ignoredDocValues.docValueCount(); i++) { ignoredValues.add(ignoredDocValues.lookupOrd(ignoredDocValues.nextOrd()).utf8ToString()); } return new DocumentField(IgnoredFieldMapper.NAME, ignoredValues); } private static StoredFieldLoader buildStoredFieldLoader(String[] fields, FetchSourceContext fetchSourceContext, SourceLoader loader) { Set<String> fieldsToLoad = new HashSet<>(); if (fields != null && fields.length > 0) { Collections.addAll(fieldsToLoad, fields); } if (fetchSourceContext.fetchSource()) { fieldsToLoad.addAll(loader.requiredStoredFields()); } else { if (fieldsToLoad.isEmpty()) { return StoredFieldLoader.empty(); } } return StoredFieldLoader.create(fetchSourceContext.fetchSource(), fieldsToLoad); } }
gitpod-io/elasticsearch
server/src/main/java/org/elasticsearch/index/get/ShardGetService.java
2,098
/* * Copyright (C) 2009 The Guava 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.common.io; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.IOException; import org.checkerframework.checker.nullness.qual.Nullable; /** * A callback to be used with the streaming {@code readLines} methods. * * <p>{@link #processLine} will be called for each line that is read, and should return {@code * false} when you want to stop processing. * * @author Miles Barr * @since 1.0 */ @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public interface LineProcessor<T extends @Nullable Object> { /** * This method will be called once for each line. * * @param line the line read from the input, without delimiter * @return true to continue processing, false to stop */ @CanIgnoreReturnValue // some uses know that their processor never returns false boolean processLine(String line) throws IOException; /** Return the result of processing all the lines. */ @ParametricNullness T getResult(); }
google/guava
guava/src/com/google/common/io/LineProcessor.java
2,101
import java.util.Random; public class Die { private static final int DEFAULT_SIDES = 6; private int faceValue; private int sides; private Random generator = new Random(); /** * Construct a new Die with default sides */ public Die() { this.sides = DEFAULT_SIDES; this.faceValue = 1 + generator.nextInt(sides); } /** * Generate a new random number between 1 and sides to be stored in faceValue */ private void throwDie() { this.faceValue = 1 + generator.nextInt(sides); } /** * @return the faceValue */ public int getFaceValue() { return faceValue; } public void printDie() { throwDie(); int x = this.getFaceValue(); System.out.println(" ----- "); if(x==4||x==5||x==6) { printTwo(); } else if(x==2||x==3) { System.out.println("| * |"); } else { printZero(); } if(x==1||x==3||x==5) { System.out.println("| * |"); } else if(x==2||x==4) { printZero(); } else { printTwo(); } if(x==4||x==5||x==6) { printTwo(); } else if(x==2||x==3) { System.out.println("| * |"); } else { printZero(); } System.out.println(" ----- "); } private void printZero() { System.out.println("| |"); } private void printTwo() { System.out.println("| * * |"); } }
coding-horror/basic-computer-games
61_Math_Dice/java/Die.java
2,102
package jadx.core.xmlgen; import java.io.IOException; public class CommonBinaryParser extends ParserConstants { protected ParserStream is; protected BinaryXMLStrings parseStringPool() throws IOException { is.checkInt16(RES_STRING_POOL_TYPE, "String pool expected"); return parseStringPoolNoType(); } protected BinaryXMLStrings parseStringPoolNoType() throws IOException { long start = is.getPos() - 2; is.checkInt16(0x001c, "String pool header size not 0x001c"); long size = is.readUInt32(); long chunkEnd = start + size; int stringCount = is.readInt32(); int styleCount = is.readInt32(); int flags = is.readInt32(); long stringsStart = is.readInt32(); long stylesStart = is.readInt32(); // Correct the offset of actual strings, as the header is already read. stringsStart = stringsStart - (is.getPos() - start); byte[] buffer = is.readInt8Array((int) (chunkEnd - is.getPos())); is.checkPos(chunkEnd, "Expected strings pool end"); return new BinaryXMLStrings( stringCount, stringsStart, buffer, (flags & UTF8_FLAG) != 0); } protected void die(String message) throws IOException { throw new IOException("Decode error: " + message + ", position: 0x" + Long.toHexString(is.getPos())); } }
skylot/jadx
jadx-core/src/main/java/jadx/core/xmlgen/CommonBinaryParser.java
2,103
package water; import hex.ModelBuilder; import jsr166y.CountedCompleter; import jsr166y.ForkJoinPool; import jsr166y.ForkJoinWorkerThread; import org.apache.log4j.LogManager; import org.apache.log4j.PropertyConfigurator; import water.UDPRebooted.ShutdownTsk; import water.api.LogsHandler; import water.api.RequestServer; import water.exceptions.H2OFailException; import water.exceptions.H2OIllegalArgumentException; import water.init.*; import water.nbhm.NonBlockingHashMap; import water.parser.DecryptionTool; import water.parser.ParserService; import water.persist.PersistManager; import water.server.ServletUtils; import water.util.*; import water.webserver.iface.WebServer; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.*; import java.nio.file.FileSystems; import java.nio.file.PathMatcher; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * Start point for creating or joining an <code>H2O</code> Cloud. * * @author <a href="mailto:[email protected]"></a> * @version 1.0 */ final public class H2O { public static final String DEFAULT_JKS_PASS = "h2oh2o"; public static final int H2O_DEFAULT_PORT = 54321; public static final Map<Integer, Integer> GITHUB_DISCUSSIONS = createMap(); static Map<Integer, Integer> createMap() { Integer[] GHDiscussion = new Integer[]{15512, 15513, 15514, 15515, 15516, 15517, 15518, 15519, 15520, 15521, 15522, 15523, 15524, 15525}; Integer[] techNoteNumber = new Integer[]{1,2,3,4,5,7,9,10,11,12,13,14,15,16}; Map<Integer, Integer> mapTNToGH = new HashMap<>(); int mapLen = GHDiscussion.length; for (int index=0; index<mapLen; index++) mapTNToGH.put(techNoteNumber[index], GHDiscussion[index]); return mapTNToGH; } //------------------------------------------------------------------------------------------------------------------- // Command-line argument parsing and help //------------------------------------------------------------------------------------------------------------------- /** * Print help about command line arguments. */ public static void printHelp() { String defaultFlowDirMessage; if (DEFAULT_FLOW_DIR() == null) { // If you start h2o on Hadoop, you must set -flow_dir. // H2O doesn't know how to guess a good one. // user.home doesn't make sense. defaultFlowDirMessage = " (The default is none; saving flows not available.)\n"; } else { defaultFlowDirMessage = " (The default is '" + DEFAULT_FLOW_DIR() + "'.)\n"; } String s = "\n" + "Usage: java [-Xmx<size>] -jar h2o.jar [options]\n" + " (Note that every option has a default and is optional.)\n" + "\n" + " -h | -help\n" + " Print this help.\n" + "\n" + " -version\n" + " Print version info and exit.\n" + "\n" + " -name <h2oCloudName>\n" + " Cloud name used for discovery of other nodes.\n" + " Nodes with the same cloud name will form an H2O cloud\n" + " (also known as an H2O cluster).\n" + "\n" + " -flatfile <flatFileName>\n" + " Configuration file explicitly listing H2O cloud node members.\n" + "\n" + " -ip <ipAddressOfNode>\n" + " IP address of this node.\n" + "\n" + " -port <port>\n" + " Port number for this node (note: port+1 is also used by default).\n" + " (The default port is " + ARGS.port + ".)\n" + "\n" + " -network <IPv4network1Specification>[,<IPv4network2Specification> ...]\n" + " The IP address discovery code will bind to the first interface\n" + " that matches one of the networks in the comma-separated list.\n" + " Use instead of -ip when a broad range of addresses is legal.\n" + " (Example network specification: '10.1.2.0/24' allows 256 legal\n" + " possibilities.)\n" + "\n" + " -ice_root <fileSystemPath>\n" + " The directory where H2O spills temporary data to disk.\n" + "\n" + " -log_dir <fileSystemPath>\n" + " The directory where H2O writes logs to disk.\n" + " (This usually has a good default that you need not change.)\n" + "\n" + " -log_level <TRACE,DEBUG,INFO,WARN,ERRR,FATAL>\n" + " Write messages at this logging level, or above. Default is INFO.\n" + "\n" + " -max_log_file_size\n" + " Maximum size of INFO and DEBUG log files. The file is rolled over after a specified size has been reached.\n" + " (The default is 3MB. Minimum is 1MB and maximum is 99999MB)\n" + "\n" + " -flow_dir <server side directory or HDFS directory>\n" + " The directory where H2O stores saved flows.\n" + defaultFlowDirMessage + "\n" + " -nthreads <#threads>\n" + " Maximum number of threads in the low priority batch-work queue.\n" + " (The default is " + (char)H2ORuntime.availableProcessors() + ".)\n" + "\n" + " -client\n" + " Launch H2O node in client mode.\n" + "\n" + " -notify_local <fileSystemPath>\n" + " Specifies a file to write when the node is up. The file contains one line with the IP and\n" + " port of the embedded web server. e.g. 192.168.1.100:54321\n" + "\n" + " -context_path <context_path>\n" + " The context path for jetty.\n" + "\n" + "Authentication options:\n" + "\n" + " -jks <filename>\n" + " Java keystore file\n" + "\n" + " -jks_pass <password>\n" + " (Default is '" + DEFAULT_JKS_PASS + "')\n" + "\n" + " -jks_alias <alias>\n" + " (Optional, use if the keystore has multiple certificates and you want to use a specific one.)\n" + "\n" + " -hostname_as_jks_alias\n" + " (Optional, use if you want to use the machine hostname as your certificate alias.)\n" + "\n" + " -hash_login\n" + " Use Jetty HashLoginService\n" + "\n" + " -ldap_login\n" + " Use Jetty Ldap login module\n" + "\n" + " -kerberos_login\n" + " Use Jetty Kerberos login module\n" + "\n" + " -spnego_login\n" + " Use Jetty SPNEGO login service\n" + "\n" + " -pam_login\n" + " Use Jetty PAM login module\n" + "\n" + " -login_conf <filename>\n" + " LoginService configuration file\n" + "\n" + " -spnego_properties <filename>\n" + " SPNEGO login module configuration file\n" + "\n" + " -form_auth\n" + " Enables Form-based authentication for Flow (default is Basic authentication)\n" + "\n" + " -session_timeout <minutes>\n" + " Specifies the number of minutes that a session can remain idle before the server invalidates\n" + " the session and requests a new login. Requires '-form_auth'. Default is no timeout\n" + "\n" + " -internal_security_conf <filename>\n" + " Path (absolute or relative) to a file containing all internal security related configurations\n" + "\n" + "Cloud formation behavior:\n" + "\n" + " New H2O nodes join together to form a cloud at startup time.\n" + " Once a cloud is given work to perform, it locks out new members\n" + " from joining.\n" + "\n" + "Examples:\n" + "\n" + " Start an H2O node with 4GB of memory and a default cloud name:\n" + " $ java -Xmx4g -jar h2o.jar\n" + "\n" + " Start an H2O node with 6GB of memory and a specify the cloud name:\n" + " $ java -Xmx6g -jar h2o.jar -name MyCloud\n" + "\n" + " Start an H2O cloud with three 2GB nodes and a default cloud name:\n" + " $ java -Xmx2g -jar h2o.jar &\n" + " $ java -Xmx2g -jar h2o.jar &\n" + " $ java -Xmx2g -jar h2o.jar &\n" + "\n"; System.out.print(s); for (AbstractH2OExtension e : extManager.getCoreExtensions()) { e.printHelp(); } } /** * Singleton ARGS instance that contains the processed arguments. */ public static final OptArgs ARGS = new OptArgs(); /** * A class containing all of the authentication arguments for H2O. */ public static class BaseArgs { //----------------------------------------------------------------------------------- // Authentication & Security //----------------------------------------------------------------------------------- /** -jks is Java KeyStore file on local filesystem */ public String jks = null; /** -jks_pass is Java KeyStore password; default is 'h2oh2o' */ public String jks_pass = DEFAULT_JKS_PASS; /** -jks_alias if the keystore has multiple certificates and you want to use a specific one */ public String jks_alias = null; /** -hostname_as_jks_alias if you want to use the machine hostname as your certificate alias */ public boolean hostname_as_jks_alias = false; /** -hash_login enables HashLoginService */ public boolean hash_login = false; /** -ldap_login enables ldaploginmodule */ public boolean ldap_login = false; /** -kerberos_login enables krb5loginmodule */ public boolean kerberos_login = false; /** -kerberos_login enables SpnegoLoginService */ public boolean spnego_login = false; /** -pam_login enables pamloginmodule */ public boolean pam_login = false; /** -login_conf is login configuration service file on local filesystem */ public String login_conf = null; /** -spnego_properties is SPNEGO configuration file on local filesystem */ public String spnego_properties = null; /** -form_auth enables Form-based authentication */ public boolean form_auth = false; /** -session_timeout maximum duration of session inactivity in minutes **/ String session_timeout_spec = null; // raw value specified by the user public int session_timeout = 0; // parsed value (in minutes) /** -user_name=user_name; Set user name */ public String user_name = System.getProperty("user.name"); /** -internal_security_conf path (absolute or relative) to a file containing all internal security related configurations */ public String internal_security_conf = null; /** -internal_security_conf_rel_paths interpret paths of internal_security_conf relative to the main config file */ public boolean internal_security_conf_rel_paths = false; /** -internal_security_enabled is a boolean that indicates if internal communication paths are secured*/ public boolean internal_security_enabled = false; /** -allow_insecure_xgboost is a boolean that allows xgboost to run in a secured cluster */ public boolean allow_insecure_xgboost = false; /** -use_external_xgboost; invoke XGBoost on external cluster started by Steam */ public boolean use_external_xgboost = false; /** -decrypt_tool specifies the DKV key where a default decrypt tool will be installed*/ public String decrypt_tool = null; //----------------------------------------------------------------------------------- // Kerberos //----------------------------------------------------------------------------------- public String principal = null; public String keytab_path = null; public String hdfs_token_refresh_interval = null; //----------------------------------------------------------------------------------- // Networking //----------------------------------------------------------------------------------- /** -port=####; Specific Browser/API/HTML port */ public int port; /** -baseport=####; Port to start upward searching from. */ public int baseport = H2O_DEFAULT_PORT; /** -port_offset=####; Offset between the API(=web) port and the internal communication port; api_port + port_offset = h2o_port */ public int port_offset = 1; /** -web_ip=ip4_or_ip6; IP used for web server. By default it listen to all interfaces. */ public String web_ip = null; /** -ip=ip4_or_ip6; Named IP4/IP6 address instead of the default */ public String ip; /** -network=network; Network specification for acceptable interfaces to bind to */ public String network; /** -context_path=jetty_context_path; the context path for jetty */ public String context_path = ""; public KeyValueArg[] extra_headers = new KeyValueArg[0]; public PathMatcher file_deny_glob = FileSystems.getDefault().getPathMatcher("glob:{/bin/*,/etc/*,/var/*,/usr/*,/proc/*,**/.**}"); } public static class KeyValueArg { public final String _key; public final String _value; private KeyValueArg(String key, String value) { _key = key; _value = value; } } /** * A class containing all of the arguments for H2O. */ public static class OptArgs extends BaseArgs { // Prefix of hidden system properties public static final String SYSTEM_PROP_PREFIX = "sys.ai.h2o."; public static final String SYSTEM_DEBUG_CORS = H2O.OptArgs.SYSTEM_PROP_PREFIX + "debug.cors"; //----------------------------------------------------------------------------------- // Help and info //----------------------------------------------------------------------------------- /** -help, -help=true; print help and exit*/ public boolean help = false; /** -version, -version=true; print version and exit */ public boolean version = false; //----------------------------------------------------------------------------------- // Clouding //----------------------------------------------------------------------------------- /** -name=name; Set cloud name */ public String name = System.getProperty("user.name"); // Cloud name /** -flatfile=flatfile; Specify a list of cluster IP addresses */ public String flatfile; //----------------------------------------------------------------------------------- // Node configuration //----------------------------------------------------------------------------------- /** -ice_root=ice_root; ice root directory; where temp files go */ public String ice_root; /** -cleaner; enable user-mode spilling of big data to disk in ice_root */ public boolean cleaner = false; /** -nthreads=nthreads; Max number of F/J threads in the low-priority batch queue */ public short nthreads= (short)H2ORuntime.availableProcessors(); /** -log_dir=/path/to/dir; directory to save logs in */ public String log_dir; /** -flow_dir=/path/to/dir; directory to save flows in */ public String flow_dir; /** -disable_web; disable Jetty and REST API interface */ public boolean disable_web = false; /** -disable_net; do not listen to incoming traffic and do not try to discover other nodes, for single node deployments */ public boolean disable_net = false; /** -disable_flow; disable access to H2O Flow, keep REST API interface available to clients */ public boolean disable_flow = false; /** -client, -client=true; Client-only; no work; no homing of Keys (but can cache) */ public boolean client; /** -allow_clients, -allow_clients=true; Enable clients to connect to this H2O node - disabled by default */ public boolean allow_clients = false; public boolean allow_unsupported_java = false; /** If this timeout is set to non 0 value, stop the cluster if there hasn't been any rest api request to leader * node after the given timeout. Unit is milliseconds. */ public int rest_api_ping_timeout = 0; /** specifies a file to write when the node is up */ public String notify_local; /** what the is ratio of available off-heap memory to maximum JVM heap memory */ public double off_heap_memory_ratio = 0; //----------------------------------------------------------------------------------- // HDFS & AWS //----------------------------------------------------------------------------------- /** -hdfs_config=hdfs_config; configuration file of the HDFS */ public String[] hdfs_config = null; /** -hdfs_skip=hdfs_skip; used by Hadoop driver to not unpack and load any HDFS jar file at runtime. */ public boolean hdfs_skip = false; /** -aws_credentials=aws_credentials; properties file for aws credentials */ public String aws_credentials = null; /** -configure_s3_using_s3a; use S3A(FileSystem) to configure S3 client */ public boolean configure_s3_using_s3a = false; /** --ga_hadoop_ver=ga_hadoop_ver; Version string for Hadoop */ public String ga_hadoop_ver = null; /** -Hkey=value; additional configuration to merge into the Hadoop Configuration */ public final Properties hadoop_properties = new Properties(); //----------------------------------------------------------------------------------- // Recovery //----------------------------------------------------------------------------------- /** -auto_recovery_dir=hdfs://path/to/recovery; Where to store {@link hex.faulttolerance.Recoverable} job data */ public String auto_recovery_dir; //----------------------------------------------------------------------------------- // Debugging //----------------------------------------------------------------------------------- /** -log_level=log_level; One of DEBUG, INFO, WARN, ERRR. Default is INFO. */ public String log_level; /** -max_log_file_size=max_log_file_size; Maximum size of log file. The file is rolled over after a specified size has been reached.*/ public String max_log_file_size; /** -random_udp_drop, -random_udp_drop=true; test only, randomly drop udp incoming */ public boolean random_udp_drop; /** -md5skip, -md5skip=true; test-only; Skip the MD5 Jar checksum; allows jars from different builds to mingle in the same cloud */ public boolean md5skip = false; /** -quiet Enable quiet mode and avoid any prints to console, useful for client embedding */ public boolean quiet = false; /** Timeout specifying how long to wait before we check if the client has disconnected from this node */ public long clientDisconnectTimeout = HeartBeatThread.CLIENT_TIMEOUT * 20; /** -embedded; when running embedded into another application (eg. Sparkling Water) - enforce all threads to be daemon threads */ public boolean embedded = false; /** * Optionally disable algorithms marked as beta or experimental. * Everything is on by default. */ public ModelBuilder.BuilderVisibility features_level = ModelBuilder.BuilderVisibility.Experimental; @Override public String toString() { StringBuilder result = new StringBuilder(); //determine fields declared in this class only (no fields of superclass) Field[] fields = this.getClass().getDeclaredFields(); //print field names paired with their values result.append("[ "); for (Field field : fields) { try { result.append(field.getName()); result.append(": "); //requires access to private field: result.append(field.get(this)); result.append(", "); } catch (IllegalAccessException ex) { Log.err(ex, ex); } } result.deleteCharAt(result.length() - 2); result.deleteCharAt(result.length() - 1); result.append(" ]"); return result.toString(); } /** * Whether this H2O instance was launched on hadoop (using 'hadoop jar h2odriver.jar') or not. */ public boolean launchedWithHadoopJar() { return hdfs_skip; } } public static void parseFailed(String message) { System.out.println(""); System.out.println("ERROR: " + message); System.out.println(""); printHelp(); H2O.exitQuietly(1); // argument parsing failed -> we might have inconsistent ARGS and not be able to initialize logging } /** * Use when given arguments are incompatible for cluster to run. * Log is flushed into stdout to show important debugging information */ public static void clusterInitializationFailed() { Log.flushBufferedMessagesToStdout(); H2O.exitQuietly(1); } public static class OptString { final String _s; String _lastMatchedFor; public OptString(String s) { _s = s; } public boolean matches(String s) { _lastMatchedFor = s; if (_s.equals("-" + s)) return true; if (_s.equals("--" + s)) return true; return false; } public int incrementAndCheck(int i, String[] args) { i = i + 1; if (i >= args.length) parseFailed(_lastMatchedFor + " not specified"); return i; } public int parseInt(String a) { try { return Integer.parseInt(a); } catch (Exception e) { } parseFailed("Argument " + _lastMatchedFor + " must be an integer (was given '" + a + "')" ); return 0; } public int parsePort(String portString){ int portNum = parseInt(portString); if(portNum < 0 || portNum > 65535){ parseFailed("Argument " + _lastMatchedFor + " must be an integer between 0 and 65535"); return 0; }else{ return portNum; } } public String checkFileSize(String fileSizeString){ int length = fileSizeString.length(); if(length > 2 && length < 8 && fileSizeString.substring(length-2, length).equals("MB")){ try { Integer.parseInt(fileSizeString.substring(0, length-2)); return fileSizeString; } catch (NumberFormatException ex){ parseFailed("Argument " + _lastMatchedFor + " must be String value from 1MB to 99999MB."); return null; } } parseFailed("Argument " + _lastMatchedFor + " must be String value from 1MB to 99999MB."); return null; } @Override public String toString() { return _s; } } /** * Dead stupid argument parser. */ static void parseArguments(String[] args) { for (AbstractH2OExtension e : extManager.getCoreExtensions()) { args = e.parseArguments(args); } parseH2OArgumentsTo(args, ARGS); } public static OptArgs parseH2OArgumentsTo(String[] args, OptArgs trgt) { for (int i = 0; i < args.length; i++) { OptString s = new OptString(args[i]); if (s.matches("h") || s.matches("help")) { trgt.help = true; } else if (s.matches("version")) { trgt.version = true; } else if (s.matches("name")) { i = s.incrementAndCheck(i, args); trgt.name = args[i]; } else if (s.matches("flatfile")) { i = s.incrementAndCheck(i, args); trgt.flatfile = args[i]; } else if (s.matches("port")) { i = s.incrementAndCheck(i, args); trgt.port = s.parsePort(args[i]); } else if (s.matches("baseport")) { i = s.incrementAndCheck(i, args); trgt.baseport = s.parsePort(args[i]); } else if (s.matches("port_offset")) { i = s.incrementAndCheck(i, args); trgt.port_offset = s.parsePort(args[i]); // port offset has the same properties as a port, we don't allow negative offsets } else if (s.matches("ip")) { i = s.incrementAndCheck(i, args); trgt.ip = args[i]; } else if (s.matches("web_ip")) { i = s.incrementAndCheck(i, args); trgt.web_ip = args[i]; } else if (s.matches("network")) { i = s.incrementAndCheck(i, args); trgt.network = args[i]; } else if (s.matches("client")) { trgt.client = true; } else if (s.matches("allow_clients")) { trgt.allow_clients = true; } else if (s.matches("allow_unsupported_java")) { trgt.allow_unsupported_java = true; } else if (s.matches("rest_api_ping_timeout")) { i = s.incrementAndCheck(i, args); trgt.rest_api_ping_timeout = s.parseInt(args[i]); } else if (s.matches("notify_local")) { i = s.incrementAndCheck(i, args); trgt.notify_local = args[i]; } else if (s.matches("off_heap_memory_ratio")) { i = s.incrementAndCheck(i, args); trgt.off_heap_memory_ratio = Double.parseDouble(args[i]); } else if (s.matches("user_name")) { i = s.incrementAndCheck(i, args); trgt.user_name = args[i]; } else if (s.matches("ice_root")) { i = s.incrementAndCheck(i, args); trgt.ice_root = args[i]; } else if (s.matches("log_dir")) { i = s.incrementAndCheck(i, args); trgt.log_dir = args[i]; } else if (s.matches("flow_dir")) { i = s.incrementAndCheck(i, args); trgt.flow_dir = args[i]; } else if (s.matches("disable_web")) { trgt.disable_web = true; } else if (s.matches("disable_net")) { trgt.disable_net = true; } else if (s.matches("disable_flow")) { trgt.disable_flow = true; } else if (s.matches("context_path")) { i = s.incrementAndCheck(i, args); String value = args[i]; trgt.context_path = value.startsWith("/") ? value.trim().length() == 1 ? "" : value : "/" + value; } else if (s.matches("nthreads")) { i = s.incrementAndCheck(i, args); int nthreads = s.parseInt(args[i]); if (nthreads >= 1) { //otherwise keep default (all cores) if (nthreads > Short.MAX_VALUE) throw H2O.unimpl("Can't handle more than " + Short.MAX_VALUE + " threads."); trgt.nthreads = (short) nthreads; } } else if (s.matches("hdfs_config")) { i = s.incrementAndCheck(i, args); trgt.hdfs_config = ArrayUtils.append(trgt.hdfs_config, args[i]); } else if (s.matches("hdfs_skip")) { trgt.hdfs_skip = true; } else if (s.matches("H")) { i = s.incrementAndCheck(i, args); String key = args[i]; i = s.incrementAndCheck(i, args); String value = args[i]; trgt.hadoop_properties.setProperty(key, value); } else if (s.matches("aws_credentials")) { i = s.incrementAndCheck(i, args); trgt.aws_credentials = args[i]; } else if (s.matches("configure_s3_using_s3a")) { trgt.configure_s3_using_s3a = true; } else if (s.matches("ga_hadoop_ver")) { i = s.incrementAndCheck(i, args); trgt.ga_hadoop_ver = args[i]; } else if (s.matches("ga_opt_out")) { // JUnits pass this as a system property, but it usually a flag without an arg if (i+1 < args.length && args[i+1].equals("yes")) i++; } else if (s.matches("auto_recovery_dir")) { i = s.incrementAndCheck(i, args); trgt.auto_recovery_dir = args[i]; } else if (s.matches("log_level")) { i = s.incrementAndCheck(i, args); trgt.log_level = args[i]; } else if (s.matches("max_log_file_size")) { i = s.incrementAndCheck(i, args); trgt.max_log_file_size = s.checkFileSize(args[i]); } else if (s.matches("random_udp_drop")) { trgt.random_udp_drop = true; } else if (s.matches("md5skip")) { trgt.md5skip = true; } else if (s.matches("quiet")) { trgt.quiet = true; } else if(s.matches("cleaner")) { trgt.cleaner = true; } else if (s.matches("jks")) { i = s.incrementAndCheck(i, args); trgt.jks = args[i]; } else if (s.matches("jks_pass")) { i = s.incrementAndCheck(i, args); trgt.jks_pass = args[i]; } else if (s.matches("jks_alias")) { i = s.incrementAndCheck(i, args); trgt.jks_alias = args[i]; } else if (s.matches("hostname_as_jks_alias")) { trgt.hostname_as_jks_alias = true; } else if (s.matches("hash_login")) { trgt.hash_login = true; } else if (s.matches("ldap_login")) { trgt.ldap_login = true; } else if (s.matches("kerberos_login")) { trgt.kerberos_login = true; } else if (s.matches("spnego_login")) { trgt.spnego_login = true; } else if (s.matches("pam_login")) { trgt.pam_login = true; } else if (s.matches("login_conf")) { i = s.incrementAndCheck(i, args); trgt.login_conf = args[i]; } else if (s.matches("spnego_properties")) { i = s.incrementAndCheck(i, args); trgt.spnego_properties = args[i]; } else if (s.matches("form_auth")) { trgt.form_auth = true; } else if (s.matches("session_timeout")) { i = s.incrementAndCheck(i, args); trgt.session_timeout_spec = args[i]; try { trgt.session_timeout = Integer.parseInt(args[i]); } catch (Exception e) { /* ignored */ } } else if (s.matches("internal_security_conf")) { i = s.incrementAndCheck(i, args); trgt.internal_security_conf = args[i]; } else if (s.matches("internal_security_conf_rel_paths")) { trgt.internal_security_conf_rel_paths = true; } else if (s.matches("allow_insecure_xgboost")) { trgt.allow_insecure_xgboost = true; } else if (s.matches("use_external_xgboost")) { trgt.use_external_xgboost = true; } else if (s.matches("decrypt_tool")) { i = s.incrementAndCheck(i, args); trgt.decrypt_tool = args[i]; } else if (s.matches("principal")) { i = s.incrementAndCheck(i, args); trgt.principal = args[i]; } else if (s.matches("keytab")) { i = s.incrementAndCheck(i, args); trgt.keytab_path = args[i]; } else if (s.matches("hdfs_token_refresh_interval")) { i = s.incrementAndCheck(i, args); trgt.hdfs_token_refresh_interval = args[i]; } else if (s.matches("no_latest_check")) { // ignored Log.trace("Invoked with 'no_latest_check' option (NOOP in current release)."); } else if(s.matches(("client_disconnect_timeout"))){ i = s.incrementAndCheck(i, args); int clientDisconnectTimeout = s.parseInt(args[i]); if (clientDisconnectTimeout <= 0) { throw new IllegalArgumentException("Interval for checking if client is disconnected has to be positive (milliseconds)."); } trgt.clientDisconnectTimeout = clientDisconnectTimeout; } else if (s.matches("useUDP")) { Log.warn("Support for UDP communication was removed from H2O, using TCP."); } else if (s.matches("watchdog_client_retry_timeout")) { warnWatchdogRemoved("watchdog_client_retry_timeout"); } else if (s.matches("watchdog_client")) { warnWatchdogRemoved("watchdog_client"); } else if (s.matches("watchdog_client_connect_timeout")) { warnWatchdogRemoved("watchdog_client_connect_timeout"); } else if (s.matches("watchdog_stop_without_client")) { warnWatchdogRemoved("watchdog_stop_without_client"); } else if (s.matches("features")) { i = s.incrementAndCheck(i, args); trgt.features_level = ModelBuilder.BuilderVisibility.valueOfIgnoreCase(args[i]); Log.info(String.format("Limiting algorithms available to level: %s", trgt.features_level.name())); } else if (s.matches("add_http_header")) { i = s.incrementAndCheck(i, args); String key = args[i]; i = s.incrementAndCheck(i, args); String value = args[i]; trgt.extra_headers = ArrayUtils.append(trgt.extra_headers, new KeyValueArg(key, value)); } else if (s.matches("file_deny_glob")) { i = s.incrementAndCheck(i, args); String key = args[i]; try { trgt.file_deny_glob = FileSystems.getDefault().getPathMatcher("glob:" + key); } catch (Exception e) { throw new IllegalArgumentException("Error parsing file_deny_glob parameter"); } } else if(s.matches("embedded")) { trgt.embedded = true; } else { parseFailed("Unknown argument (" + s + ")"); } } return trgt; } private static void warnWatchdogRemoved(String param) { Log.warn("Support for watchdog client communication was removed and '" + param + "' argument has no longer any effect. " + "It will be removed in the next major release 3.30."); } private static void validateArguments() { if (ARGS.jks != null) { if (! new File(ARGS.jks).exists()) { parseFailed("File does not exist: " + ARGS.jks); } } if (ARGS.jks_alias != null && ARGS.hostname_as_jks_alias) { parseFailed("Options -jks_alias and -hostname_as_jks_alias are mutually exclusive, specify only one of them"); } if (ARGS.login_conf != null) { if (! new File(ARGS.login_conf).exists()) { parseFailed("File does not exist: " + ARGS.login_conf); } } int login_arg_count = 0; if (ARGS.hash_login) login_arg_count++; if (ARGS.ldap_login) login_arg_count++; if (ARGS.kerberos_login) login_arg_count++; if (ARGS.spnego_login) login_arg_count++; if (ARGS.pam_login) login_arg_count++; if (login_arg_count > 1) { parseFailed("Can only specify one of -hash_login, -ldap_login, -kerberos_login, -spnego_login and -pam_login"); } if (ARGS.hash_login || ARGS.ldap_login || ARGS.kerberos_login || ARGS.pam_login || ARGS.spnego_login) { if (H2O.ARGS.login_conf == null) { parseFailed("Must specify -login_conf argument"); } } else { if (H2O.ARGS.form_auth) { parseFailed("No login method was specified. Form-based authentication can only be used in conjunction with of a LoginService.\n" + "Pick a LoginService by specifying '-<method>_login' option."); } } if (ARGS.spnego_login) { if (H2O.ARGS.spnego_properties == null) { parseFailed("Must specify -spnego_properties argument"); } if (H2O.ARGS.form_auth) { parseFailed("Form-based authentication not supported when SPNEGO login is enabled."); } } if (ARGS.session_timeout_spec != null) { if (! ARGS.form_auth) { parseFailed("Session timeout can only be enabled for Form based authentication (use -form_auth)"); } if (ARGS.session_timeout <= 0) parseFailed("Invalid session timeout specification (" + ARGS.session_timeout + ")"); } if (ARGS.rest_api_ping_timeout < 0) { parseFailed(String.format("rest_api_ping_timeout needs to be 0 or higher, was (%d)", ARGS.rest_api_ping_timeout)); } // Validate extension arguments for (AbstractH2OExtension e : extManager.getCoreExtensions()) { e.validateArguments(); } } //------------------------------------------------------------------------------------------------------------------- // Embedded configuration for a full H2O node to be implanted in another // piece of software (e.g. Hadoop mapper task). //------------------------------------------------------------------------------------------------------------------- public static volatile AbstractEmbeddedH2OConfig embeddedH2OConfig; /** * Register embedded H2O configuration object with H2O instance. */ public static void setEmbeddedH2OConfig(AbstractEmbeddedH2OConfig c) { embeddedH2OConfig = c; } /** * Returns an instance of {@link AbstractEmbeddedH2OConfig}. The origin of the embedded config might be either * from directly setting the embeddedH2OConfig field via setEmbeddedH2OConfig setter, or dynamically provided via * service loader. Directly set {@link AbstractEmbeddedH2OConfig} is always prioritized. ServiceLoader lookup is only * performed if no config is previously set. * <p> * Result of first ServiceLoader lookup is also considered final - once a service is found, dynamic lookup is not * performed any further. * * @return An instance of {@link AbstractEmbeddedH2OConfig}, if set or dynamically provided. Otherwise null * @author Michal Kurka */ public static AbstractEmbeddedH2OConfig getEmbeddedH2OConfig() { if (embeddedH2OConfig != null) { return embeddedH2OConfig; } embeddedH2OConfig = discoverEmbeddedConfigProvider() .map(embeddedConfigProvider -> { Log.info(String.format("Dynamically loaded '%s' as AbstractEmbeddedH2OConfigProvider.", embeddedConfigProvider.getName())); return embeddedConfigProvider.getConfig(); }).orElse(null); return embeddedH2OConfig; } /** * Uses {@link ServiceLoader} to discover active instances of {@link EmbeddedConfigProvider}. Only one provider * may be active at a time. If more providers are detected, {@link IllegalStateException} is thrown. * * @return An {@link Optional} of {@link EmbeddedConfigProvider}, if a single active provider is found. Otherwise * an empty optional. * @throws IllegalStateException When there are multiple active instances {@link EmbeddedConfigProvider} discovered. */ private static Optional<EmbeddedConfigProvider> discoverEmbeddedConfigProvider() throws IllegalStateException { final ServiceLoader<EmbeddedConfigProvider> configProviders = ServiceLoader.load(EmbeddedConfigProvider.class); EmbeddedConfigProvider provider = null; for (final EmbeddedConfigProvider candidateProvider : configProviders) { candidateProvider.init(); if (!candidateProvider.isActive()) continue; if (provider != null) { throw new IllegalStateException("Multiple active EmbeddedH2OConfig providers: " + provider.getName() + " and " + candidateProvider.getName() + " (possibly other as well)."); } provider = candidateProvider; } return Optional.ofNullable(provider); } /** * Tell the embedding software that this H2O instance belongs to * a cloud of a certain size. * This may be non-blocking. * * @param ip IP address this H2O can be reached at. * @param port Port this H2O can be reached at (for REST API and browser). * @param size Number of H2O instances in the cloud. */ public static void notifyAboutCloudSize(InetAddress ip, int port, InetAddress leaderIp, int leaderPort, int size) { if (ARGS.notify_local != null && !ARGS.notify_local.trim().isEmpty()) { final File notifyFile = new File(ARGS.notify_local); final File parentDir = notifyFile.getParentFile(); if (parentDir != null && !parentDir.isDirectory()) { if (!parentDir.mkdirs()) { Log.err("Cannot make parent dir for notify file."); H2O.exit(-1); } } try(BufferedWriter output = new BufferedWriter(new FileWriter(notifyFile))) { output.write(SELF_ADDRESS.getHostAddress()); output.write(':'); output.write(Integer.toString(API_PORT)); output.flush(); } catch (IOException e) { Log.err("Unable to write notify file."); H2O.exit(-1); } } if (embeddedH2OConfig != null) { embeddedH2OConfig.notifyAboutCloudSize(ip, port, leaderIp, leaderPort, size); } } public static void closeAll() { try { H2O.getWebServer().stop(); } catch( Exception ignore ) { } try { NetworkInit.close(); } catch( IOException ignore ) { } PersistManager PM = H2O.getPM(); if( PM != null ) PM.getIce().cleanUp(); } /** Notify embedding software instance H2O wants to exit. Shuts down a single Node. * @param status H2O's requested process exit value. */ public static void exit(int status) { // Log subsystem might be still caching message, let it know to flush the cache and start logging even if we don't have SELF yet Log.notifyAboutProcessExiting(); exitQuietly(status); } /** * Notify embedding software instance H2O wants to exit. Shuts down a single Node. * Exit without logging any buffered messages, invoked when H2O arguments are not correctly parsed * and we might thus not be able to successfully initialize the logging subsystem. * * @param status H2O's requested process exit value. */ private static void exitQuietly(int status) { // Embedded H2O path (e.g. inside Hadoop mapper task). if( embeddedH2OConfig != null ) embeddedH2OConfig.exit(status); // Standalone H2O path,p or if the embedded config does not exit System.exit(status); } /** Cluster shutdown itself by sending a shutdown UDP packet. */ public static void shutdown(int status) { if(status == 0) H2O.orderlyShutdown(); UDPRebooted.T.error.send(H2O.SELF); H2O.exit(status); } /** Orderly shutdown with infinite timeout for confirmations from the nodes in the cluster */ public static int orderlyShutdown() { return orderlyShutdown(-1); } public static int orderlyShutdown(int timeout) { boolean [] confirmations = new boolean[H2O.CLOUD.size()]; if (H2O.SELF.index() >= 0) { // Do not wait for clients to shutdown confirmations[H2O.SELF.index()] = true; } Futures fs = new Futures(); for(H2ONode n:H2O.CLOUD._memary) { if(n != H2O.SELF) fs.add(new RPC(n, new ShutdownTsk(H2O.SELF,n.index(), 1000, confirmations, 0)).call()); } if(timeout > 0) try { Thread.sleep(timeout); } catch (Exception ignore) {} else fs.blockForPending(); // todo, should really have block for pending with a timeout int failedToShutdown = 0; // shutdown failed for(boolean b:confirmations) if(!b) failedToShutdown++; return failedToShutdown; } private static volatile boolean _shutdownRequested = false; public static void requestShutdown() { _shutdownRequested = true; } public static boolean getShutdownRequested() { return _shutdownRequested; } //------------------------------------------------------------------------------------------------------------------- public static final AbstractBuildVersion ABV = AbstractBuildVersion.getBuildVersion(); //------------------------------------------------------------------------------------------------------------------- private static boolean _haveInheritedLog4jConfiguration = false; public static boolean haveInheritedLog4jConfiguration() { return _haveInheritedLog4jConfiguration; } public static void configureLogging() { if (LogManager.getCurrentLoggers().hasMoreElements()) { _haveInheritedLog4jConfiguration = true; return; } else if (System.getProperty("log4j.configuration") != null) { _haveInheritedLog4jConfiguration = true; return; } // Disable logging from a few specific classes at startup. // (These classes may (or may not) be re-enabled later on.) // // The full logger initialization is done by setLog4jProperties() in class water.util.Log. // The trick is the output path / file isn't known until the H2O API PORT is chosen, // so real logger initialization has to happen somewhat late in the startup lifecycle. java.util.Properties p = new java.util.Properties(); p.setProperty("log4j.rootCategory", "WARN, console"); p.setProperty("log4j.logger.org.eclipse.jetty", "WARN"); p.setProperty("log4j.appender.console", "org.apache.log4j.ConsoleAppender"); p.setProperty("log4j.appender.console.layout", "org.apache.log4j.PatternLayout"); p.setProperty("log4j.appender.console.layout.ConversionPattern", "%m%n"); PropertyConfigurator.configure(p); System.setProperty("org.eclipse.jetty.LEVEL", "WARN"); // Log jetty stuff to stdout for now. // TODO: figure out how to wire this into log4j. System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog"); } //------------------------------------------------------------------------------------------------------------------- public static class AboutEntry { private String name; private String value; public String getName() { return name; } public String getValue() { return value; } AboutEntry(String n, String v) { name = n; value = v; } } private static ArrayList<AboutEntry> aboutEntries = new ArrayList<>(); @SuppressWarnings("unused") public static void addAboutEntry(String name, String value) { AboutEntry e = new AboutEntry(name, value); aboutEntries.add(e); } @SuppressWarnings("unused") public static ArrayList<AboutEntry> getAboutEntries() { return aboutEntries; } //------------------------------------------------------------------------------------------------------------------- private static final AtomicLong nextModelNum = new AtomicLong(0); /** * Calculate a unique model id that includes User-Agent info (if it can be discovered). * For the user agent info to be discovered, this needs to be called from a Jetty thread. * * This lets us distinguish models created from R vs. other front-ends, for example. * At some future point, it could make sense to include a sessionId here. * * The algorithm is: * descModel_[userAgentPrefixIfKnown_]cloudId_monotonicallyIncreasingInteger * * Right now because of the way the REST API works, a bunch of numbers are created and * thrown away. So the values are monotonically increasing but not contiguous. * * @param desc Model description. * @return The suffix. */ public static String calcNextUniqueModelId(String desc) { return calcNextUniqueObjectId("model", nextModelNum, desc); } synchronized public static String calcNextUniqueObjectId(String type, AtomicLong sequenceSource, String desc) { StringBuilder sb = new StringBuilder(); sb.append(desc).append('_').append(type).append('_'); // Append user agent string if we can figure it out. String source = ServletUtils.getUserAgent(); if (source != null) { StringBuilder ua = new StringBuilder(); if (source.contains("Safari")) { ua.append("safari"); } else if (source.contains("Python")) { ua.append("python"); } else { for (int i = 0; i < source.length(); i++) { char c = source.charAt(i); if (c >= 'a' && c <= 'z') { ua.append(c); continue; } else if (c >= 'A' && c <= 'Z') { ua.append(c); continue; } break; } } if (ua.toString().length() > 0) { sb.append(ua.toString()).append("_"); } } // REST API needs some refactoring to avoid burning lots of extra numbers. // // I actually tried only doing the addAndGet only for POST requests (and junk UUID otherwise), // but that didn't eliminate the gaps. long n = sequenceSource.addAndGet(1); sb.append(CLUSTER_ID).append("_").append(n); return sb.toString(); } //------------------------------------------------------------------------------------------------------------------- // This piece of state is queried by Steam. // It's used to inform the Admin user the last time each H2O instance did something. // Admins can take this information and decide whether to kill idle clusters to reclaim tied up resources. private static volatile long lastTimeSomethingHappenedMillis = System.currentTimeMillis(); private static volatile AtomicInteger activeRapidsExecs = new AtomicInteger(); /** * Get the number of milliseconds the H2O cluster has been idle. * @return milliseconds since the last interesting thing happened. */ public static long getIdleTimeMillis() { long latestEndTimeMillis = -1; // If there are any running rapids queries, consider that not idle. if (activeRapidsExecs.get() > 0) { updateNotIdle(); } else { // If there are any running jobs, consider that not idle. // Remember the latest job ending time as well. Job[] jobs = Job.jobs(); for (int i = jobs.length - 1; i >= 0; i--) { Job j = jobs[i]; if (j.isRunning()) { updateNotIdle(); break; } if (j.end_time() > latestEndTimeMillis) { latestEndTimeMillis = j.end_time(); } } } long latestTimeMillis = Math.max(latestEndTimeMillis, lastTimeSomethingHappenedMillis); // Calculate milliseconds and clamp at zero. long now = System.currentTimeMillis(); long deltaMillis = now - latestTimeMillis; if (deltaMillis < 0) { deltaMillis = 0; } return deltaMillis; } /** * Update the last time that something happened to reset the idle timer. * This is meant to be callable safely from almost anywhere. */ public static void updateNotIdle() { lastTimeSomethingHappenedMillis = System.currentTimeMillis(); } /** * Increment the current number of active Rapids exec calls. */ public static void incrementActiveRapidsCounter() { updateNotIdle(); activeRapidsExecs.incrementAndGet(); } /** * Decrement the current number of active Rapids exec calls. */ public static void decrementActiveRapidsCounter() { updateNotIdle(); activeRapidsExecs.decrementAndGet(); } //------------------------------------------------------------------------------------------------------------------- // Atomically set once during startup. Guards against repeated startups. public static final AtomicLong START_TIME_MILLIS = new AtomicLong(); // When did main() run // Used to gate default worker threadpool sizes public static final int NUMCPUS = H2ORuntime.availableProcessors(); // Best-guess process ID public static final long PID; static { PID = getCurrentPID(); } // Extension Manager instance private static final ExtensionManager extManager = ExtensionManager.getInstance(); /** * Retrieves a value of an H2O system property. * * H2O system properties have {@link OptArgs#SYSTEM_PROP_PREFIX} prefix. * * @param name property name * @param def default value * @return value of the system property or default value if property was not defined */ public static String getSysProperty(String name, String def) { return System.getProperty(H2O.OptArgs.SYSTEM_PROP_PREFIX + name, def); } /** * Retrieves a boolean value of an H2O system property. * * H2O system properties have {@link OptArgs#SYSTEM_PROP_PREFIX} prefix. * * @param name property name * @param def default value * @return value of the system property as boolean or default value if property was not defined. False returned if * the system property value is set but it is not "true" or any upper/lower case variant of it. */ public static boolean getSysBoolProperty(String name, boolean def) { return Boolean.parseBoolean(getSysProperty(name, String.valueOf(def))); } /** * Throw an exception that will cause the request to fail, but the cluster to continue. * @see #fail(String, Throwable) * @return never returns */ public static H2OIllegalArgumentException unimpl() { return new H2OIllegalArgumentException("unimplemented"); } /** * Throw an exception that will cause the request to fail, but the cluster to continue. * @see #unimpl(String) * @see #fail(String, Throwable) * @return never returns */ public static H2OIllegalArgumentException unimpl(String msg) { return new H2OIllegalArgumentException("unimplemented: " + msg); } /** * H2O.fail is intended to be used in code where something should never happen, and if * it does it's a coding error that needs to be addressed immediately. Examples are: * AutoBuffer serialization for an object you're trying to serialize isn't available; * there's a typing error on your schema; your switch statement didn't cover all the AstRoot * subclasses available in Rapids. * <p> * It should *not* be used when only the single request should fail, it should *only* be * used if the error means that someone needs to go add some code right away. * * @param msg Message to Log.fatal() * @param cause Optional cause exception to Log.fatal() * @return never returns; calls System.exit(-1) */ public static H2OFailException fail(String msg, Throwable cause) { Log.fatal(msg); if (null != cause) Log.fatal(cause); Log.fatal("Stacktrace: "); Log.fatal(new Exception(msg)); // H2O fail() exists because of coding errors - but what if usage of fail() was itself a coding error? // Property "suppress.shutdown.on.failure" can be used in the case when someone is seeing shutdowns on production // because a developer incorrectly used fail() instead of just throwing a (recoverable) exception boolean suppressShutdown = getSysBoolProperty("suppress.shutdown.on.failure", false); if (! suppressShutdown) { H2O.shutdown(-1); } else { throw new IllegalStateException("Suppressed shutdown for failure: " + msg, cause); } // unreachable return new H2OFailException(msg); } /** * @see #fail(String, Throwable) * @return never returns */ public static H2OFailException fail() { return H2O.fail("Unknown code failure"); } /** * @see #fail(String, Throwable) * @return never returns */ public static H2OFailException fail(String msg) { return H2O.fail(msg, null); } /** * Return an error message with an accompanying URL to help the user get more detailed information. * * @param number H2O tech note number. * @param message Message to present to the user. * @return A longer message including a URL. */ public static String technote(int number, String message) { return message + "\n\n" + "For more information visit:\n" + " https://github.com/h2oai/h2o-3/discussions/" + GITHUB_DISCUSSIONS.get(number); } /** * Return an error message with an accompanying list of URLs to help the user get more detailed information. * * @param numbers H2O tech note numbers. * @param message Message to present to the user. * @return A longer message including a list of URLs. */ public static String technote(int[] numbers, String message) { StringBuilder sb = new StringBuilder() .append(message) .append("\n") .append("\n") .append("For more information visit:\n"); for (int number : numbers) { sb.append(" https://github.com/h2oai/h2o-3/discussions/").append(GITHUB_DISCUSSIONS.get(number)).append("\n"); } return sb.toString(); } // -------------------------------------------------------------------------- // The worker pools - F/J pools with different priorities. // These priorities are carefully ordered and asserted for... modify with // care. The real problem here is that we can get into cyclic deadlock // unless we spawn a thread of priority "X+1" in order to allow progress // on a queue which might be flooded with a large number of "<=X" tasks. // // Example of deadlock: suppose TaskPutKey and the Invalidate ran at the same // priority on a 2-node cluster. Both nodes flood their own queues with // writes to unique keys, which require invalidates to run on the other node. // Suppose the flooding depth exceeds the thread-limit (e.g. 99); then each // node might have all 99 worker threads blocked in TaskPutKey, awaiting // remote invalidates - but the other nodes' threads are also all blocked // awaiting invalidates! // // We fix this by being willing to always spawn a thread working on jobs at // priority X+1, and guaranteeing there are no jobs above MAX_PRIORITY - // i.e., jobs running at MAX_PRIORITY cannot block, and when those jobs are // done, the next lower level jobs get unblocked, etc. public static final byte MAX_PRIORITY = Byte.MAX_VALUE-1; public static final byte ACK_ACK_PRIORITY = MAX_PRIORITY; //126 public static final byte FETCH_ACK_PRIORITY = MAX_PRIORITY-1; //125 public static final byte ACK_PRIORITY = MAX_PRIORITY-2; //124 public static final byte DESERIAL_PRIORITY = MAX_PRIORITY-3; //123 public static final byte INVALIDATE_PRIORITY = MAX_PRIORITY-3; //123 public static final byte GET_KEY_PRIORITY = MAX_PRIORITY-4; //122 public static final byte PUT_KEY_PRIORITY = MAX_PRIORITY-5; //121 public static final byte ATOMIC_PRIORITY = MAX_PRIORITY-6; //120 public static final byte GUI_PRIORITY = MAX_PRIORITY-7; //119 public static final byte MIN_HI_PRIORITY = MAX_PRIORITY-7; //119 public static final byte MIN_PRIORITY = 0; // F/J threads that remember the priority of the last task they started // working on. // made public for ddply public static class FJWThr extends ForkJoinWorkerThread { public int _priority; FJWThr(ForkJoinPool pool) { super(pool); _priority = ((PrioritizedForkJoinPool)pool)._priority; setPriority( _priority == Thread.MIN_PRIORITY ? Thread.NORM_PRIORITY-1 : Thread. MAX_PRIORITY-1 ); setName("FJ-"+_priority+"-"+getPoolIndex()); } } // Factory for F/J threads, with cap's that vary with priority. static class FJWThrFact implements ForkJoinPool.ForkJoinWorkerThreadFactory { private final int _cap; FJWThrFact( int cap ) { _cap = cap; } @Override public ForkJoinWorkerThread newThread(ForkJoinPool pool) { int cap = _cap==-1 ? 4 * NUMCPUS : _cap; return pool.getPoolSize() <= cap ? new FJWThr(pool) : null; } } // A standard FJ Pool, with an expected priority level. private static class PrioritizedForkJoinPool extends ForkJoinPool { final int _priority; private PrioritizedForkJoinPool(int p, int cap) { super((ARGS.nthreads <= 0) ? NUMCPUS : ARGS.nthreads, new FJWThrFact(cap), null, p>=MIN_HI_PRIORITY /* low priority FJQs should use the default FJ settings to use LIFO order of thread private queues. */); _priority = p; } private H2OCountedCompleter poll2() { return (H2OCountedCompleter)pollSubmission(); } } // Hi-priority work, sorted into individual queues per-priority. // Capped at a small number of threads per pool. private static final PrioritizedForkJoinPool FJPS[] = new PrioritizedForkJoinPool[MAX_PRIORITY+1]; static { // Only need 1 thread for the AckAck work, as it cannot block FJPS[ACK_ACK_PRIORITY] = new PrioritizedForkJoinPool(ACK_ACK_PRIORITY,1); for( int i=MIN_HI_PRIORITY+1; i<MAX_PRIORITY; i++ ) FJPS[i] = new PrioritizedForkJoinPool(i,4); // All CPUs, but no more for blocking purposes FJPS[GUI_PRIORITY] = new PrioritizedForkJoinPool(GUI_PRIORITY,2); } // Easy peeks at the FJ queues static int getWrkQueueSize (int i) { return FJPS[i]==null ? -1 : FJPS[i].getQueuedSubmissionCount();} static int getWrkThrPoolSize(int i) { return FJPS[i]==null ? -1 : FJPS[i].getPoolSize(); } // For testing purposes (verifying API work exceeds grunt model-build work) // capture the class of any submitted job lower than this priority; static public int LOW_PRIORITY_API_WORK; static public String LOW_PRIORITY_API_WORK_CLASS; // Submit to the correct priority queue public static <T extends H2OCountedCompleter> T submitTask( T task ) { int priority = task.priority(); if( priority < LOW_PRIORITY_API_WORK ) LOW_PRIORITY_API_WORK_CLASS = task.getClass().toString(); assert MIN_PRIORITY <= priority && priority <= MAX_PRIORITY:"priority " + priority + " is out of range, expected range is < " + MIN_PRIORITY + "," + MAX_PRIORITY + ">"; if( FJPS[priority]==null ) synchronized( H2O.class ) { if( FJPS[priority] == null ) FJPS[priority] = new PrioritizedForkJoinPool(priority,-1); } FJPS[priority].submit(task); return task; } /** * Executes a runnable on a regular H2O Node (= not on a client). * If the current H2O Node is a regular node, the runnable will be executed directly (RemoteRunnable#run will be invoked). * If the current H2O Node is a client node, the runnable will be send to a leader node of the cluster and executed there. * The caller shouldn't make any assumptions on where the code will be run. * @param runnable code to be executed * @param <T> RemoteRunnable * @return executed runnable (will be a different instance if executed remotely). */ public static <T extends RemoteRunnable> T runOnH2ONode(T runnable) { H2ONode node = H2O.ARGS.client ? H2O.CLOUD.leader() : H2O.SELF; return runOnH2ONode(node, runnable); } public static <T extends RemoteRunnable> T runOnLeaderNode(T runnable) { return runOnH2ONode(H2O.CLOUD.leader(), runnable); } // package-private for unit tests static <T extends RemoteRunnable> T runOnH2ONode(H2ONode node, T runnable) { if (node == H2O.SELF) { // run directly runnable.run(); return runnable; } else { RunnableWrapperTask<T> task = new RunnableWrapperTask<>(runnable); try { return new RPC<>(node, task).call().get()._runnable; } catch (DistributedException e) { Log.trace("Exception in calling runnable on a remote node", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : e; } } } private static class RunnableWrapperTask<T extends RemoteRunnable> extends DTask<RunnableWrapperTask<T>> { private final T _runnable; private RunnableWrapperTask(T runnable) { _runnable = runnable; } @Override public void compute2() { _runnable.setupOnRemote(); _runnable.run(); tryComplete(); } } public abstract static class RemoteRunnable<T extends RemoteRunnable> extends Iced<T> { public void setupOnRemote() {} public abstract void run(); } /** Simple wrapper over F/J {@link CountedCompleter} to support priority * queues. F/J queues are simple unordered (and extremely light weight) * queues. However, we frequently need priorities to avoid deadlock and to * promote efficient throughput (e.g. failure to respond quickly to {@link * TaskGetKey} can block an entire node for lack of some small piece of * data). So each attempt to do lower-priority F/J work starts with an * attempt to work and drain the higher-priority queues. */ public static abstract class H2OCountedCompleter<T extends H2OCountedCompleter> extends CountedCompleter implements Cloneable, Freezable<T> { @Override public byte [] asBytes(){return new AutoBuffer().put(this).buf();} @Override public T reloadFromBytes(byte [] ary){ return read(new AutoBuffer(ary));} private /*final*/ byte _priority; // Without a completer, we expect this task will be blocked on - so the // blocking thread is not available in the current thread pool, so the // launched task needs to run at a higher priority. public H2OCountedCompleter( ) { this(null); } // With a completer, this task will NOT be blocked on and the the current // thread is available for executing it... so the priority can remain at // the current level. static private byte computePriority( H2OCountedCompleter completer ) { int currThrPrior = currThrPriority(); // If there's no completer, then current thread will block on this task // at the current priority, possibly filling up the current-priority // thread pool - so the task has to run at the next higher priority. if( completer == null ) return (byte)(currThrPrior+1); // With a completer - no thread blocks on this task, so no thread pool // gets filled-up with blocked threads. We can run at the current // priority (or the completer's priority if it's higher). return (byte)Math.max(currThrPrior,completer.priority()); } protected H2OCountedCompleter(H2OCountedCompleter completer) { this(completer,computePriority(completer)); } // Special for picking GUI priorities protected H2OCountedCompleter( byte prior ) { this(null,prior); } protected H2OCountedCompleter(H2OCountedCompleter completer, byte prior) { super(completer); _priority = prior; } /** Used by the F/J framework internally to do work. Once per F/J task, * drain the high priority queue before doing any low priority work. * Calls {@link #compute2} which contains actual work. */ @Override public final void compute() { FJWThr t = (FJWThr)Thread.currentThread(); int pp = ((PrioritizedForkJoinPool)t.getPool())._priority; // Drain the high priority queues before the normal F/J queue H2OCountedCompleter h2o = null; boolean set_t_prior = false; try { assert priority() == pp:" wrong priority for task " + getClass().getSimpleName() + ", expected " + priority() + ", but got " + pp; // Job went to the correct queue? assert t._priority <= pp; // Thread attempting the job is only a low-priority? final int p2 = Math.max(pp,MIN_HI_PRIORITY); for( int p = MAX_PRIORITY; p > p2; p-- ) { if( FJPS[p] == null ) continue; h2o = FJPS[p].poll2(); if( h2o != null ) { // Got a hi-priority job? t._priority = p; // Set & do it now! t.setPriority(Thread.MAX_PRIORITY-1); set_t_prior = true; h2o.compute2(); // Do it ahead of normal F/J work p++; // Check again the same queue } } } catch( Throwable ex ) { // If the higher priority job popped an exception, complete it // exceptionally... but then carry on and do the lower priority job. if( h2o != null ) h2o.completeExceptionally(ex); else { ex.printStackTrace(); throw ex; } } finally { t._priority = pp; if( pp == MIN_PRIORITY && set_t_prior ) t.setPriority(Thread.NORM_PRIORITY-1); } // Now run the task as planned if( this instanceof DTask ) icer().compute1(this); else compute2(); } public void compute1() { compute2(); } /** Override compute3() with actual work without having to worry about tryComplete() */ public void compute2() {} // In order to prevent deadlock, threads that block waiting for a reply // from a remote node, need the remote task to run at a higher priority // than themselves. This field tracks the required priority. protected final byte priority() { return _priority; } @Override public final T clone(){ try { return (T)super.clone(); } catch( CloneNotSupportedException e ) { throw Log.throwErr(e); } } /** If this is a F/J thread, return it's priority - used to lift the * priority of a blocking remote call, so the remote node runs it at a * higher priority - so we don't deadlock when we burn the local * thread. */ protected static byte currThrPriority() { Thread cThr = Thread.currentThread(); return (byte)((cThr instanceof FJWThr) ? ((FJWThr)cThr)._priority : MIN_PRIORITY); } // The serialization flavor / delegate. Lazily set on first use. private short _ice_id; /** Find the serialization delegate for a subclass of this class */ protected Icer<T> icer() { int id = _ice_id; if(id != 0) { int tyid; if (id != 0) assert id == (tyid = TypeMap.onIce(this)) : "incorrectly cashed id " + id + ", typemap has " + tyid + ", type = " + getClass().getName(); } return TypeMap.getIcer(id!=0 ? id : (_ice_id=(short)TypeMap.onIce(this)),this); } @Override final public AutoBuffer write (AutoBuffer ab) { return icer().write (ab,(T)this); } @Override final public AutoBuffer writeJSON(AutoBuffer ab) { return icer().writeJSON(ab,(T)this); } @Override final public T read (AutoBuffer ab) { return icer().read (ab,(T)this); } @Override final public T readJSON(AutoBuffer ab) { return icer().readJSON(ab,(T)this); } @Override final public int frozenType() { return icer().frozenType(); } } public static abstract class H2OCallback<T extends H2OCountedCompleter> extends H2OCountedCompleter{ public H2OCallback(){} public H2OCallback(H2OCountedCompleter cc){super(cc);} @Override public void compute2(){throw H2O.fail();} @Override public void onCompletion(CountedCompleter caller){callback((T) caller);} public abstract void callback(T t); } public static int H2O_PORT; // H2O TCP Port public static int API_PORT; // RequestServer and the API HTTP port /** * @return String of the form ipaddress:port */ public static String getIpPortString() { return H2O.ARGS.disable_web? "" : H2O.SELF_ADDRESS.getHostAddress() + ":" + H2O.API_PORT; } public static String getURL(String schema) { return getURL(schema, H2O.SELF_ADDRESS, H2O.API_PORT, H2O.ARGS.context_path); } public static String getURL(String schema, InetAddress address, int port, String contextPath) { return String.format(address instanceof Inet6Address ? "%s://[%s]:%d%s" : "%s://%s:%d%s", schema, address.getHostAddress(), port, contextPath); } public static String getURL(String schema, String hostname, int port, String contextPath) { return String.format("%s://%s:%d%s", schema, hostname, port, contextPath); } // The multicast discovery port public static MulticastSocket CLOUD_MULTICAST_SOCKET; public static NetworkInterface CLOUD_MULTICAST_IF; public static InetAddress CLOUD_MULTICAST_GROUP; public static int CLOUD_MULTICAST_PORT ; /** Myself, as a Node in the Cloud */ public static H2ONode SELF = null; /** IP address of this node used for communication * with other nodes. */ public static InetAddress SELF_ADDRESS; /* Global flag to mark this specific cloud instance IPv6 only. * Right now, users have to force IPv6 stack by specifying the following * JVM options: * -Djava.net.preferIPv6Addresses=true * -Djava.net.preferIPv6Addresses=false */ static final boolean IS_IPV6 = NetworkUtils.isIPv6Preferred() && !NetworkUtils.isIPv4Preferred(); // Place to store temp/swap files public static URI ICE_ROOT; public static String DEFAULT_ICE_ROOT() { String username = System.getProperty("user.name"); if (username == null) username = ""; String u2 = username.replaceAll(" ", "_"); if (u2.length() == 0) u2 = "unknown"; return "/tmp/h2o-" + u2; } // Place to store flows public static String DEFAULT_FLOW_DIR() { String flow_dir = null; try { if (ARGS.ga_hadoop_ver != null) { PersistManager pm = getPM(); if (pm != null) { String s = pm.getHdfsHomeDirectory(); if (pm.exists(s)) { flow_dir = s; } } if (flow_dir != null) { flow_dir = flow_dir + "/h2oflows"; } } else { flow_dir = System.getProperty("user.home") + File.separator + "h2oflows"; } } catch (Exception ignore) { // Never want this to fail, as it will kill program startup. // Returning null is fine if it fails for whatever reason. } return flow_dir; } /* A static list of acceptable Cloud members passed via -flatfile option. * It is updated also when a new client appears. */ private static Set<H2ONode> STATIC_H2OS = null; // Reverse cloud index to a cloud; limit of 256 old clouds. static private final H2O[] CLOUDS = new H2O[256]; // Enables debug features like more logging and multiple instances per JVM static final String DEBUG_ARG = "h2o.debug"; static final boolean DEBUG = System.getProperty(DEBUG_ARG) != null; // Returned in REST API responses as X-h2o-cluster-id. // // Currently this is unique per node. Might make sense to distribute this // as part of joining the cluster so all nodes have the same value. public static final long CLUSTER_ID = System.currentTimeMillis(); private static WebServer webServer; public static void setWebServer(WebServer value) { webServer = value; } public static WebServer getWebServer() { return webServer; } /** If logging has not been setup yet, then Log.info will only print to * stdout. This allows for early processing of the '-version' option * without unpacking the jar file and other startup stuff. */ private static void printAndLogVersion(String[] arguments) { Log.init(ARGS.log_level, ARGS.quiet, ARGS.max_log_file_size); Log.info("----- H2O started " + (ARGS.client?"(client)":"") + " -----"); Log.info("Build git branch: " + ABV.branchName()); Log.info("Build git hash: " + ABV.lastCommitHash()); Log.info("Build git describe: " + ABV.describe()); Log.info("Build project version: " + ABV.projectVersion()); Log.info("Build age: " + PrettyPrint.toAge(ABV.compiledOnDate(), new Date())); Log.info("Built by: '" + ABV.compiledBy() + "'"); Log.info("Built on: '" + ABV.compiledOn() + "'"); if (ABV.isTooOld()) { Log.warn("\n*** Your H2O version is over 100 days old. Please download the latest version from: https://h2o-release.s3.amazonaws.com/h2o/latest_stable.html ***"); Log.warn(""); } Log.info("Found H2O Core extensions: " + extManager.getCoreExtensions()); Log.info("Processed H2O arguments: ", Arrays.toString(arguments)); Runtime runtime = Runtime.getRuntime(); Log.info("Java availableProcessors: " + H2ORuntime.availableProcessors()); Log.info("Java heap totalMemory: " + PrettyPrint.bytes(runtime.totalMemory())); Log.info("Java heap maxMemory: " + PrettyPrint.bytes(runtime.maxMemory())); Log.info("Java version: Java "+System.getProperty("java.version")+" (from "+System.getProperty("java.vendor")+")"); List<String> launchStrings = ManagementFactory.getRuntimeMXBean().getInputArguments(); Log.info("JVM launch parameters: "+launchStrings); Log.info("JVM process id: " + ManagementFactory.getRuntimeMXBean().getName()); Log.info("OS version: "+System.getProperty("os.name")+" "+System.getProperty("os.version")+" ("+System.getProperty("os.arch")+")"); long totalMemory = OSUtils.getTotalPhysicalMemory(); Log.info ("Machine physical memory: " + (totalMemory==-1 ? "NA" : PrettyPrint.bytes(totalMemory))); Log.info("Machine locale: " + Locale.getDefault()); } /** Initializes the local node and the local cloud with itself as the only member. */ private static void startLocalNode() { // Figure self out; this is surprisingly hard NetworkInit.initializeNetworkSockets(); // Do not forget to put SELF into the static configuration (to simulate proper multicast behavior) if ( !ARGS.client && H2O.isFlatfileEnabled() && !H2O.isNodeInFlatfile(SELF)) { Log.warn("Flatfile configuration does not include self: " + SELF + ", but contains " + H2O.getFlatfile()); H2O.addNodeToFlatfile(SELF); } if (!H2O.ARGS.disable_net) { Log.info("H2O cloud name: '" + ARGS.name + "' on " + SELF + (H2O.isFlatfileEnabled() ? ", static configuration based on -flatfile " + ARGS.flatfile : (", discovery address " + CLOUD_MULTICAST_GROUP + ":" + CLOUD_MULTICAST_PORT))); } if (!H2O.ARGS.disable_web) { Log.info("If you have trouble connecting, try SSH tunneling from your local machine (e.g., via port 55555):\n" + " 1. Open a terminal and run 'ssh -L 55555:localhost:" + API_PORT + " " + System.getProperty("user.name") + "@" + SELF_ADDRESS.getHostAddress() + "'\n" + " 2. Point your browser to " + NetworkInit.h2oHttpView.getScheme() + "://localhost:55555"); } if (H2O.ARGS.rest_api_ping_timeout > 0) { Log.info(String.format("Registering REST API Check Thread. If 3/Ping endpoint is not" + " accessed during %d ms, the cluster will be terminated.", H2O.ARGS.rest_api_ping_timeout)); new RestApiPingCheckThread().start(); } // Create the starter Cloud with 1 member SELF._heartbeat._jar_md5 = JarHash.JARHASH; SELF._heartbeat._client = ARGS.client; SELF._heartbeat._cloud_name_hash = ARGS.name.hashCode(); } /** Starts the worker threads, receiver threads, heartbeats and all other * network related services. */ private static void startNetworkServices() { // Start the Persistent meta-data cleaner thread, which updates the K/V // mappings periodically to disk. There should be only 1 of these, and it // never shuts down. Needs to start BEFORE the HeartBeatThread to build // an initial histogram state. Cleaner.THE_CLEANER.start(); if (H2O.ARGS.disable_net) return; // We've rebooted the JVM recently. Tell other Nodes they can ignore task // prior tasks by us. Do this before we receive any packets UDPRebooted.T.reboot.broadcast(); // Start the MultiReceiverThread, to listen for multi-cast requests from // other Cloud Nodes. There should be only 1 of these, and it never shuts // down. Started soon, so we can start parsing multi-cast UDP packets new MultiReceiverThread().start(); // Start the TCPReceiverThread, to listen for TCP requests from other Cloud // Nodes. There should be only 1 of these, and it never shuts down. NetworkInit.makeReceiverThread().start(); } @Deprecated static public void register( String method_url, Class<? extends water.api.Handler> hclass, String method, String apiName, String summary ) { Log.warn("The H2O.register method is deprecated and will be removed in the next major release." + "Please register REST API endpoints as part of their corresponding REST API extensions!"); RequestServer.registerEndpoint(apiName, method_url, hclass, method, summary); } public static void registerResourceRoot(File f) { JarHash.registerResourceRoot(f); } /** Start the web service; disallow future URL registration. * Blocks until the server is up. * * @deprecated use starServingRestApi */ @Deprecated static public void finalizeRegistration() { startServingRestApi(); } /** * This switch Jetty into accepting mode. */ public static void startServingRestApi() { if (!H2O.ARGS.disable_web) { NetworkInit.h2oHttpView.acceptRequests(); } } // -------------------------------------------------------------------------- // The Current Cloud. A list of all the Nodes in the Cloud. Changes if we // decide to change Clouds via atomic Cloud update. public static volatile H2O CLOUD = new H2O(new H2ONode[0],0,0); // --- // A dense array indexing all Cloud members. Fast reversal from "member#" to // Node. No holes. Cloud size is _members.length. public final H2ONode[] _memary; // mapping from a node ip to node index private HashMap<String, Integer> _node_ip_to_index; final int _hash; public H2ONode getNodeByIpPort(String ipPort) { if(_node_ip_to_index != null) { Integer index = _node_ip_to_index.get(ipPort); if (index != null) { if(index == -1){ return H2O.SELF; } else if(index <= -1 || index >= _memary.length){ // index -1 should not happen anymore as well throw new RuntimeException("Mapping from node id to node index contains: " + index + ", however this node" + "does not exist!"); } return _memary[index]; } else { // no node with such ip:port return null; } } else { // mapping is null, no cloud ready yet return null; } } // A dense integer identifier that rolls over rarely. Rollover limits the // number of simultaneous nested Clouds we are operating on in-parallel. // Really capped to 1 byte, under the assumption we won't have 256 nested // Clouds. Capped at 1 byte so it can be part of an atomically-assigned // 'long' holding info specific to this Cloud. final char _idx; // no unsigned byte, so unsigned char instead // Construct a new H2O Cloud from the member list H2O( H2ONode[] h2os, int hash, int idx ) { this(h2os, false, hash, idx); } H2O( H2ONode[] h2os, boolean presorted, int hash, int idx ) { _memary = h2os; if (!presorted) java.util.Arrays.sort(_memary); // ... sorted! _hash = hash; // And record hash for cloud rollover _idx = (char)(idx&0x0ff); // Roll-over at 256 } // One-shot atomic setting of the next Cloud, with an empty K/V store. // Called single-threaded from Paxos. Constructs the new H2O Cloud from a // member list. void set_next_Cloud( H2ONode[] h2os, int hash ) { synchronized(this) { int idx = _idx+1; // Unique 1-byte Cloud index if( idx == 256 ) idx=1; // wrap, avoiding zero CLOUDS[idx] = CLOUD = new H2O(h2os,hash,idx); } SELF._heartbeat._cloud_size=(char)CLOUD.size(); H2O.CLOUD._node_ip_to_index = new HashMap<>(); for(H2ONode node: H2O.CLOUD._memary){ H2O.CLOUD._node_ip_to_index.put(node.getIpPortString(), node.index()); } } // Is nnn larger than old (counting for wrap around)? Gets confused if we // start seeing a mix of more than 128 unique clouds at the same time. Used // to tell the order of Clouds appearing. static boolean larger( int nnn, int old ) { assert (0 <= nnn && nnn <= 255); assert (0 <= old && old <= 255); return ((nnn-old)&0xFF) < 64; } public final int size() { return _memary.length; } public boolean isSingleNode() { return size() == 1; } public final H2ONode leader() { return _memary[0]; } public final H2ONode leaderOrNull() { return _memary.length > 0 ? _memary[0] : null; } // Find the node index for this H2ONode, or a negative number on a miss int nidx( H2ONode h2o ) { return java.util.Arrays.binarySearch(_memary,h2o); } boolean contains( H2ONode h2o ) { return nidx(h2o) >= 0; } @Override public String toString() { return java.util.Arrays.toString(_memary); } public H2ONode[] members() { return _memary; } // Cluster free memory public long free_mem() { long memsz = 0; for( H2ONode h2o : CLOUD._memary ) memsz += h2o._heartbeat.get_free_mem(); return memsz; } // Quick health check; no reason given for bad health public boolean healthy() { long now = System.currentTimeMillis(); for (H2ONode node : H2O.CLOUD.members()) if (!node.isHealthy(now)) return false; return true; } public static void waitForCloudSize(int x, long ms) { long start = System.currentTimeMillis(); if(!cloudIsReady(x)) Log.info("Waiting for clouding to finish. Current number of nodes " + CLOUD.size() + ". Target number of nodes: " + x); while (System.currentTimeMillis() - start < ms) { if (cloudIsReady(x)) break; try { Thread.sleep(100); } catch (InterruptedException ignore) {} } if (CLOUD.size() < x) throw new RuntimeException("Cloud size " + CLOUD.size() + " under " + x + ". Consider to increase `DEFAULT_TIME_FOR_CLOUDING`."); } private static boolean cloudIsReady(int x) { return CLOUD.size() >= x && Paxos._commonKnowledge; } public static int getCloudSize() { if (! Paxos._commonKnowledge) return -1; return CLOUD.size(); } // - Wait for at least HeartBeatThread.SLEEP msecs and // try to join others, if any. Try 2x just in case. // - Assume that we get introduced to everybody else // in one Paxos update, if at all (i.e, rest of // the cloud was already formed and stable by now) // - If nobody else is found, not an error. public static void joinOthers() { long start = System.currentTimeMillis(); while( System.currentTimeMillis() - start < 2000 ) { if( CLOUD.size() > 1 && Paxos._commonKnowledge ) break; try { Thread.sleep(100); } catch( InterruptedException ignore ) { } } } // -------------------------------------------------------------------------- static void initializePersistence() { _PM = new PersistManager(ICE_ROOT); } // -------------------------------------------------------------------------- // The (local) set of Key/Value mappings. public static final NonBlockingHashMap<Key,Value> STORE = new NonBlockingHashMap<>(); // PutIfMatch // - Atomically update the STORE, returning the old Value on success // - Kick the persistence engine as needed // - Return existing Value on fail, no change. // // Keys are interned here: I always keep the existing Key, if any. The // existing Key is blind jammed into the Value prior to atomically inserting // it into the STORE and interning. // // Because of the blind jam, there is a narrow unusual race where the Key // might exist but be stale (deleted, mapped to a TOMBSTONE), a fresh put() // can find it and jam it into the Value, then the Key can be deleted // completely (e.g. via an invalidate), the table can resize flushing the // stale Key, an unrelated weak-put can re-insert a matching Key (but as a // new Java object), and delete it, and then the original thread can do a // successful put_if_later over the missing Key and blow the invariant that a // stored Value always points to the physically equal Key that maps to it // from the STORE. If this happens, some of replication management bits in // the Key will be set in the wrong Key copy... leading to extra rounds of // replication. public static Value putIfMatch( Key key, Value val, Value old ) { if( old != null ) // Have an old value? key = old._key; // Use prior key if( val != null ) { assert val._key.equals(key); if( val._key != key ) val._key = key; // Attempt to uniquify keys } // Insert into the K/V store Value res = STORE.putIfMatchUnlocked(key,val,old); if( res != old ) return res; // Return the failure cause // Persistence-tickle. // If the K/V mapping is going away, remove the old guy. // If the K/V mapping is changing, let the store cleaner just overwrite. // If the K/V mapping is new, let the store cleaner just create if( old != null && val == null ) old.removePersist(); // Remove the old guy if( val != null ) { Cleaner.dirty_store(); // Start storing the new guy if( old==null ) Scope.track_internal(key); // New Key - start tracking } return old; // Return success } // Get the value from the store public static void raw_remove(Key key) { Value v = STORE.remove(key); if( v != null ) v.removePersist(); } public static void raw_clear() { STORE.clear(); } public static boolean containsKey( Key key ) { return STORE.get(key) != null; } static Key getk( Key key ) { return STORE.getk(key); } public static Set<Key> localKeySet( ) { return STORE.keySet(); } static Collection<Value> values( ) { return STORE.values(); } static public int store_size() { return STORE.size(); } // Nice local-STORE only debugging summary public static String STOREtoString() { int[] cnts = new int[1]; Object[] kvs = H2O.STORE.raw_array(); // Start the walk at slot 2, because slots 0,1 hold meta-data for( int i=2; i<kvs.length; i += 2 ) { // In the raw backing array, Keys and Values alternate in slots Object ov = kvs[i+1]; if( !(ov instanceof Value) ) continue; // Ignore tombstones and Primes and null's Value val = (Value)ov; if( val.isNull() ) { Value.STORE_get(val._key); continue; } // Another variant of NULL int t = val.type(); while( t >= cnts.length ) cnts = Arrays.copyOf(cnts,cnts.length<<1); cnts[t]++; } StringBuilder sb = new StringBuilder(); for( int t=0; t<cnts.length; t++ ) if( cnts[t] != 0 ) sb.append(String.format("-%30s %5d\n",TypeMap.CLAZZES[t],cnts[t])); return sb.toString(); } // Persistence manager private static PersistManager _PM; public static PersistManager getPM() { return _PM; } // Node persistent storage private static NodePersistentStorage NPS; public static NodePersistentStorage getNPS() { return NPS; } /** * Run System.gc() on every node in the H2O cluster. * * Having to call this manually from user code is a sign that something is wrong and a better * heuristic is needed internally. */ public static void gc() { class GCTask extends DTask<GCTask> { public GCTask() {super(GUI_PRIORITY);} @Override public void compute2() { Log.info("Calling System.gc() now..."); System.gc(); Log.info("System.gc() finished"); tryComplete(); } } for (H2ONode node : H2O.CLOUD._memary) { GCTask t = new GCTask(); new RPC<>(node, t).call().get(); } } private static boolean JAVA_CHECK_PASSED = false; /** * Check if the Java version is not supported * * @return true if not supported */ public static boolean checkUnsupportedJava(String[] args) { if (JAVA_CHECK_PASSED) return false; if (Boolean.getBoolean(H2O.OptArgs.SYSTEM_PROP_PREFIX + "debug.noJavaVersionCheck")) { return false; } boolean unsupported = runCheckUnsupportedJava(args); if (!unsupported) { JAVA_CHECK_PASSED = true; } return unsupported; } static boolean runCheckUnsupportedJava(String[] args) { if (!JavaVersionSupport.runningOnSupportedVersion()) { Throwable error = null; boolean allowUnsupported = ArrayUtils.contains(args, "-allow_unsupported_java"); if (allowUnsupported) { boolean checkPassed = false; try { checkPassed = dynamicallyInvokeJavaSelfCheck(); } catch (Throwable t) { error = t; } if (checkPassed) { Log.warn("H2O is running on a version of Java (" + System.getProperty("java.version") + ") that was not certified at the time of the H2O release. " + "For production use please use a certified Java version (versions " + JavaVersionSupport.describeSupportedVersions() + " are officially supported)."); return false; } } System.err.printf("Only Java versions %s are supported, system version is %s%n", JavaVersionSupport.describeSupportedVersions(), System.getProperty("java.version")); if (ARGS.allow_unsupported_java) { System.err.println("H2O was invoked with flag -allow_unsupported_java, however, " + "we found out that your Java version doesn't meet the requirements to run H2O. Please use a supported Java version."); } if (error != null) error.printStackTrace(System.err); return true; } String vmName = System.getProperty("java.vm.name"); if (vmName != null && vmName.equals("GNU libgcj")) { System.err.println("GNU gcj is not supported"); return true; } return false; } /** * Dynamically invoke water.JavaSelfCheck#checkCompatibility. The call is dynamic in order to prevent * classloading issues to even load this class. * * @return true if Java-compatibility self-check passes successfully * @throws ClassNotFoundException * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ static boolean dynamicallyInvokeJavaSelfCheck() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class<?> cls = Class.forName("water.JavaSelfCheck"); Method m = cls.getDeclaredMethod("checkCompatibility"); return (Boolean) m.invoke(null); } /** * Any system property starting with `ai.h2o.` and containing any more `.` does not match * this pattern and is therefore ignored. This is mostly to prevent system properties * serving as configuration for H2O's dependencies (e.g. `ai.h2o.org.eclipse.jetty.LEVEL` ). */ static boolean isArgProperty(String name) { final String prefix = "ai.h2o."; if (!name.startsWith(prefix)) return false; return name.lastIndexOf('.') < prefix.length(); } // -------------------------------------------------------------------------- public static void main( String[] args ) { H2O.configureLogging(); extManager.registerCoreExtensions(); extManager.registerListenerExtensions(); extManager.registerAuthExtensions(); long time0 = System.currentTimeMillis(); if (checkUnsupportedJava(args)) throw new RuntimeException("Unsupported Java version"); // Record system start-time. if( !START_TIME_MILLIS.compareAndSet(0L, System.currentTimeMillis()) ) return; // Already started // Copy all ai.h2o.* system properties to the tail of the command line, // effectively overwriting the earlier args. ArrayList<String> args2 = new ArrayList<>(Arrays.asList(args)); for( Object p : System.getProperties().keySet() ) { String s = (String) p; if(isArgProperty(s)) { args2.add("-" + s.substring(7)); // hack: Junits expect properties, throw out dummy prop for ga_opt_out if (!s.substring(7).equals("ga_opt_out") && !System.getProperty(s).isEmpty()) args2.add(System.getProperty(s)); } } // Parse args String[] arguments = args2.toArray(args); parseArguments(arguments); // Get ice path before loading Log or Persist class long time1 = System.currentTimeMillis(); String ice = DEFAULT_ICE_ROOT(); if( ARGS.ice_root != null ) ice = ARGS.ice_root.replace("\\", "/"); try { ICE_ROOT = new URI(ice); } catch(URISyntaxException ex) { throw new RuntimeException("Invalid ice_root: " + ice + ", " + ex.getMessage()); } // Always print version, whether asked-for or not! long time2 = System.currentTimeMillis(); printAndLogVersion(arguments); if( ARGS.version ) { Log.flushBufferedMessagesToStdout(); exit(0); } // Print help & exit if (ARGS.help) { printHelp(); exit(0); } // Validate arguments validateArguments(); // Raise user warnings if (H2O.ARGS.web_ip == null) { Log.warn("SECURITY_WARNING: web_ip is not specified. H2O Rest API is listening on all available interfaces."); } Log.info("X-h2o-cluster-id: " + H2O.CLUSTER_ID); Log.info("User name: '" + H2O.ARGS.user_name + "'"); // Epic Hunt for the correct self InetAddress long time4 = System.currentTimeMillis(); Log.info("IPv6 stack selected: " + IS_IPV6); SELF_ADDRESS = NetworkInit.findInetAddressForSelf(); // Right now the global preference is to use IPv4 stack // To select IPv6 stack user has to explicitly pass JVM flags // to enable IPv6 preference. if (!IS_IPV6 && SELF_ADDRESS instanceof Inet6Address) { Log.err("IPv4 network stack specified but IPv6 address found: " + SELF_ADDRESS + "\n" + "Please specify JVM flags -Djava.net.preferIPv6Addresses=true and -Djava.net.preferIPv4Addresses=false to select IPv6 stack"); H2O.exit(-1); } if (IS_IPV6 && SELF_ADDRESS instanceof Inet4Address) { Log.err("IPv6 network stack specified but IPv4 address found: " + SELF_ADDRESS); H2O.exit(-1); } // Start the local node. Needed before starting logging. long time5 = System.currentTimeMillis(); startLocalNode(); // Allow core extensions to perform initialization that requires the network. long time6 = System.currentTimeMillis(); for (AbstractH2OExtension ext: extManager.getCoreExtensions()) { ext.onLocalNodeStarted(); } try { String logDir = Log.getLogDir(); Log.info("Log dir: '" + logDir + "'"); } catch (Exception e) { Log.info("Log dir: (Log4j configuration inherited)"); } Log.info("Cur dir: '" + System.getProperty("user.dir") + "'"); //Print extra debug info now that logs are setup long time7 = System.currentTimeMillis(); RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean(); Log.debug("H2O launch parameters: "+ARGS.toString()); if (rtBean.isBootClassPathSupported()) { Log.debug("Boot class path: " + rtBean.getBootClassPath()); } Log.debug("Java class path: "+ rtBean.getClassPath()); Log.debug("Java library path: "+ rtBean.getLibraryPath()); // Load up from disk and initialize the persistence layer long time8 = System.currentTimeMillis(); initializePersistence(); // Initialize NPS { String flow_dir; if (ARGS.flow_dir != null) { flow_dir = ARGS.flow_dir; } else { flow_dir = DEFAULT_FLOW_DIR(); } if (flow_dir != null) { flow_dir = flow_dir.replace("\\", "/"); Log.info("Flow dir: '" + flow_dir + "'"); } else { Log.info("Flow dir is undefined; saving flows not available"); } NPS = new NodePersistentStorage(flow_dir); } // Start network services, including heartbeats long time9 = System.currentTimeMillis(); startNetworkServices(); // start server services Log.trace("Network services started"); // The "Cloud of size N formed" message printed out by doHeartbeat is the trigger // for users of H2O to know that it's OK to start sending REST API requests. long time10 = System.currentTimeMillis(); Paxos.doHeartbeat(SELF); assert SELF._heartbeat._cloud_hash != 0 || ARGS.client; // Start the heartbeat thread, to publish the Clouds' existence to other // Clouds. This will typically trigger a round of Paxos voting so we can // join an existing Cloud. new HeartBeatThread().start(); long time11 = System.currentTimeMillis(); // Log registered parsers Log.info("Registered parsers: " + Arrays.toString(ParserService.INSTANCE.getAllProviderNames(true))); // Start thread checking client disconnections if (Boolean.getBoolean(H2O.OptArgs.SYSTEM_PROP_PREFIX + "debug.clientDisconnectAttack")) { // for development only! Log.warn("Client Random Disconnect attack is enabled - use only for debugging! More warnings to follow ;)"); new ClientRandomDisconnectThread().start(); } else { // regular mode of operation new ClientDisconnectCheckThread().start(); } if (isGCLoggingEnabled()) { Log.info(H2O.technote(16, "GC logging is enabled, you might see messages containing \"GC (Allocation Failure)\". " + "Please note that this is a normal part of GC operations and occurrence of such messages doesn't directly indicate an issue.")); } long time12 = System.currentTimeMillis(); Log.debug("Timing within H2O.main():"); Log.debug(" Args parsing & validation: " + (time1 - time0) + "ms"); Log.debug(" Get ICE root: " + (time2 - time1) + "ms"); Log.debug(" Print log version: " + (time4 - time2) + "ms"); Log.debug(" Detect network address: " + (time5 - time4) + "ms"); Log.debug(" Start local node: " + (time6 - time5) + "ms"); Log.debug(" Extensions onLocalNodeStarted(): " + (time7 - time6) + "ms"); Log.debug(" RuntimeMxBean: " + (time8 - time7) + "ms"); Log.debug(" Initialize persistence layer: " + (time9 - time8) + "ms"); Log.debug(" Start network services: " + (time10 - time9) + "ms"); Log.debug(" Cloud up: " + (time11 - time10) + "ms"); Log.debug(" Start GA: " + (time12 - time11) + "ms"); } private static boolean isGCLoggingEnabled() { RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); List<String> jvmArgs = runtimeMXBean.getInputArguments(); for (String arg : jvmArgs) { if (arg.startsWith("-XX:+PrintGC") || arg.equals("-verbose:gc") || (arg.startsWith("-Xlog:") && arg.contains("gc"))) return true; } return false; } /** Find PID of the current process, use -1 if we can't find the value. */ private static long getCurrentPID() { try { String n = ManagementFactory.getRuntimeMXBean().getName(); int i = n.indexOf('@'); if(i != -1) { return Long.parseLong(n.substring(0, i)); } else { return -1L; } } catch(Throwable ignore) { return -1L; } } // Die horribly public static void die(String s) { Log.fatal(s); H2O.exit(-1); } /** * Add node to a manual multicast list. * Note: the method is valid only if -flatfile option was specified on commandline * * @param node H2O node * @return true if the node was already in the multicast list. */ public static boolean addNodeToFlatfile(H2ONode node) { assert isFlatfileEnabled() : "Trying to use flatfile, but flatfile is not enabled!"; return STATIC_H2OS.add(node); } /** * Remove node from a manual multicast list. * Note: the method is valid only if -flatfile option was specified on commandline * * @param node H2O node * @return true if the node was in the multicast list. */ public static boolean removeNodeFromFlatfile(H2ONode node) { assert isFlatfileEnabled() : "Trying to use flatfile, but flatfile is not enabled!"; return STATIC_H2OS.remove(node); } /** * Check if a node is included in a manual multicast list. * Note: the method is valid only if -flatfile option was specified on commandline * * @param node H2O node * @return true if the node is in the multicast list. */ public static boolean isNodeInFlatfile(H2ONode node) { assert isFlatfileEnabled() : "Trying to use flatfile, but flatfile is not enabled!"; return STATIC_H2OS.contains(node); } /** * Check if manual multicast is enabled. * * @return true if -flatfile option was specified on commandline */ public static boolean isFlatfileEnabled() { return STATIC_H2OS != null; } /** * Setup a set of nodes which should be contacted during manual multicast * * @param nodes set of H2O nodes */ public static void setFlatfile(Set<H2ONode> nodes) { if (nodes == null) { STATIC_H2OS = null; } else { STATIC_H2OS = Collections.newSetFromMap(new ConcurrentHashMap<H2ONode, Boolean>()); STATIC_H2OS.addAll(nodes); } } /** * Returns a set of nodes which are contacted during manual multi-cast. * * @return set of H2O nodes */ public static Set<H2ONode> getFlatfile() { return new HashSet<>(STATIC_H2OS); } /** * Forgets H2O client */ static boolean removeClient(H2ONode client){ return client.removeClient(); } public static H2ONode[] getClients(){ return H2ONode.getClients(); } public static H2ONode getClientByIPPort(String ipPort){ return H2ONode.getClientByIPPort(ipPort); } public static Key<DecryptionTool> defaultDecryptionTool() { return H2O.ARGS.decrypt_tool != null ? Key.<DecryptionTool>make(H2O.ARGS.decrypt_tool) : null; } public static URI downloadLogs(URI destinationDir, LogArchiveContainer logContainer) { return LogsHandler.downloadLogs(destinationDir.toString(), logContainer); } public static URI downloadLogs(URI destinationDir, String logContainer) { return LogsHandler.downloadLogs(destinationDir.toString(), LogArchiveContainer.valueOf(logContainer)); } public static URI downloadLogs(String destinationDir, LogArchiveContainer logContainer) { return LogsHandler.downloadLogs(destinationDir, logContainer); } public static URI downloadLogs(String destinationDir, String logContainer) { return LogsHandler.downloadLogs(destinationDir, LogArchiveContainer.valueOf(logContainer)); } /** * Is this H2O cluster running in our continuous integration environment? * * This information can be used to enable extended error output or force shutdown in case * an error is encountered. Use responsibly. * * @return true, if running in CI */ static boolean isCI() { return AbstractBuildVersion.getBuildVersion().isDevVersion() && "jenkins".equals(System.getProperty("user.name")); } }
h2oai/h2o-3
h2o-core/src/main/java/water/H2O.java
2,104
/* ### * IP: GHIDRA * * 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 ghidra.app.util.bin.format.dwarf; import static ghidra.app.util.bin.format.dwarf.DWARFTag.*; import static ghidra.app.util.bin.format.dwarf.attribs.DWARFAttribute.*; import java.io.IOException; import java.util.*; import org.apache.commons.lang3.ArrayUtils; import ghidra.app.util.bin.format.dwarf.attribs.*; import ghidra.app.util.bin.format.dwarf.expression.*; import ghidra.app.util.bin.format.dwarf.line.DWARFLine; import ghidra.util.Msg; /** * DIEAggregate groups related {@link DebugInfoEntry} records together in a single interface * for querying attribute values. * <p> * Information about program elements are written into the .debug_info as partial snapshots * of the element, with later follow-up records that more fully specify the program element. * <p> * (For instance, a declaration-only DIE that introduces the name of a structure type * will be found at the beginning of a compilation unit, followed later by a DIE that * specifies the contents of the structure type) * <p> * A DIEAggregate groups these {@link DebugInfoEntry} records under one interface so a fully * specified view of the program element can be presented. */ public class DIEAggregate { /** * Sanity check upper limit on how many DIE records can be in a aggregate. */ private static final int MAX_FRAGMENT_COUNT = 20; /** * A list of {@link DebugInfoEntry DIEs} that make up this DWARF program element, with * the 'head'-most listed first, followed by earlier less specified DIEs, ending with * the first 'decl' DIE in the last element. * <p> * For example:<p> * [0] - head<br> * [1] - specification<br> * [2] - decl<br> * <p> * A primitive array is used instead of a java.util.List because of memory constraint issues * and also that the set of fragments does not change after the bootstrap process in * {@link #createFromHead(DebugInfoEntry) createFromHead()}. */ private DebugInfoEntry[] fragments; /** * Creates a {@link DIEAggregate} starting from a 'head' {@link DebugInfoEntry} instance. * <p> * DW_AT_abstract_origin and DW_AT_specification attributes are followed to find the previous * {@link DebugInfoEntry} instances. * <p> * @param die starting DIE record * @return new {@link DIEAggregate} made up of the starting DIE and all DIEs that it points * to via abstract_origin and spec attributes. */ public static DIEAggregate createFromHead(DebugInfoEntry die) { // build the list of fragments assuming we are starting at the topmost fragment // (ie. forward references only). // Possible fragments are: // headEntry --abstract_origin--> specEntry --specification--> declEntry // The fragments are in reversed order (ie. more primitive DIEs are at the // front of the list) while querying for additional abstract_origin // values to ensure that we retrieve what would normally be the overridden value. // When all fragments have been found, the order of the fragments is reversed so // that the 'head' or topmost fragment is first in the list and will be the DIE record // queried first for attribute values. DIEAggregate result = new DIEAggregate(new DebugInfoEntry[] { die }); // keep querying for abstract_origin DIEs as long as we haven't seen them yet, // and add them to the fragment list. DebugInfoEntry tmp; while ((tmp = result.getRefDIE(DW_AT_abstract_origin)) != null && !result.hasOffset(tmp.getOffset()) && result.getFragmentCount() < MAX_FRAGMENT_COUNT) { result.addFragment(tmp); } // look for 1 spec DIE and add it. tmp = result.getRefDIE(DW_AT_specification); if (tmp != null) { result.addFragment(tmp); } result.flipFragments(); return result; } /** * Creates a new {@link DIEAggregate} from the contents of the specified DIEA, using * all the source's {@link DebugInfoEntry} fragments except for the head fragment * which is skipped. * <p> * Used when a DIEA is composed of a head DIE with a different TAG type than the rest of * the DIEs. (ie. a dw_tag_call_site -&gt; dw_tag_sub DIEA) * * @param source {@link DIEAggregate} containing fragments * @return {@link DIEAggregate} with the fragments of the source, skipping the first */ public static DIEAggregate createSkipHead(DIEAggregate source) { if (source.fragments.length == 1) { return null; } DebugInfoEntry[] partialFrags = new DebugInfoEntry[source.fragments.length - 1]; System.arraycopy(source.fragments, 1, partialFrags, 0, partialFrags.length); return new DIEAggregate(partialFrags); } /** * Create a {@link DIEAggregate} from a single {@link DebugInfoEntry DIE}. * <p> * Mainly useful early in the {@link DWARFCompilationUnit}'s bootstrapping process * when it needs to read values from DIEs. * <p> * @param die {@link DebugInfoEntry} * @return {@link DIEAggregate} containing a single DIE */ public static DIEAggregate createSingle(DebugInfoEntry die) { DIEAggregate result = new DIEAggregate(new DebugInfoEntry[] { die }); return result; } /** * Private ctor to force use of the static factory methods {@link #createFromHead(DebugInfoEntry)} * and {@link #createSingle(DebugInfoEntry)}. * * @param fragments array of DIEs that make this aggregate */ private DIEAggregate(DebugInfoEntry[] fragments) { this.fragments = fragments; } /** * Used during creation process to add new DebugInfoEntry elements as they are found by * following links in the current set of DIEs. * <p> * Adds the new DIE fragment to the front of the fragment array list, which is reversed * from how it needs to be when this DIEA is being used. The caller needs to * call {@link #flipFragments()} after the build phase to reverse the order of the * DIE fragments list so that querying for attribute values will return the correct values. * * @param newDIE {@link DebugInfoEntry} to add */ private void addFragment(DebugInfoEntry newDIE) { DebugInfoEntry[] tmp = new DebugInfoEntry[fragments.length + 1]; System.arraycopy(fragments, 0, tmp, 1, fragments.length); tmp[0] = newDIE; fragments = tmp; } private void flipFragments() { ArrayUtils.reverse(fragments); } public int getFragmentCount() { return fragments.length; } public long getOffset() { return getHeadFragment().getOffset(); } public long[] getOffsets() { long[] result = new long[fragments.length]; for (int i = 0; i < fragments.length; i++) { result[i] = fragments[i].getOffset(); } return result; } /** * Returns true if any of the {@link DebugInfoEntry DIEs} that makeup this aggregate * have the specified offset. * * @param offset DIE offset to search for * @return true if this {@link DIEAggregate} has a fragment DIE at that offset. */ public boolean hasOffset(long offset) { for (DebugInfoEntry fragment : fragments) { if (fragment.getOffset() == offset) { return true; } } return false; } public long getDeclOffset() { return getLastFragment().getOffset(); } /** * Returns {@link #getOffset()} as a hex string. * @return string hex offset of the head DIE */ public String getHexOffset() { return Long.toHexString(getHeadFragment().getOffset()); } public DWARFTag getTag() { return getHeadFragment().getTag(); } public DWARFCompilationUnit getCompilationUnit() { return getHeadFragment().getCompilationUnit(); } public DWARFProgram getProgram() { return getHeadFragment().getProgram(); } /** * Returns the last {@link DebugInfoEntry DIE} fragment, ie. the decl DIE. * @return last DIE of this aggregate */ public DebugInfoEntry getLastFragment() { return fragments[fragments.length - 1]; } /** * Returns the first {@link DebugInfoEntry DIE} fragment, ie. the spec or abstract_origin * DIE. * @return first DIE of this aggregate */ public DebugInfoEntry getHeadFragment() { return fragments[0]; } public DIEAggregate getDeclParent() { DebugInfoEntry declDIE = getLastFragment(); DebugInfoEntry declParent = declDIE.getParent(); return getProgram().getAggregate(declParent); } public DIEAggregate getParent() { DebugInfoEntry die = getHeadFragment(); DebugInfoEntry parent = die.getParent(); return getProgram().getAggregate(parent); } /** * Returns the depth of the head fragment, where depth is defined as * the distance between the DIE and the root DIE of the owning compilation * unit. * <p> * The root die would return 0, the children of the root will return 1, etc. * <p> * This value matches the nesting value shown when dumping DWARF * info using 'readelf'. * * @return depth of this instance, from the root of its head DIE fragment, with 0 indicating * that this instance was already the root of the compUnit */ public int getDepth() { return getProgram().getParentDepth(getHeadFragment().getIndex()); } private FoundAttribute findAttribute(DWARFAttribute attribute) { for (DebugInfoEntry die : fragments) { DWARFAttributeValue attrVal = die.findAttribute(attribute); if (attrVal != null) { return new FoundAttribute(attrVal, die); } } return null; } /** * Return an attribute that is present in this {@link DIEAggregate}, or in any of its * direct children (of a specific type) * * @param <T> attribute value type * @param attribute the attribute to find * @param childTag the type of children to search * @param clazz type of the attribute to return * @return attribute value, or null if not found */ public <T extends DWARFAttributeValue> T findAttributeInChildren(DWARFAttribute attribute, DWARFTag childTag, Class<T> clazz) { T attributeValue = getAttribute(attribute, clazz); if (attributeValue != null) { return attributeValue; } for (DebugInfoEntry childDIE : getChildren(childTag)) { DIEAggregate childDIEA = getProgram().getAggregate(childDIE); attributeValue = childDIEA.getAttribute(attribute, clazz); if (attributeValue != null) { return attributeValue; } } return null; } /** * Finds a {@link DWARFAttributeValue attribute} with a matching {@link DWARFAttribute} id. * <p> * Returns null if the attribute does not exist or is wrong java class type. * <p> * Attributes are searched for in each fragment in this aggregate, starting with the * 'head' fragment, progressing toward the 'decl' fragment. * <p> * * @param attribute See {@link DWARFAttribute} * @param clazz must be derived from {@link DWARFAttributeValue} * @return DWARFAttributeValue or subclass as specified by the clazz, or null if not found */ public <T extends DWARFAttributeValue> T getAttribute(DWARFAttribute attribute, Class<T> clazz) { FoundAttribute attrInfo = findAttribute(attribute); return attrInfo != null ? attrInfo.getValue(clazz) : null; } /** * Finds a {@link DWARFAttributeValue attribute} with a matching {@link DWARFAttribute} id. * <p> * Returns null if the attribute does not exist. * <p> * Attributes are searched for in each fragment in this aggregate, starting with the * 'head' fragment, progressing toward the 'decl' fragment. * <p> * * @param attribute See {@link DWARFAttribute} * @return DWARFAttributeValue, or null if not found */ public DWARFAttributeValue getAttribute(DWARFAttribute attribute) { return getAttribute(attribute, DWARFAttributeValue.class); } /** * Returns the value of the requested attribute, or -defaultValue- if the * attribute is missing. * * @param attribute {@link DWARFAttribute} id * @param defaultValue value to return if attribute is not present * @return long value, or the defaultValue if attribute not present */ public long getLong(DWARFAttribute attribute, long defaultValue) { DWARFNumericAttribute attr = getAttribute(attribute, DWARFNumericAttribute.class); return (attr != null) ? attr.getValue() : defaultValue; } /** * Returns the boolean value of the requested attribute, or -defaultValue- if * the attribute is missing or not the correct type. * <p> * @param attribute {@link DWARFAttribute} id * @param defaultValue value to return if attribute is not present * @return boolean value, or the defaultValue if attribute is not present */ public boolean getBool(DWARFAttribute attribute, boolean defaultValue) { DWARFBooleanAttribute val = getAttribute(attribute, DWARFBooleanAttribute.class); return (val != null) ? val.getValue() : defaultValue; } /** * Returns the string value of the requested attribute, or -defaultValue- if * the attribute is missing or not the correct type. * <p> * @param attribute {@link DWARFAttribute} id * @param defaultValue value to return if attribute is not present * @return String value, or the defaultValue if attribute is not present */ public String getString(DWARFAttribute attribute, String defaultValue) { FoundAttribute attrInfo = findAttribute(attribute); if (attrInfo == null || !(attrInfo.attr instanceof DWARFStringAttribute strAttr)) { return defaultValue; } return strAttr.getValue(attrInfo.die.getCompilationUnit()); } /** * Returns the string value of the {@link DWARFAttribute#DW_AT_name dw_at_name} attribute, * or null if it is missing. * <p> * @return name of this DIE aggregate, or null if missing */ public String getName() { return getString(DW_AT_name, null); } /** * Returns the unsigned long integer value of the requested attribute, or -defaultValue- * if the attribute is missing. * <p> * The 'unsigned'ness of this method refers to how the binary value is read from * the dwarf information (ie. a value with the high bit set is not treated as signed). * <p> * The -defaultValue- parameter can accept a negative value. * * @param attribute {@link DWARFAttribute} id * @param defaultValue value to return if attribute is not present * @return unsigned long value, or the defaultValue if attribute is not present */ public long getUnsignedLong(DWARFAttribute attribute, long defaultValue) { DWARFNumericAttribute attr = getAttribute(attribute, DWARFNumericAttribute.class); return (attr != null) ? attr.getUnsignedValue() : defaultValue; } private DebugInfoEntry getRefDIE(DWARFAttribute attribute) { DWARFNumericAttribute val = getAttribute(attribute, DWARFNumericAttribute.class); if (val == null) { return null; } long offset = val.getUnsignedValue(); DebugInfoEntry result = getProgram().getDIEByOffset(offset); if (result == null) { Msg.warn(this, "Invalid reference value [%x]".formatted(offset)); Msg.warn(this, this.toString()); } return result; } /** * Returns the {@link DIEAggregate diea} instance pointed to by the requested attribute, * or null if the attribute does not exist. * <p> * @param attribute {@link DWARFAttribute} id * @return {@link DIEAggregate}, or the null if attribute is not present */ public DIEAggregate getRef(DWARFAttribute attribute) { DebugInfoEntry die = getRefDIE(attribute); return getProgram().getAggregate(die); } /** * Returns the DIE pointed to by a DW_AT_containing_type attribute. * * @return DIEA pointed to by the DW_AT_containing_type attribute, or null if not present. */ public DIEAggregate getContainingTypeRef() { return getRef(DW_AT_containing_type); } public DIEAggregate getTypeRef() { return getRef(DW_AT_type); } /** * Returns the name of the source file this item was declared in (DW_AT_decl_file) * * @return name of file this item was declared in, or null if info not available */ public String getSourceFile() { FoundAttribute attrInfo = findAttribute(DW_AT_decl_file); if (attrInfo == null) { return null; } DWARFNumericAttribute attr = attrInfo.getValue(DWARFNumericAttribute.class); if (attr == null) { return null; } try { int fileNum = attr.getUnsignedIntExact(); DWARFCompilationUnit cu = attrInfo.die.getCompilationUnit(); DWARFLine line = cu.getLine(); return line.getFilePath(fileNum, false); } catch (IOException e) { return null; } } /** * Return a list of children that are of a specific DWARF type. * <p> * @param childTag see {@link DWARFTag DWARFTag DW_TAG_* values} * @return List of children DIEs that match the specified tag */ public List<DebugInfoEntry> getChildren(DWARFTag childTag) { return getHeadFragment().getChildren(childTag); } /** * Returns true if the specified attribute is present. * * @param attribute attribute id * @return boolean true if value is present */ public boolean hasAttribute(DWARFAttribute attribute) { return findAttribute(attribute) != null; } /** * Return a {@link DIEAggregate} that only contains the information present in the * "abstract instance" (and lower) DIEs. * * @return a new {@link DIEAggregate}, or null if this DIEA was not split into a concrete and * abstract portion */ public DIEAggregate getAbstractInstance() { FoundAttribute aoAttr = findAttribute(DW_AT_abstract_origin); if (aoAttr == null) { return null; } for (int aoIndex = 0; aoIndex < fragments.length; aoIndex++) { if (fragments[aoIndex] == aoAttr.die) { DebugInfoEntry[] partialFrags = new DebugInfoEntry[fragments.length - aoIndex - 1]; System.arraycopy(fragments, aoIndex + 1, partialFrags, 0, partialFrags.length); return new DIEAggregate(partialFrags); } } throw new IllegalArgumentException("Should not get here"); } /** * Returns the signed integer value of the requested attribute after resolving * any DWARF expression opcodes. * <p> * @param attribute {@link DWARFAttribute} id * @param defaultValue value to return if attribute is not present * @return int value, or the defaultValue if attribute is not present * @throws IOException if error reading value or invalid value type * @throws DWARFExpressionException if error evaluating a DWARF expression */ public int parseInt(DWARFAttribute attribute, int defaultValue) throws IOException, DWARFExpressionException { DWARFAttributeValue attr = getAttribute(attribute); if (attr == null) { return defaultValue; } if (attr instanceof DWARFNumericAttribute dnum) { return assertValidInt(dnum.getValue()); } else if (attr instanceof DWARFBlobAttribute dblob) { byte[] exprBytes = dblob.getBytes(); DWARFExpressionEvaluator evaluator = new DWARFExpressionEvaluator(getCompilationUnit()); DWARFExpression expr = evaluator.readExpr(exprBytes); evaluator.evaluate(expr, 0); return assertValidInt(evaluator.pop()); } else { throw new IOException("Not integer attribute: %s".formatted(attr)); } } /** * Returns the unsigned integer value of the requested attribute after resolving * any DWARF expression opcodes. * <p> * @param attribute {@link DWARFAttribute} id * @param defaultValue value to return if attribute is not present * @return unsigned long value, or the defaultValue if attribute is not present * @throws IOException if error reading value or invalid value type * @throws DWARFExpressionException if error evaluating a DWARF expression */ public long parseUnsignedLong(DWARFAttribute attribute, long defaultValue) throws IOException, DWARFExpressionException { FoundAttribute attrInfo = findAttribute(attribute); if (attrInfo == null) { return defaultValue; } DWARFAttributeValue attr = attrInfo.attr; if (attr instanceof DWARFNumericAttribute dnum) { return dnum.getUnsignedValue(); } else if (attr instanceof DWARFBlobAttribute dblob) { byte[] exprBytes = dblob.getBytes(); DWARFExpressionEvaluator evaluator = new DWARFExpressionEvaluator(attrInfo.die().getCompilationUnit()); DWARFExpression expr = evaluator.readExpr(exprBytes); evaluator.evaluate(expr, 0); return evaluator.pop(); } else { throw new IOException("Not integer attribute: %s".formatted(attr)); } } private int assertValidInt(long l) throws DWARFException { if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { throw new DWARFException("Value out of allowed range: " + l); } return (int) l; } private int assertValidUInt(long l) throws DWARFException { if (l < 0 || l > Integer.MAX_VALUE) { throw new DWARFException("Value out of allowed range: " + l); } return (int) l; } /** * Returns the unsigned integer value of the requested attribute after resolving * any DWARF expression opcodes. * * @param attribute {@link DWARFAttribute} id * @param defaultValue value to return if attribute is not present * @return unsigned int value, or the defaultValue if attribute is not present * @throws IOException if error reading value or invalid value type * @throws DWARFExpressionException if error evaluating a DWARF expression */ public int parseDataMemberOffset(DWARFAttribute attribute, int defaultValue) throws DWARFExpressionException, IOException { DWARFAttributeValue attr = getAttribute(attribute); if (attr == null) { return defaultValue; } if (attr instanceof DWARFNumericAttribute dnum) { return dnum.getUnsignedIntExact(); } else if (attr instanceof DWARFBlobAttribute dblob) { byte[] exprBytes = dblob.getBytes(); DWARFExpressionEvaluator evaluator = new DWARFExpressionEvaluator(getCompilationUnit()); DWARFExpression expr = evaluator.readExpr(exprBytes); // DW_AT_data_member_location expects the address of the containing object // to be on the stack before evaluation starts. We don't have that so we // fake it with zero. evaluator.evaluate(expr, 0); return assertValidUInt(evaluator.pop()); } else { throw new DWARFException("DWARF attribute form not valid for data member offset: %s" .formatted(attr.getAttributeForm())); } } /** * Parses a location attribute value, which can be a single expression that is valid for any * PC, or a list of expressions that are tied to specific ranges. * * @param attribute typically {@link DWARFAttribute#DW_AT_location} * @return a {@link DWARFLocationList}, never null, possibly empty * @throws IOException if error reading data */ public DWARFLocationList getLocationList(DWARFAttribute attribute) throws IOException { return getProgram().getLocationList(this, attribute); } /** * Parses a location attribute value, and returns the {@link DWARFLocation} instance that * covers the specified pc. * * @param attribute typically {@link DWARFAttribute#DW_AT_location} * @param pc program counter * @return a {@link DWARFLocationList}, never null, possibly empty * @throws IOException if error reading data */ public DWARFLocation getLocation(DWARFAttribute attribute, long pc) throws IOException { DWARFLocationList locList = getLocationList(attribute); return locList.getLocationContaining(pc); } /** * Returns true if this DIE has a DW_AT_declaration attribute and * does NOT have a matching inbound DW_AT_specification reference. * <p> * @return boolean true if this DIE has a DW_AT_declaration attribute and * does NOT have a matching inbound DW_AT_specification reference */ public boolean isDanglingDeclaration() { return isPartialDeclaration() && fragments.length == 1; } /** * Returns true if this DIE has a DW_AT_declaration attribute. * @return true if this DIE has a DW_AT_declaration attribute */ public boolean isPartialDeclaration() { return hasAttribute(DW_AT_declaration); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DIEAgregrate of: "); for (DebugInfoEntry die : fragments) { sb.append("DIE [0x%x], ".formatted(die.getOffset())); } sb.append("\n"); for (DebugInfoEntry die : fragments) { sb.append(die.toString()); } return sb.toString(); } /** * Parses a range list. * * @param attribute attribute eg {@link DWARFAttribute#DW_AT_ranges} * @return list of ranges, or null if attribute is not present * @throws IOException if an I/O error occurs */ public DWARFRangeList getRangeList(DWARFAttribute attribute) throws IOException { return getProgram().getRangeList(this, attribute); } /** * Return the range specified by the low_pc...high_pc attribute values. * * @return {@link DWARFRange} containing low_pc - high_pc, or empty range if the low_pc is * not present */ public DWARFRange getPCRange() { DWARFNumericAttribute lowPc = getAttribute(DW_AT_low_pc, DWARFNumericAttribute.class); if (lowPc != null) { try { // TODO: previous code excluded lowPc values that were == 0 as invalid. long rawLowPc = lowPc.getUnsignedValue(); long lowPcOffset = getProgram().getAddress(lowPc.getAttributeForm(), rawLowPc, getCompilationUnit()); long highPcOffset = lowPcOffset; DWARFNumericAttribute highPc = getAttribute(DW_AT_high_pc, DWARFNumericAttribute.class); if (highPc != null) { if (highPc.getAttributeForm() == DWARFForm.DW_FORM_addr) { highPcOffset = highPc.getUnsignedValue(); } else { highPcOffset = highPc.getUnsignedValue(); highPcOffset = lowPcOffset + highPcOffset; } } return new DWARFRange(lowPcOffset, highPcOffset); } catch (IOException e) { // fall thru, return empty } } return DWARFRange.EMPTY; } /** * Returns a function's parameter list, taking care to ensure that the params * are well ordered (to avoid issues with concrete instance param ordering) * * @return list of params for this function */ public List<DIEAggregate> getFunctionParamList() { // build list of params, as seen by the function's DIEA List<DIEAggregate> params = new ArrayList<>(); for (DebugInfoEntry paramDIE : getChildren(DW_TAG_formal_parameter)) { DIEAggregate paramDIEA = getProgram().getAggregate(paramDIE); params.add(paramDIEA); } // since the function might be defined using an abstract and concrete parts, // and the param ordering of the concrete part can be inconsistent, re-order the // params according to the abstract instance's params. // Extra concrete params will be discarded. DIEAggregate abstractDIEA = getAbstractInstance(); if (abstractDIEA != null) { List<DIEAggregate> newParams = new ArrayList<>(); for (DebugInfoEntry paramDIE : abstractDIEA.getChildren(DW_TAG_formal_parameter)) { int index = findDIEInList(params, paramDIE); if (index >= 0) { newParams.add(params.get(index)); params.remove(index); } else { // add generic (abstract) definition of the param to the list newParams.add(getProgram().getAggregate(paramDIE)); } } if (!params.isEmpty()) { //Msg.warn(this, "Extra params in concrete DIE instance: " + params); //Msg.warn(this, this.toString()); newParams.addAll(params); } params = newParams; } return params; } private static int findDIEInList(List<DIEAggregate> dieas, DebugInfoEntry die) { for (int i = 0; i < dieas.size(); i++) { if (dieas.get(i).hasOffset(die.getOffset())) { return i; } } return -1; } /** * A simple class used by findAttribute() to return the found attribute, along with * the DIE it was found in, and the DWARFForm type of the raw attribute. * * @param attr attribute value * @param die DIE the value was found in */ record FoundAttribute(DWARFAttributeValue attr, DebugInfoEntry die) { <T extends DWARFAttributeValue> T getValue(Class<T> clazz) { if (attr != null && clazz.isAssignableFrom(attr.getClass())) { return clazz.cast(attr); } return null; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(fragments); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof DIEAggregate)) { return false; } DIEAggregate other = (DIEAggregate) obj; if (!Arrays.equals(fragments, other.fragments)) { return false; } return true; } }
NationalSecurityAgency/ghidra
Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/DIEAggregate.java
2,105
/* * 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.jasper; import java.io.BufferedReader; import java.io.CharArrayWriter; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jakarta.servlet.jsp.JspFactory; import jakarta.servlet.jsp.tagext.TagLibraryInfo; import org.apache.jasper.compiler.Compiler; import org.apache.jasper.compiler.JspConfig; import org.apache.jasper.compiler.JspRuntimeContext; import org.apache.jasper.compiler.Localizer; import org.apache.jasper.compiler.TagPluginManager; import org.apache.jasper.compiler.TldCache; import org.apache.jasper.runtime.JspFactoryImpl; import org.apache.jasper.servlet.JspCServletContext; import org.apache.jasper.servlet.TldScanner; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.util.FileUtils; import org.xml.sax.SAXException; /** * Shell for the jspc compiler. Handles all options associated with the * command line and creates compilation contexts which it then compiles * according to the specified options. * * This version can process files from a _single_ webapp at once, i.e. * a single docbase can be specified. * * It can be used as an Ant task using: * <pre> * &lt;taskdef classname="org.apache.jasper.JspC" name="jasper" &gt; * &lt;classpath&gt; * &lt;pathelement location="${java.home}/../lib/tools.jar"/&gt; * &lt;fileset dir="${ENV.CATALINA_HOME}/lib"&gt; * &lt;include name="*.jar"/&gt; * &lt;/fileset&gt; * &lt;path refid="myjars"/&gt; * &lt;/classpath&gt; * &lt;/taskdef&gt; * * &lt;jasper verbose="0" * package="my.package" * uriroot="${webapps.dir}/${webapp.name}" * webXmlFragment="${build.dir}/generated_web.xml" * outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package" /&gt; * </pre> * * @author Danno Ferrin * @author Pierre Delisle * @author Costin Manolache * @author Yoav Shapira */ public class JspC extends Task implements Options { static { // the Validator uses this to access the EL ExpressionFactory JspFactory.setDefaultFactory(new JspFactoryImpl()); } // Logger private static final Log log = LogFactory.getLog(JspC.class); protected static final String SWITCH_VERBOSE = "-v"; protected static final String SWITCH_HELP = "-help"; protected static final String SWITCH_OUTPUT_DIR = "-d"; protected static final String SWITCH_PACKAGE_NAME = "-p"; protected static final String SWITCH_CACHE = "-cache"; protected static final String SWITCH_CLASS_NAME = "-c"; protected static final String SWITCH_FULL_STOP = "--"; protected static final String SWITCH_COMPILE = "-compile"; protected static final String SWITCH_FAIL_FAST = "-failFast"; protected static final String SWITCH_SOURCE = "-source"; protected static final String SWITCH_TARGET = "-target"; protected static final String SWITCH_URI_BASE = "-uribase"; protected static final String SWITCH_URI_ROOT = "-uriroot"; protected static final String SWITCH_FILE_WEBAPP = "-webapp"; protected static final String SWITCH_WEBAPP_INC = "-webinc"; protected static final String SWITCH_WEBAPP_FRG = "-webfrg"; protected static final String SWITCH_WEBAPP_XML = "-webxml"; protected static final String SWITCH_WEBAPP_XML_ENCODING = "-webxmlencoding"; protected static final String SWITCH_ADD_WEBAPP_XML_MAPPINGS = "-addwebxmlmappings"; protected static final String SWITCH_MAPPED = "-mapped"; protected static final String SWITCH_XPOWERED_BY = "-xpoweredBy"; protected static final String SWITCH_TRIM_SPACES = "-trimSpaces"; protected static final String SWITCH_CLASSPATH = "-classpath"; protected static final String SWITCH_DIE = "-die"; protected static final String SWITCH_POOLING = "-poolingEnabled"; protected static final String SWITCH_ENCODING = "-javaEncoding"; protected static final String SWITCH_SMAP = "-smap"; protected static final String SWITCH_DUMP_SMAP = "-dumpsmap"; protected static final String SWITCH_VALIDATE_TLD = "-validateTld"; protected static final String SWITCH_VALIDATE_XML = "-validateXml"; protected static final String SWITCH_NO_BLOCK_EXTERNAL = "-no-blockExternal"; protected static final String SWITCH_NO_STRICT_QUOTE_ESCAPING = "-no-strictQuoteEscaping"; protected static final String SWITCH_QUOTE_ATTRIBUTE_EL = "-quoteAttributeEL"; protected static final String SWITCH_NO_QUOTE_ATTRIBUTE_EL = "-no-quoteAttributeEL"; protected static final String SWITCH_THREAD_COUNT = "-threadCount"; protected static final String SHOW_SUCCESS ="-s"; protected static final String LIST_ERRORS = "-l"; protected static final int INC_WEBXML = 10; protected static final int FRG_WEBXML = 15; protected static final int ALL_WEBXML = 20; protected static final int DEFAULT_DIE_LEVEL = 1; protected static final int NO_DIE_LEVEL = 0; protected static final Set<String> insertBefore = new HashSet<>(); static { insertBefore.add("</web-app>"); insertBefore.add("<servlet-mapping>"); insertBefore.add("<session-config>"); insertBefore.add("<mime-mapping>"); insertBefore.add("<welcome-file-list>"); insertBefore.add("<error-page>"); insertBefore.add("<taglib>"); insertBefore.add("<resource-env-ref>"); insertBefore.add("<resource-ref>"); insertBefore.add("<security-constraint>"); insertBefore.add("<login-config>"); insertBefore.add("<security-role>"); insertBefore.add("<env-entry>"); insertBefore.add("<ejb-ref>"); insertBefore.add("<ejb-local-ref>"); } protected String classPath = null; protected ClassLoader loader = null; protected TrimSpacesOption trimSpaces = TrimSpacesOption.FALSE; protected boolean genStringAsCharArray = false; protected boolean validateTld; protected boolean validateXml; protected boolean blockExternal = true; protected boolean strictQuoteEscaping = true; protected boolean quoteAttributeEL = true; protected boolean xpoweredBy; protected boolean mappedFile = false; protected boolean poolingEnabled = true; protected File scratchDir; protected String targetPackage; protected String targetClassName; protected String uriBase; protected String uriRoot; protected int dieLevel; protected boolean helpNeeded = false; protected boolean compile = false; protected boolean failFast = false; protected boolean smapSuppressed = true; protected boolean smapDumped = false; protected boolean caching = true; protected final Map<String, TagLibraryInfo> cache = new HashMap<>(); protected String compiler = null; protected String compilerTargetVM = "17"; protected String compilerSourceVM = "17"; protected boolean classDebugInfo = true; /** * Throw an exception if there's a compilation error, or swallow it. * Default is true to preserve old behavior. */ protected boolean failOnError = true; /** * Should a separate process be forked to perform the compilation? */ private boolean fork = false; /** * The file extensions to be handled as JSP files. * Default list is .jsp and .jspx. */ protected List<String> extensions; /** * The pages. */ protected final List<String> pages = new ArrayList<>(); /** * Needs better documentation, this data member does. * True by default. */ protected boolean errorOnUseBeanInvalidClassAttribute = true; /** * The java file encoding. Default * is UTF-8. Added per bugzilla 19622. */ protected String javaEncoding = "UTF-8"; /** The number of threads to use; default is one per core */ protected int threadCount = Runtime.getRuntime().availableProcessors(); // Generation of web.xml fragments protected String webxmlFile; protected int webxmlLevel; protected String webxmlEncoding = "UTF-8"; protected boolean addWebXmlMappings = false; protected Writer mapout; protected CharArrayWriter servletout; protected CharArrayWriter mappingout; /** * The servlet context. */ protected JspCServletContext context; /** * The runtime context. * Maintain a dummy JspRuntimeContext for compiling tag files. */ protected JspRuntimeContext rctxt; /** * Cache for the TLD locations */ protected TldCache tldCache = null; protected JspConfig jspConfig = null; protected TagPluginManager tagPluginManager = null; protected TldScanner scanner = null; protected boolean verbose = false; protected boolean listErrors = false; protected boolean showSuccess = false; protected int argPos; protected boolean fullstop = false; protected String args[]; public static void main(String arg[]) { if (arg.length == 0) { System.out.println(Localizer.getMessage("jspc.usage")); } else { JspC jspc = new JspC(); try { jspc.setArgs(arg); if (jspc.helpNeeded) { System.out.println(Localizer.getMessage("jspc.usage")); } else { jspc.execute(); } } catch (JasperException | BuildException e) { System.err.println(e); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } } } } /** * Apply command-line arguments. * @param arg The arguments * @throws JasperException JSPC error */ public void setArgs(String[] arg) throws JasperException { args = arg; String tok; dieLevel = NO_DIE_LEVEL; while ((tok = nextArg()) != null) { if (tok.equals(SWITCH_VERBOSE)) { verbose = true; showSuccess = true; listErrors = true; } else if (tok.equals(SWITCH_OUTPUT_DIR)) { tok = nextArg(); setOutputDir( tok ); } else if (tok.equals(SWITCH_PACKAGE_NAME)) { targetPackage = nextArg(); } else if (tok.equals(SWITCH_COMPILE)) { compile=true; } else if (tok.equals(SWITCH_FAIL_FAST)) { failFast = true; } else if (tok.equals(SWITCH_CLASS_NAME)) { targetClassName = nextArg(); } else if (tok.equals(SWITCH_URI_BASE)) { uriBase=nextArg(); } else if (tok.equals(SWITCH_URI_ROOT)) { setUriroot( nextArg()); } else if (tok.equals(SWITCH_FILE_WEBAPP)) { setUriroot( nextArg()); } else if ( tok.equals( SHOW_SUCCESS ) ) { showSuccess = true; } else if ( tok.equals( LIST_ERRORS ) ) { listErrors = true; } else if (tok.equals(SWITCH_WEBAPP_INC)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = INC_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_FRG)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = FRG_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = ALL_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) { setWebXmlEncoding(nextArg()); } else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) { setAddWebXmlMappings(true); } else if (tok.equals(SWITCH_MAPPED)) { mappedFile = true; } else if (tok.equals(SWITCH_XPOWERED_BY)) { xpoweredBy = true; } else if (tok.equals(SWITCH_TRIM_SPACES)) { tok = nextArg(); if (TrimSpacesOption.SINGLE.toString().equalsIgnoreCase(tok)) { setTrimSpaces(TrimSpacesOption.SINGLE); } else { setTrimSpaces(TrimSpacesOption.TRUE); argPos--; } } else if (tok.equals(SWITCH_CACHE)) { tok = nextArg(); if ("false".equals(tok)) { caching = false; } else { caching = true; } } else if (tok.equals(SWITCH_CLASSPATH)) { setClassPath(nextArg()); } else if (tok.startsWith(SWITCH_DIE)) { try { dieLevel = Integer.parseInt( tok.substring(SWITCH_DIE.length())); } catch (NumberFormatException nfe) { dieLevel = DEFAULT_DIE_LEVEL; } } else if (tok.equals(SWITCH_HELP)) { helpNeeded = true; } else if (tok.equals(SWITCH_POOLING)) { tok = nextArg(); if ("false".equals(tok)) { poolingEnabled = false; } else { poolingEnabled = true; } } else if (tok.equals(SWITCH_ENCODING)) { setJavaEncoding(nextArg()); } else if (tok.equals(SWITCH_SOURCE)) { setCompilerSourceVM(nextArg()); } else if (tok.equals(SWITCH_TARGET)) { setCompilerTargetVM(nextArg()); } else if (tok.equals(SWITCH_SMAP)) { smapSuppressed = false; } else if (tok.equals(SWITCH_DUMP_SMAP)) { smapDumped = true; } else if (tok.equals(SWITCH_VALIDATE_TLD)) { setValidateTld(true); } else if (tok.equals(SWITCH_VALIDATE_XML)) { setValidateXml(true); } else if (tok.equals(SWITCH_NO_BLOCK_EXTERNAL)) { setBlockExternal(false); } else if (tok.equals(SWITCH_NO_STRICT_QUOTE_ESCAPING)) { setStrictQuoteEscaping(false); } else if (tok.equals(SWITCH_QUOTE_ATTRIBUTE_EL)) { setQuoteAttributeEL(true); } else if (tok.equals(SWITCH_NO_QUOTE_ATTRIBUTE_EL)) { setQuoteAttributeEL(false); } else if (tok.equals(SWITCH_THREAD_COUNT)) { setThreadCount(nextArg()); } else { if (tok.startsWith("-")) { throw new JasperException(Localizer.getMessage("jspc.error.unknownOption", tok)); } if (!fullstop) { argPos--; } // Start treating the rest as JSP Pages break; } } // Add all extra arguments to the list of files while( true ) { String file = nextFile(); if( file==null ) { break; } pages.add( file ); } } /** * In JspC this always returns <code>true</code>. * {@inheritDoc} */ @Override public boolean getKeepGenerated() { // isn't this why we are running jspc? return true; } @Override public TrimSpacesOption getTrimSpaces() { return trimSpaces; } public void setTrimSpaces(TrimSpacesOption trimSpaces) { this.trimSpaces = trimSpaces; } /** * Sets the option to control handling of template text that consists * entirely of whitespace. * * @param ts New value */ public void setTrimSpaces(String ts) { this.trimSpaces = TrimSpacesOption.valueOf(ts); } /* * Backwards compatibility with 8.5.x */ public void setTrimSpaces(boolean trimSpaces) { if (trimSpaces) { setTrimSpaces(TrimSpacesOption.TRUE); } else { setTrimSpaces(TrimSpacesOption.FALSE); } } @Override public boolean isPoolingEnabled() { return poolingEnabled; } /** * Sets the option to enable the tag handler pooling. * @param poolingEnabled New value */ public void setPoolingEnabled(boolean poolingEnabled) { this.poolingEnabled = poolingEnabled; } @Override public boolean isXpoweredBy() { return xpoweredBy; } /** * Sets the option to enable generation of X-Powered-By response header. * @param xpoweredBy New value */ public void setXpoweredBy(boolean xpoweredBy) { this.xpoweredBy = xpoweredBy; } /** * In JspC this always returns <code>true</code>. * {@inheritDoc} */ @Override public boolean getDisplaySourceFragment() { return true; } @Override public int getMaxLoadedJsps() { return -1; } @Override public int getJspIdleTimeout() { return -1; } @Override public boolean getErrorOnUseBeanInvalidClassAttribute() { return errorOnUseBeanInvalidClassAttribute; } /** * Sets the option to issue a compilation error if the class attribute * specified in useBean action is invalid. * @param b New value */ public void setErrorOnUseBeanInvalidClassAttribute(boolean b) { errorOnUseBeanInvalidClassAttribute = b; } @Override public boolean getMappedFile() { return mappedFile; } public void setMappedFile(boolean b) { mappedFile = b; } /** * Sets the option to include debug information in compiled class. * @param b New value */ public void setClassDebugInfo( boolean b ) { classDebugInfo=b; } @Override public boolean getClassDebugInfo() { // compile with debug info return classDebugInfo; } @Override public boolean isCaching() { return caching; } /** * Sets the option to enable caching. * @param caching New value * * @see Options#isCaching() */ public void setCaching(boolean caching) { this.caching = caching; } @Override public Map<String, TagLibraryInfo> getCache() { return cache; } /** * In JspC this always returns <code>0</code>. * {@inheritDoc} */ @Override public int getCheckInterval() { return 0; } /** * In JspC this always returns <code>0</code>. * {@inheritDoc} */ @Override public int getModificationTestInterval() { return 0; } /** * In JspC this always returns <code>false</code>. * {@inheritDoc} */ @Override public boolean getRecompileOnFail() { return false; } /** * In JspC this always returns <code>false</code>. * {@inheritDoc} */ @Override public boolean getDevelopment() { return false; } @Override public boolean isSmapSuppressed() { return smapSuppressed; } /** * Sets smapSuppressed flag. * @param smapSuppressed New value */ public void setSmapSuppressed(boolean smapSuppressed) { this.smapSuppressed = smapSuppressed; } @Override public boolean isSmapDumped() { return smapDumped; } /** * Sets smapDumped flag. * @param smapDumped New value * * @see Options#isSmapDumped() */ public void setSmapDumped(boolean smapDumped) { this.smapDumped = smapDumped; } /** * Determines whether text strings are to be generated as char arrays, * which improves performance in some cases. * * @param genStringAsCharArray true if text strings are to be generated as * char arrays, false otherwise */ public void setGenStringAsCharArray(boolean genStringAsCharArray) { this.genStringAsCharArray = genStringAsCharArray; } @Override public boolean genStringAsCharArray() { return genStringAsCharArray; } @Override public File getScratchDir() { return scratchDir; } @Override public String getCompiler() { return compiler; } /** * Sets the option to determine what compiler to use. * @param c New value * * @see Options#getCompiler() */ public void setCompiler(String c) { compiler=c; } @Override public String getCompilerClassName() { return null; } @Override public String getCompilerTargetVM() { return compilerTargetVM; } /** * Sets the compiler target VM. * @param vm New value * * @see Options#getCompilerTargetVM() */ public void setCompilerTargetVM(String vm) { compilerTargetVM = vm; } @Override public String getCompilerSourceVM() { return compilerSourceVM; } /** * Sets the compiler source VM. * @param vm New value * * @see Options#getCompilerSourceVM() */ public void setCompilerSourceVM(String vm) { compilerSourceVM = vm; } @Override public TldCache getTldCache() { return tldCache; } /** * Returns the encoding to use for * java files. The default is UTF-8. * * @return String The encoding */ @Override public String getJavaEncoding() { return javaEncoding; } /** * Sets the encoding to use for * java files. * * @param encodingName The name, e.g. "UTF-8" */ public void setJavaEncoding(String encodingName) { javaEncoding = encodingName; } @Override public boolean getFork() { return fork; } public void setFork(boolean fork) { this.fork = fork; } @Override public String getClassPath() { if( classPath != null ) { return classPath; } return System.getProperty("java.class.path"); } /** * Sets the classpath used while compiling the servlets generated from JSP * files * @param s New value */ public void setClassPath(String s) { classPath=s; } /** * Returns the list of file extensions * that are treated as JSP files. * * @return The list of extensions */ public List<String> getExtensions() { return extensions; } /** * Adds the given file extension to the * list of extensions handled as JSP files. * * @param extension The extension to add, e.g. "myjsp" */ protected void addExtension(final String extension) { if(extension != null) { if(extensions == null) { extensions = new ArrayList<>(); } extensions.add(extension); } } /** * Base dir for the webapp. Used to generate class names and resolve * includes. * @param s New value */ public void setUriroot( String s ) { if (s == null) { uriRoot = null; return; } try { uriRoot = resolveFile(s).getCanonicalPath(); } catch( Exception ex ) { uriRoot = s; } } /** * Parses comma-separated list of JSP files to be processed. If the argument * is null, nothing is done. * * <p>Each file is interpreted relative to uriroot, unless it is absolute, * in which case it must start with uriroot.</p> * * @param jspFiles Comma-separated list of JSP files to be processed */ public void setJspFiles(final String jspFiles) { if(jspFiles == null) { return; } StringTokenizer tok = new StringTokenizer(jspFiles, ","); while (tok.hasMoreTokens()) { pages.add(tok.nextToken()); } } /** * Sets the compile flag. * * @param b Flag value */ public void setCompile( final boolean b ) { compile = b; } /** * Sets the verbosity level. The actual number doesn't * matter: if it's greater than zero, the verbose flag will * be true. * * @param level Positive means verbose */ public void setVerbose( final int level ) { if (level > 0) { verbose = true; showSuccess = true; listErrors = true; } } public void setValidateTld( boolean b ) { this.validateTld = b; } public boolean isValidateTld() { return validateTld; } public void setValidateXml( boolean b ) { this.validateXml = b; } public boolean isValidateXml() { return validateXml; } public void setBlockExternal( boolean b ) { this.blockExternal = b; } public boolean isBlockExternal() { return blockExternal; } public void setStrictQuoteEscaping( boolean b ) { this.strictQuoteEscaping = b; } @Override public boolean getStrictQuoteEscaping() { return strictQuoteEscaping; } public void setQuoteAttributeEL(boolean b) { quoteAttributeEL = b; } @Override public boolean getQuoteAttributeEL() { return quoteAttributeEL; } public int getThreadCount() { return threadCount; } public void setThreadCount(String threadCount) { if (threadCount == null) { return; } int newThreadCount; try { if (threadCount.endsWith("C")) { double factor = Double.parseDouble(threadCount.substring(0, threadCount.length() - 1)); newThreadCount = (int) (factor * Runtime.getRuntime().availableProcessors()); } else { newThreadCount = Integer.parseInt(threadCount); } } catch (NumberFormatException e) { throw new BuildException(Localizer.getMessage("jspc.error.parseThreadCount", threadCount)); } if (newThreadCount < 1) { throw new BuildException(Localizer.getMessage( "jspc.error.minThreadCount", Integer.valueOf(newThreadCount))); } this.threadCount = newThreadCount; } public void setListErrors( boolean b ) { listErrors = b; } public void setOutputDir( String s ) { if( s!= null ) { scratchDir = resolveFile(s).getAbsoluteFile(); } else { scratchDir=null; } } /** * Sets the package name to be used for the generated servlet classes. * @param p New value */ public void setPackage( String p ) { targetPackage=p; } /** * Class name of the generated file ( without package ). * Can only be used if a single file is converted. * XXX Do we need this feature ? * @param p New value */ public void setClassName( String p ) { targetClassName=p; } /** * File where we generate configuration with the class definitions to be * included in a web.xml file. * @param s New value */ public void setWebXmlInclude( String s ) { webxmlFile=resolveFile(s).getAbsolutePath(); webxmlLevel=INC_WEBXML; } /** * File where we generate a complete web-fragment.xml with the class * definitions. * @param s New value */ public void setWebFragmentXml( String s ) { webxmlFile=resolveFile(s).getAbsolutePath(); webxmlLevel=FRG_WEBXML; } /** * File where we generate a complete web.xml with the class definitions. * @param s New value */ public void setWebXml( String s ) { webxmlFile=resolveFile(s).getAbsolutePath(); webxmlLevel=ALL_WEBXML; } /** * Sets the encoding to be used to read and write web.xml files. * * <p> * If not specified, defaults to UTF-8. * </p> * * @param encoding * Encoding, e.g. "UTF-8". */ public void setWebXmlEncoding(String encoding) { webxmlEncoding = encoding; } /** * Sets the option to merge generated web.xml fragment into the * WEB-INF/web.xml file of the web application that we were processing. * * @param b * <code>true</code> to merge the fragment into the existing * web.xml file of the processed web application * ({uriroot}/WEB-INF/web.xml), <code>false</code> to keep the * generated web.xml fragment */ public void setAddWebXmlMappings(boolean b) { addWebXmlMappings = b; } /** * Sets the option that throws an exception in case of a compilation error. * @param b New value */ public void setFailOnError(final boolean b) { failOnError = b; } /** * @return <code>true</code> if an exception will be thrown * in case of a compilation error. */ public boolean getFailOnError() { return failOnError; } @Override public JspConfig getJspConfig() { return jspConfig; } @Override public TagPluginManager getTagPluginManager() { return tagPluginManager; } /** * {@inheritDoc} * <p> * Hard-coded to {@code false} for pre-compiled code to enable repeatable * builds. */ @Override public boolean getGeneratedJavaAddTimestamp() { return false; } /** * Adds servlet declaration and mapping for the JSP page servlet to the * generated web.xml fragment. * * @param file * Context-relative path to the JSP file, e.g. * <code>/index.jsp</code> * @param clctxt * Compilation context of the servlet * @throws IOException An IO error occurred */ public void generateWebMapping( String file, JspCompilationContext clctxt ) throws IOException { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jspc.generatingMapping", file, clctxt)); } String className = clctxt.getServletClassName(); String packageName = clctxt.getServletPackageName(); String thisServletName; if (packageName.isEmpty()) { thisServletName = className; } else { thisServletName = packageName + '.' + className; } if (servletout != null) { synchronized(servletout) { servletout.write("\n <servlet>\n <servlet-name>"); servletout.write(thisServletName); servletout.write("</servlet-name>\n <servlet-class>"); servletout.write(thisServletName); servletout.write("</servlet-class>\n </servlet>\n"); } } if (mappingout != null) { synchronized(mappingout) { mappingout.write("\n <servlet-mapping>\n <servlet-name>"); mappingout.write(thisServletName); mappingout.write("</servlet-name>\n <url-pattern>"); mappingout.write(file.replace('\\', '/')); mappingout.write("</url-pattern>\n </servlet-mapping>\n"); } } } /** * Include the generated web.xml inside the webapp's web.xml. * @throws IOException An IO error occurred */ protected void mergeIntoWebXml() throws IOException { File webappBase = new File(uriRoot); File webXml = new File(webappBase, "WEB-INF/web.xml"); File webXml2 = new File(webappBase, "WEB-INF/web2.xml"); String insertStartMarker = Localizer.getMessage("jspc.webinc.insertStart"); String insertEndMarker = Localizer.getMessage("jspc.webinc.insertEnd"); try (BufferedReader reader = new BufferedReader(openWebxmlReader(webXml)); BufferedReader fragmentReader = new BufferedReader(openWebxmlReader(new File(webxmlFile))); PrintWriter writer = new PrintWriter(openWebxmlWriter(webXml2))) { // Insert the <servlet> and <servlet-mapping> declarations boolean inserted = false; int current = reader.read(); while (current > -1) { if (current == '<') { String element = getElement(reader); if (!inserted && insertBefore.contains(element)) { // Insert generated content here writer.println(insertStartMarker); while (true) { String line = fragmentReader.readLine(); if (line == null) { writer.println(); break; } writer.println(line); } writer.println(insertEndMarker); writer.println(); writer.write(element); inserted = true; } else if (element.equals(insertStartMarker)) { // Skip the previous auto-generated content while (true) { current = reader.read(); if (current < 0) { throw new EOFException(); } if (current == '<') { element = getElement(reader); if (element.equals(insertEndMarker)) { break; } } } current = reader.read(); while (current == '\n' || current == '\r') { current = reader.read(); } continue; } else { writer.write(element); } } else { writer.write(current); } current = reader.read(); } } try (FileInputStream fis = new FileInputStream(webXml2); FileOutputStream fos = new FileOutputStream(webXml)) { byte buf[] = new byte[512]; while (true) { int n = fis.read(buf); if (n < 0) { break; } fos.write(buf, 0, n); } } if(!webXml2.delete() && log.isDebugEnabled()) { log.debug(Localizer.getMessage("jspc.delete.fail", webXml2.toString())); } if (!(new File(webxmlFile)).delete() && log.isDebugEnabled()) { log.debug(Localizer.getMessage("jspc.delete.fail", webxmlFile)); } } /* * Assumes valid xml */ private String getElement(Reader reader) throws IOException { StringBuilder result = new StringBuilder(); result.append('<'); boolean done = false; while (!done) { int current = reader.read(); while (current != '>') { if (current < 0) { throw new EOFException(); } result.append((char) current); current = reader.read(); } result.append((char) current); int len = result.length(); if (len > 4 && result.substring(0, 4).equals("<!--")) { // This is a comment - make sure we are at the end if (len >= 7 && result.substring(len - 3, len).equals("-->")) { done = true; } } else { done = true; } } return result.toString(); } protected void processFile(String file) throws JasperException { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jspc.processing", file)); } ClassLoader originalClassLoader = null; Thread currentThread = Thread.currentThread(); try { // set up a scratch/output dir if none is provided if (scratchDir == null) { String temp = System.getProperty("java.io.tmpdir"); if (temp == null) { temp = ""; } scratchDir = new File(temp).getAbsoluteFile(); } String jspUri=file.replace('\\','/'); JspCompilationContext clctxt = new JspCompilationContext ( jspUri, this, context, null, rctxt ); /* Override the defaults */ if ((targetClassName != null) && (targetClassName.length() > 0)) { clctxt.setServletClassName(targetClassName); targetClassName = null; } if (targetPackage != null) { clctxt.setBasePackageName(targetPackage); } originalClassLoader = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(loader); clctxt.setClassLoader(loader); clctxt.setClassPath(classPath); Compiler clc = clctxt.createCompiler(); // If compile is set, generate both .java and .class, if // .jsp file is newer than .class file; // Otherwise only generate .java, if .jsp file is newer than // the .java file if( clc.isOutDated(compile) ) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jspc.outdated", jspUri)); } clc.compile(compile, true); } // Generate mapping generateWebMapping( file, clctxt ); if ( showSuccess ) { log.info(Localizer.getMessage("jspc.built", file)); } } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } throw je; } catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); } finally { if (originalClassLoader != null) { currentThread.setContextClassLoader(originalClassLoader); } } } /** * Locate all jsp files in the webapp. Used if no explicit jsps are * specified. Scan is performed via the ServletContext and will include any * JSPs located in resource JARs. */ public void scanFiles() { // Make sure default extensions are always included if ((getExtensions() == null) || (getExtensions().size() < 2)) { addExtension("jsp"); addExtension("jspx"); } scanFilesInternal("/"); } private void scanFilesInternal(String input) { Set<String> paths = context.getResourcePaths(input); for (String path : paths) { if (path.endsWith("/")) { scanFilesInternal(path); } else if (jspConfig.isJspPage(path)) { pages.add(path); } else { String ext = path.substring(path.lastIndexOf('.') + 1); if (extensions.contains(ext)) { pages.add(path); } } } } /** * Executes the compilation. */ @Override public void execute() { if(log.isDebugEnabled()) { log.debug(Localizer.getMessage("jspc.start", Integer.toString(pages.size()))); } try { if (uriRoot == null) { if (pages.size() == 0) { throw new JasperException(Localizer.getMessage("jsp.error.jspc.missingTarget")); } String firstJsp = pages.get(0); File firstJspF = new File(firstJsp); if (!firstJspF.exists()) { throw new JasperException(Localizer.getMessage( "jspc.error.fileDoesNotExist", firstJsp)); } locateUriRoot(firstJspF); } if (uriRoot == null) { throw new JasperException(Localizer.getMessage("jsp.error.jspc.no_uriroot")); } File uriRootF = new File(uriRoot); if (!uriRootF.isDirectory()) { throw new JasperException(Localizer.getMessage("jsp.error.jspc.uriroot_not_dir")); } if (loader == null) { loader = initClassLoader(); } if (context == null) { initServletContext(loader); } // No explicit pages, we'll process all .jsp in the webapp if (pages.size() == 0) { scanFiles(); } else { // Ensure pages are all relative to the uriRoot. // Those that are not will trigger an error later. The error // could be detected earlier but isn't to support the use case // when failFast is not used. for (int i = 0; i < pages.size(); i++) { String nextjsp = pages.get(i); File fjsp = new File(nextjsp); if (!fjsp.isAbsolute()) { fjsp = new File(uriRootF, nextjsp); } if (!fjsp.exists()) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jspc.error.fileDoesNotExist", fjsp.toString())); } continue; } String s = fjsp.getAbsolutePath(); if (s.startsWith(uriRoot)) { nextjsp = s.substring(uriRoot.length()); } if (nextjsp.startsWith("." + File.separatorChar)) { nextjsp = nextjsp.substring(2); } pages.set(i, nextjsp); } } initWebXml(); int errorCount = 0; long start = System.currentTimeMillis(); ExecutorService threadPool = Executors.newFixedThreadPool(threadCount); ExecutorCompletionService<Void> service = new ExecutorCompletionService<>(threadPool); try { int pageCount = pages.size(); for (String nextjsp : pages) { service.submit(new ProcessFile(nextjsp)); } JasperException reportableError = null; for (int i = 0; i < pageCount; i++) { try { service.take().get(); } catch (ExecutionException e) { if (failFast) { // Generation is not interruptible so any tasks that // have started will complete. List<Runnable> notExecuted = threadPool.shutdownNow(); i += notExecuted.size(); Throwable t = e.getCause(); if (t instanceof JasperException) { reportableError = (JasperException) t; } else { reportableError = new JasperException(t); } } else { errorCount++; log.error(Localizer.getMessage("jspc.error.compilation"), e); } } catch (InterruptedException e) { // Ignore } } if (reportableError != null) { throw reportableError; } } finally { threadPool.shutdown(); } long time = System.currentTimeMillis() - start; String msg = Localizer.getMessage("jspc.generation.result", Integer.toString(errorCount), Long.toString(time)); if (failOnError && errorCount > 0) { System.out.println(Localizer.getMessage( "jspc.errorCount", Integer.valueOf(errorCount))); throw new BuildException(msg); } else { log.info(msg); } completeWebXml(); if (addWebXmlMappings) { mergeIntoWebXml(); } } catch (IOException ioe) { throw new BuildException(ioe); } catch (JasperException je) { if (failOnError) { throw new BuildException(je); } } finally { if (loader != null) { LogFactory.release(loader); } } } // ==================== protected utility methods ==================== protected String nextArg() { if ((argPos >= args.length) || (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) { return null; } else { return args[argPos++]; } } protected String nextFile() { if (fullstop) { argPos++; } if (argPos >= args.length) { return null; } else { return args[argPos++]; } } protected void initWebXml() throws JasperException { try { if (webxmlLevel >= INC_WEBXML) { mapout = openWebxmlWriter(new File(webxmlFile)); servletout = new CharArrayWriter(); mappingout = new CharArrayWriter(); } else { mapout = null; servletout = null; mappingout = null; } if (webxmlLevel >= ALL_WEBXML) { mapout.write(Localizer.getMessage("jspc.webxml.header", webxmlEncoding)); mapout.flush(); } else if (webxmlLevel >= FRG_WEBXML) { mapout.write(Localizer.getMessage("jspc.webfrg.header", webxmlEncoding)); mapout.flush(); } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) { mapout.write(Localizer.getMessage("jspc.webinc.header")); mapout.flush(); } } catch (IOException ioe) { mapout = null; servletout = null; mappingout = null; throw new JasperException(ioe); } } protected void completeWebXml() { if (mapout != null) { try { servletout.writeTo(mapout); mappingout.writeTo(mapout); if (webxmlLevel >= ALL_WEBXML) { mapout.write(Localizer.getMessage("jspc.webxml.footer")); } else if (webxmlLevel >= FRG_WEBXML) { mapout.write(Localizer.getMessage("jspc.webfrg.footer")); } else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings) { mapout.write(Localizer.getMessage("jspc.webinc.footer")); } mapout.close(); } catch (IOException ioe) { // nothing to do if it fails since we are done with it } } } protected void initTldScanner(JspCServletContext context, ClassLoader classLoader) { if (scanner != null) { return; } scanner = newTldScanner(context, true, isValidateTld(), isBlockExternal()); scanner.setClassLoader(classLoader); } protected TldScanner newTldScanner(JspCServletContext context, boolean namespaceAware, boolean validate, boolean blockExternal) { return new TldScanner(context, namespaceAware, validate, blockExternal); } protected void initServletContext(ClassLoader classLoader) throws IOException, JasperException { // TODO: should we use the Ant Project's log? PrintWriter log = new PrintWriter(System.out); URL resourceBase = new File(uriRoot).getCanonicalFile().toURI().toURL(); context = new JspCServletContext(log, resourceBase, classLoader, isValidateXml(), isBlockExternal()); if (isValidateTld()) { context.setInitParameter(Constants.XML_VALIDATION_TLD_INIT_PARAM, "true"); } initTldScanner(context, classLoader); try { scanner.scan(); } catch (SAXException e) { throw new JasperException(e); } tldCache = new TldCache(context, scanner.getUriTldResourcePathMap(), scanner.getTldResourcePathTaglibXmlMap()); context.setAttribute(TldCache.SERVLET_CONTEXT_ATTRIBUTE_NAME, tldCache); rctxt = new JspRuntimeContext(context, this); jspConfig = new JspConfig(context); tagPluginManager = new TagPluginManager(context); } /** * Initializes the classloader as/if needed for the given * compilation context. * @return the classloader that will be used * @throws IOException If an error occurs */ protected ClassLoader initClassLoader() throws IOException { classPath = getClassPath(); ClassLoader jspcLoader = getClass().getClassLoader(); if (jspcLoader instanceof AntClassLoader) { classPath += File.pathSeparator + ((AntClassLoader) jspcLoader).getClasspath(); } // Turn the classPath into URLs List<URL> urls = new ArrayList<>(); StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { File libFile = new File(path); urls.add(libFile.toURI().toURL()); } catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); } } File webappBase = new File(uriRoot); if (webappBase.exists()) { File classes = new File(webappBase, "/WEB-INF/classes"); try { if (classes.exists()) { classPath = classPath + File.pathSeparator + classes.getCanonicalPath(); urls.add(classes.getCanonicalFile().toURI().toURL()); } } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } File webinfLib = new File(webappBase, "/WEB-INF/lib"); if (webinfLib.exists() && webinfLib.isDirectory()) { String[] libs = webinfLib.list(); if (libs != null) { for (String lib : libs) { if (lib.length() < 5) { continue; } String ext = lib.substring(lib.length() - 4); if (!".jar".equalsIgnoreCase(ext)) { if (".tld".equalsIgnoreCase(ext)) { log.warn(Localizer.getMessage("jspc.warning.tldInWebInfLib")); } continue; } try { File libFile = new File(webinfLib, lib); classPath = classPath + File.pathSeparator + libFile.getAbsolutePath(); urls.add(libFile.getAbsoluteFile().toURI().toURL()); } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } } } } } URL[] urlsA = urls.toArray(new URL[0]); loader = new URLClassLoader(urlsA, this.getClass().getClassLoader()); return loader; } /** * Find the WEB-INF dir by looking up in the directory tree. * This is used if no explicit docbase is set, but only files. * * @param f The path from which it will start looking */ protected void locateUriRoot( File f ) { String tUriBase = uriBase; if (tUriBase == null) { tUriBase = "/"; } try { if (f.exists()) { f = new File(f.getAbsolutePath()); while (true) { File g = new File(f, "WEB-INF"); if (g.exists() && g.isDirectory()) { uriRoot = f.getCanonicalPath(); uriBase = tUriBase; if (log.isInfoEnabled()) { log.info(Localizer.getMessage( "jspc.implicit.uriRoot", uriRoot)); } break; } if (f.exists() && f.isDirectory()) { tUriBase = "/" + f.getName() + "/" + tUriBase; } String fParent = f.getParent(); if (fParent == null) { break; } else { f = new File(fParent); } // If there is no acceptable candidate, uriRoot will // remain null. } if (uriRoot != null) { File froot = new File(uriRoot); uriRoot = froot.getCanonicalPath(); } } } catch (IOException ioe) { // Missing uriRoot will be handled in the caller. } } /** * Resolves the relative or absolute pathname correctly * in both Ant and command-line situations. If Ant launched * us, we should use the basedir of the current project * to resolve relative paths. * * See Bugzilla 35571. * * @param s The file * @return The file resolved */ protected File resolveFile(final String s) { if(getProject() == null) { // Note FileUtils.getFileUtils replaces FileUtils.newFileUtils in Ant 1.6.3 return FileUtils.getFileUtils().resolveFile(null, s); } else { return FileUtils.getFileUtils().resolveFile(getProject().getBaseDir(), s); } } private Reader openWebxmlReader(File file) throws IOException { FileInputStream fis = new FileInputStream(file); try { return webxmlEncoding != null ? new InputStreamReader(fis, webxmlEncoding) : new InputStreamReader(fis); } catch (IOException ex) { fis.close(); throw ex; } } private Writer openWebxmlWriter(File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); try { return webxmlEncoding != null ? new OutputStreamWriter(fos, webxmlEncoding) : new OutputStreamWriter(fos); } catch (IOException ex) { fos.close(); throw ex; } } private class ProcessFile implements Callable<Void> { private final String file; private ProcessFile(String file) { this.file = file; } @Override public Void call() throws Exception { processFile(file); return null; } } }
apache/tomcat
java/org/apache/jasper/JspC.java
2,106
/** * 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 backtype.storm.task; import backtype.storm.Config; import backtype.storm.generated.ShellComponent; import backtype.storm.tuple.MessageId; import backtype.storm.tuple.Tuple; import backtype.storm.utils.Utils; import backtype.storm.utils.ShellProcess; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import static java.util.concurrent.TimeUnit.SECONDS; import java.util.List; import java.util.Map; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.json.simple.JSONObject; /** * A bolt that shells out to another process to process tuples. ShellBolt * communicates with that process over stdio using a special protocol. An ~100 * line library is required to implement that protocol, and adapter libraries * currently exist for Ruby and Python. * * <p>To run a ShellBolt on a cluster, the scripts that are shelled out to must be * in the resources directory within the jar submitted to the master. * During development/testing on a local machine, that resources directory just * needs to be on the classpath.</p> * * <p>When creating topologies using the Java API, subclass this bolt and implement * the IRichBolt interface to create components for the topology that use other languages. For example: * </p> * * <pre> * public class MyBolt extends ShellBolt implements IRichBolt { * public MyBolt() { * super("python", "mybolt.py"); * } * * public void declareOutputFields(OutputFieldsDeclarer declarer) { * declarer.declare(new Fields("field1", "field2")); * } * } * </pre> */ public class ShellBolt implements IBolt { public static Logger LOG = LoggerFactory.getLogger(ShellBolt.class); Process _subprocess; OutputCollector _collector; Map<String, Tuple> _inputs = new ConcurrentHashMap<String, Tuple>(); private String[] _command; private ShellProcess _process; private volatile boolean _running = true; private volatile Throwable _exception; private LinkedBlockingQueue _pendingWrites = new LinkedBlockingQueue(); private Random _rand; private Thread _readerThread; private Thread _writerThread; public ShellBolt(ShellComponent component) { this(component.get_execution_command(), component.get_script()); } public ShellBolt(String... command) { _command = command; } public void prepare(Map stormConf, TopologyContext context, final OutputCollector collector) { Object maxPending = stormConf.get(Config.TOPOLOGY_SHELLBOLT_MAX_PENDING); if (maxPending != null) { this._pendingWrites = new LinkedBlockingQueue(((Number)maxPending).intValue()); } _rand = new Random(); _process = new ShellProcess(_command); _collector = collector; try { //subprocesses must send their pid first thing Number subpid = _process.launch(stormConf, context); LOG.info("Launched subprocess with pid " + subpid); } catch (IOException e) { throw new RuntimeException("Error when launching multilang subprocess\n" + _process.getErrorsString(), e); } // reader _readerThread = new Thread(new Runnable() { public void run() { while (_running) { try { JSONObject action = _process.readMessage(); if (action == null) { // ignore sync } String command = (String) action.get("command"); if(command.equals("ack")) { handleAck(action); } else if (command.equals("fail")) { handleFail(action); } else if (command.equals("error")) { handleError(action); } else if (command.equals("log")) { String msg = (String) action.get("msg"); LOG.info("Shell msg: " + msg); } else if (command.equals("emit")) { handleEmit(action); } } catch (InterruptedException e) { } catch (Throwable t) { die(t); } } } }); _readerThread.start(); _writerThread = new Thread(new Runnable() { public void run() { while (_running) { try { Object write = _pendingWrites.poll(1, SECONDS); if (write != null) { _process.writeMessage(write); } // drain the error stream to avoid dead lock because of full error stream buffer _process.drainErrorStream(); } catch (InterruptedException e) { } catch (Throwable t) { die(t); } } } }); _writerThread.start(); } public void execute(Tuple input) { if (_exception != null) { throw new RuntimeException(_exception); } //just need an id String genId = Long.toString(_rand.nextLong()); _inputs.put(genId, input); try { JSONObject obj = new JSONObject(); obj.put("id", genId); obj.put("comp", input.getSourceComponent()); obj.put("stream", input.getSourceStreamId()); obj.put("task", input.getSourceTask()); obj.put("tuple", input.getValues()); _pendingWrites.put(obj); } catch(InterruptedException e) { throw new RuntimeException("Error during multilang processing", e); } } public void cleanup() { _running = false; _process.destroy(); _inputs.clear(); } private void handleAck(Map action) { String id = (String) action.get("id"); Tuple acked = _inputs.remove(id); if(acked==null) { throw new RuntimeException("Acked a non-existent or already acked/failed id: " + id); } _collector.ack(acked); } private void handleFail(Map action) { String id = (String) action.get("id"); Tuple failed = _inputs.remove(id); if(failed==null) { throw new RuntimeException("Failed a non-existent or already acked/failed id: " + id); } _collector.fail(failed); } private void handleError(Map action) { String msg = (String) action.get("msg"); _collector.reportError(new Exception("Shell Process Exception: " + msg)); } private void handleEmit(Map action) throws InterruptedException { String stream = (String) action.get("stream"); if(stream==null) stream = Utils.DEFAULT_STREAM_ID; Long task = (Long) action.get("task"); List<Object> tuple = (List) action.get("tuple"); List<Tuple> anchors = new ArrayList<Tuple>(); Object anchorObj = action.get("anchors"); if(anchorObj!=null) { if(anchorObj instanceof String) { anchorObj = Arrays.asList(anchorObj); } for(Object o: (List) anchorObj) { Tuple t = _inputs.get((String) o); if (t == null) { throw new RuntimeException("Anchored onto " + o + " after ack/fail"); } anchors.add(t); } } if(task==null) { List<Integer> outtasks = _collector.emit(stream, anchors, tuple); Object need_task_ids = action.get("need_task_ids"); if (need_task_ids == null || ((Boolean) need_task_ids).booleanValue()) { _pendingWrites.put(outtasks); } } else { _collector.emitDirect((int)task.longValue(), stream, anchors, tuple); } } private void die(Throwable exception) { _exception = exception; } }
xumingming/storm
storm-core/src/jvm/backtype/storm/task/ShellBolt.java
2,107
class Solution { public int dietPlanPerformance(int[] calories, int k, int lower, int upper) { int n = calories.length; int[] s = new int[n + 1]; for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + calories[i]; } int ans = 0; for (int i = 0; i < n - k + 1; ++i) { int t = s[i + k] - s[i]; if (t < lower) { --ans; } else if (t > upper) { ++ans; } } return ans; } }
doocs/leetcode
solution/1100-1199/1176.Diet Plan Performance/Solution.java
2,108
//There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. //They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the //minimum amount of pigs you need to figure out which bucket contains the poison within one hour. //Answer this question, and write an algorithm for the follow-up general case. //Follow-up: //If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) //you need to figure out the "poison" bucket within p minutes? There is exact one bucket with poison. class PoorPigs { public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int numPigs = 0; while (Math.pow(minutesToTest / minutesToDie + 1, numPigs) < buckets) { numPigs++; } return numPigs; } }
kdn251/interviews
leetcode/math/PoorPigs.java
2,109
// This file is part of OpenTSDB. // Copyright (C) 2010-2014 The OpenTSDB Authors. // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 2.1 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 Lesser // General Public License for more details. You should have received a copy // of the GNU Lesser General Public License along with this program. If not, // see <http://www.gnu.org/licenses/>. package net.opentsdb.tsd; import java.io.IOException; import java.lang.reflect.Method; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.util.concurrent.Atomics; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import org.jboss.netty.channel.Channel; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.opentsdb.tools.BuildData; import net.opentsdb.core.Aggregators; import net.opentsdb.core.TSDB; import net.opentsdb.core.TSDB.OperationMode; import net.opentsdb.query.filter.TagVFilter; import net.opentsdb.stats.StatsCollector; import net.opentsdb.utils.Config; import net.opentsdb.utils.JSON; import net.opentsdb.utils.PluginLoader; /** * Manager for the lifecycle of <code>HttpRpc</code>s, <code>TelnetRpc</code>s, * <code>RpcPlugin</code>s, and <code>HttpRpcPlugin</code>. This is a * singleton. Its lifecycle must be managed by the "container". If you are * launching via {@code TSDMain} then shutdown (and non-lazy initialization) * is taken care of. Outside of the use of {@code TSDMain}, you are responsible * for shutdown, at least. * * <p> Here's an example of how to correctly handle shutdown manually: * * <pre> * // Startup our TSDB instance... * TSDB tsdb_instance = ...; * * // ... later, during shtudown .. * * if (RpcManager.isInitialized()) { * // Check that its actually been initialized. We don't want to * // create a new instance only to shutdown! * RpcManager.instance(tsdb_instance).shutdown().join(); * } * </pre> * * @since 2.2 */ public final class RpcManager { private static final Logger LOG = LoggerFactory.getLogger(RpcManager.class); /** This is base path where {@link HttpRpcPlugin}s are rooted. It's used * to match incoming requests. */ @VisibleForTesting protected static final String PLUGIN_BASE_WEBPATH = "plugin"; /** Splitter for web paths. Removes empty strings to handle trailing or * leading slashes. For instance, all of <code>/plugin/mytest</code>, * <code>plugin/mytest/</code>, and <code>plugin/mytest</code> will be * split to <code>[plugin, mytest]</code>. */ private static final Splitter WEBPATH_SPLITTER = Splitter.on('/') .trimResults() .omitEmptyStrings(); /** Matches paths declared by {@link HttpRpcPlugin}s that are rooted in * the system's plugins path. */ private static final Pattern HAS_PLUGIN_BASE_WEBPATH = Pattern.compile( "^/?" + PLUGIN_BASE_WEBPATH + "/?.*", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); /** Reference to our singleton instance. Set in {@link #initialize}. */ private static final AtomicReference<RpcManager> INSTANCE = Atomics.newReference(); /** Commands we can serve on the simple, telnet-style RPC interface. */ private ImmutableMap<String, TelnetRpc> telnet_commands; /** Commands we serve on the HTTP interface. */ private ImmutableMap<String, HttpRpc> http_commands; /** HTTP commands from user plugins. */ private ImmutableMap<String, HttpRpcPlugin> http_plugin_commands; /** List of activated RPC plugins */ private ImmutableList<RpcPlugin> rpc_plugins; /** The TSDB that owns us. */ private TSDB tsdb; /** * Constructor used by singleton factory method. * @param tsdb the owning TSDB instance. */ private RpcManager(final TSDB tsdb) { this.tsdb = tsdb; } /** * Get or create the singleton instance of the manager, loading all the * plugins enabled in the given TSDB's {@link Config}. * @return the shared instance of {@link RpcManager}. It's okay to * hold this reference once obtained. */ public static synchronized RpcManager instance(final TSDB tsdb) { final RpcManager existing = INSTANCE.get(); if (existing != null) { return existing; } final RpcManager manager = new RpcManager(tsdb); // Load any plugins that are enabled via Config. Fail if any plugin cannot be loaded. final ImmutableList.Builder<RpcPlugin> rpcBuilder = ImmutableList.builder(); if (tsdb.getConfig().hasProperty("tsd.rpc.plugins")) { final String[] plugins = tsdb.getConfig().getString("tsd.rpc.plugins").split(","); manager.initializeRpcPlugins(plugins, rpcBuilder); } manager.rpc_plugins = rpcBuilder.build(); final ImmutableMap.Builder<String, TelnetRpc> telnetBuilder = ImmutableMap.builder(); final ImmutableMap.Builder<String, HttpRpc> httpBuilder = ImmutableMap.builder(); manager.initializeBuiltinRpcs(tsdb.getMode(), telnetBuilder, httpBuilder); manager.telnet_commands = telnetBuilder.build(); manager.http_commands = httpBuilder.build(); final ImmutableMap.Builder<String, HttpRpcPlugin> httpPluginsBuilder = ImmutableMap.builder(); if (tsdb.getConfig().hasProperty("tsd.http.rpc.plugins")) { final String[] plugins = tsdb.getConfig().getString("tsd.http.rpc.plugins").split(","); manager.initializeHttpRpcPlugins(tsdb.getMode(), plugins, httpPluginsBuilder); } manager.http_plugin_commands = httpPluginsBuilder.build(); INSTANCE.set(manager); return manager; } /** * @return {@code true} if the shared instance has been initialized; * {@code false} otherwise. */ public static synchronized boolean isInitialized() { return INSTANCE.get() != null; } /** * @return list of loaded {@link RpcPlugin}s. Possibly empty but * never {@code null}. */ @VisibleForTesting protected ImmutableList<RpcPlugin> getRpcPlugins() { return rpc_plugins; } /** * Lookup a {@link TelnetRpc} based on given command name. Note that this * lookup is case sensitive in that the {@code command} passed in must * match a registered RPC command exactly. * @param command a telnet API command name. * @return the {@link TelnetRpc} for the given {@code command} or {@code null} * if not found. */ TelnetRpc lookupTelnetRpc(final String command) { return telnet_commands.get(command); } /** * Lookup a built-in {@link HttpRpc} based on the given {@code queryBaseRoute}. * The lookup is based on exact match of the input parameter and the registered * {@link HttpRpc}s. * @param queryBaseRoute the HTTP query's base route, with no trailing or * leading slashes. For example: {@code api/query} * @return the {@link HttpRpc} for the given {@code queryBaseRoute} or * {@code null} if not found. */ HttpRpc lookupHttpRpc(final String queryBaseRoute) { return http_commands.get(queryBaseRoute); } /** * Lookup a user-supplied {@link HttpRpcPlugin} for the given * {@code queryBaseRoute}. The lookup is based on exact match of the input * parameter and the registered {@link HttpRpcPlugin}s. * @param queryBaseRoute the value of {@link HttpRpcPlugin#getPath()} with no * trailing or leading slashes. * @return the {@link HttpRpcPlugin} for the given {@code queryBaseRoute} or * {@code null} if not found. */ HttpRpcPlugin lookupHttpRpcPlugin(final String queryBaseRoute) { return http_plugin_commands.get(queryBaseRoute); } /** * @param uri HTTP request URI, with or without query parameters. * @return {@code true} if the URI represents a request for a * {@link HttpRpcPlugin}; {@code false} otherwise. Note that this * method returning true <strong>says nothing</strong> about * whether or not there is a {@link HttpRpcPlugin} registered * at the given URI, only that it's a valid RPC plugin request. */ boolean isHttpRpcPluginPath(final String uri) { if (Strings.isNullOrEmpty(uri) || uri.length() <= PLUGIN_BASE_WEBPATH.length()) { return false; } else { // Don't consider the query portion, if any. int qmark = uri.indexOf('?'); String path = uri; if (qmark != -1) { path = uri.substring(0, qmark); } final List<String> parts = WEBPATH_SPLITTER.splitToList(path); return (parts.size() > 1 && parts.get(0).equals(PLUGIN_BASE_WEBPATH)); } } /** * Load and init instances of {@link TelnetRpc}s and {@link HttpRpc}s. * These are not generally configurable via TSDB config. * @param mode is this TSD in read/write ("rw") or read-only ("ro") * mode? * @param telnet a map of telnet command names to {@link TelnetRpc} * instances. * @param http a map of API endpoints to {@link HttpRpc} instances. */ private void initializeBuiltinRpcs(final OperationMode mode, final ImmutableMap.Builder<String, TelnetRpc> telnet, final ImmutableMap.Builder<String, HttpRpc> http) { final Boolean enableApi = tsdb.getConfig().getString("tsd.core.enable_api").equals("true"); final Boolean enableUi = tsdb.getConfig().getString("tsd.core.enable_ui").equals("true"); final Boolean enableDieDieDie = tsdb.getConfig().getString("tsd.no_diediedie").equals("false"); LOG.info("Mode: {}, HTTP UI Enabled: {}, HTTP API Enabled: {}", mode, enableUi, enableApi); // defaults common to every mode final StatsRpc stats = new StatsRpc(); final ListAggregators aggregators = new ListAggregators(); final DropCachesRpc dropcaches = new DropCachesRpc(); final Version version = new Version(); telnet.put("stats", stats); telnet.put("dropcaches", dropcaches); telnet.put("version", version); telnet.put("exit", new Exit()); telnet.put("help", new Help()); if (enableUi) { http.put("aggregators", aggregators); http.put("logs", new LogsRpc()); http.put("stats", stats); http.put("version", version); } if (enableApi) { http.put("api/aggregators", aggregators); http.put("api/config", new ShowConfig()); http.put("api/dropcaches", dropcaches); http.put("api/stats", stats); http.put("api/version", version); } final PutDataPointRpc put = new PutDataPointRpc(tsdb.getConfig()); final RollupDataPointRpc rollups = new RollupDataPointRpc(tsdb.getConfig()); final HistogramDataPointRpc histos = new HistogramDataPointRpc(tsdb.getConfig()); final SuggestRpc suggest_rpc = new SuggestRpc(); final AnnotationRpc annotation_rpc = new AnnotationRpc(); final StaticFileRpc staticfile = new StaticFileRpc(); switch(mode) { case WRITEONLY: telnet.put("put", put); telnet.put("rollup", rollups); telnet.put("histogram", histos); if (enableApi) { http.put("api/annotation", annotation_rpc); http.put("api/annotations", annotation_rpc); http.put("api/put", put); http.put("api/rollup", rollups); http.put("api/histogram", histos); http.put("api/tree", new TreeRpc()); http.put("api/uid", new UniqueIdRpc()); } break; case READONLY: if (enableUi) { http.put("", new HomePage()); http.put("s", staticfile); http.put("favicon.ico", staticfile); http.put("suggest", suggest_rpc); http.put("q", new GraphHandler()); } if (enableApi) { http.put("api/query", new QueryRpc()); http.put("api/search", new SearchRpc()); http.put("api/suggest", suggest_rpc); } break; case READWRITE: telnet.put("put", put); telnet.put("rollup", rollups); telnet.put("histogram", histos); if (enableUi) { http.put("", new HomePage()); http.put("s", staticfile); http.put("favicon.ico", staticfile); http.put("suggest", suggest_rpc); http.put("q", new GraphHandler()); } if (enableApi) { http.put("api/query", new QueryRpc()); http.put("api/search", new SearchRpc()); http.put("api/annotation", annotation_rpc); http.put("api/annotations", annotation_rpc); http.put("api/suggest", suggest_rpc); http.put("api/put", put); http.put("api/rollup", rollups); http.put("api/histogram", histos); http.put("api/tree", new TreeRpc()); http.put("api/uid", new UniqueIdRpc()); } } if (enableDieDieDie) { final DieDieDie diediedie = new DieDieDie(); telnet.put("diediedie", diediedie); if (enableUi) { http.put("diediedie", diediedie); } } } /** * Load and init the {@link HttpRpcPlugin}s provided as an array of * {@code pluginClassNames}. * @param mode is this TSD in read/write ("rw") or read-only ("ro") * mode? * @param pluginClassNames fully-qualified class names that are * instances of {@link HttpRpcPlugin}s * @param http a map of canonicalized paths * (obtained via {@link #canonicalizePluginPath(String)}) * to {@link HttpRpcPlugin} instance. */ @VisibleForTesting protected void initializeHttpRpcPlugins(final OperationMode mode, final String[] pluginClassNames, final ImmutableMap.Builder<String, HttpRpcPlugin> http) { for (final String plugin : pluginClassNames) { final HttpRpcPlugin rpc = createAndInitialize(plugin, HttpRpcPlugin.class); validateHttpRpcPluginPath(rpc.getPath()); final String path = rpc.getPath().trim(); final String canonicalized_path = canonicalizePluginPath(path); http.put(canonicalized_path, rpc); LOG.info("Mounted HttpRpcPlugin [{}] at path \"{}\"", rpc.getClass().getName(), canonicalized_path); } } /** * Ensure that the given path for an {@link HttpRpcPlugin} is valid. This * method simply returns for valid inputs; throws and exception otherwise. * @param path a request path, no query parameters, etc. * @throws IllegalArgumentException on invalid paths. */ @VisibleForTesting protected void validateHttpRpcPluginPath(final String path) { Preconditions.checkArgument(!Strings.isNullOrEmpty(path), "Invalid HttpRpcPlugin path. Path is null or empty."); final String testPath = path.trim(); Preconditions.checkArgument(!HAS_PLUGIN_BASE_WEBPATH.matcher(path).matches(), "Invalid HttpRpcPlugin path %s. Path contains system's plugin base path.", testPath); URI uri = URI.create(testPath); Preconditions.checkArgument(!Strings.isNullOrEmpty(uri.getPath()), "Invalid HttpRpcPlugin path %s. Parsed path is null or empty.", testPath); Preconditions.checkArgument(!uri.getPath().equals("/"), "Invalid HttpRpcPlugin path %s. Path is equal to root.", testPath); Preconditions.checkArgument(Strings.isNullOrEmpty(uri.getQuery()), "Invalid HttpRpcPlugin path %s. Path contains query parameters.", testPath); } /** * @param origPath a request path, no query parameters, etc. * @return a canonical representation of the input, with trailing and leading * slashes removed. * @throws IllegalArgumentException if the given path is a root. */ @VisibleForTesting protected String canonicalizePluginPath(final String origPath) { Preconditions.checkArgument(!(Strings.isNullOrEmpty(origPath) || origPath.equals("/")), "Path %s is a root.", origPath); String new_path = origPath; if (new_path.startsWith("/")) { new_path = new_path.substring(1); } if (new_path.endsWith("/")) { new_path = new_path.substring(0, new_path.length()-1); } return new_path; } /** * Load and init the {@link RpcPlugin}s provided as an array of * {@code pluginClassNames}. * @param pluginClassNames fully-qualified class names that are * instances of {@link RpcPlugin}s * @param rpcs a list of loaded and initialized plugins */ private void initializeRpcPlugins(final String[] pluginClassNames, final ImmutableList.Builder<RpcPlugin> rpcs) { for (final String plugin : pluginClassNames) { final RpcPlugin rpc = createAndInitialize(plugin, RpcPlugin.class); rpcs.add(rpc); } } /** * Helper method to load and initialize a given plugin class. This uses reflection * because plugins share no common interfaces. (They could though!) * @param pluginClassName the class name of the plugin to load * @param pluginClass class of the plugin * @return loaded an initialized instance of {@code pluginClass} */ @VisibleForTesting protected <T> T createAndInitialize(final String pluginClassName, final Class<T> pluginClass) { final T instance = PluginLoader.loadSpecificPlugin(pluginClassName, pluginClass); Preconditions.checkState(instance != null, "Unable to locate %s using name '%s", pluginClass, pluginClassName); try { final Method initMeth = instance.getClass().getMethod("initialize", TSDB.class); initMeth.invoke(instance, tsdb); final Method versionMeth = instance.getClass().getMethod("version"); String version = (String) versionMeth.invoke(instance); LOG.info("Successfully initialized plugin [{}] version: {}", instance.getClass().getCanonicalName(), version); return instance; } catch (Exception e) { throw new RuntimeException("Failed to initialize " + instance.getClass(), e); } } /** * Called to gracefully shutdown the plugin. Implementations should close * any IO they have open * @return A deferred object that indicates the completion of the request. * The {@link Object} has not special meaning and can be {@code null} * (think of it as {@code Deferred<Void>}). */ public Deferred<ArrayList<Object>> shutdown() { // Clear shared instance. INSTANCE.set(null); final Collection<Deferred<Object>> deferreds = Lists.newArrayList(); if (http_plugin_commands != null) { for (final Map.Entry<String, HttpRpcPlugin> entry : http_plugin_commands.entrySet()) { deferreds.add(entry.getValue().shutdown()); } } if (rpc_plugins != null) { for (final RpcPlugin rpc : rpc_plugins) { deferreds.add(rpc.shutdown()); } } return Deferred.groupInOrder(deferreds); } /** * Collect stats on the shared instance of {@link RpcManager}. */ static void collectStats(final StatsCollector collector) { final RpcManager manager = INSTANCE.get(); if (manager != null) { if (manager.rpc_plugins != null) { try { collector.addExtraTag("plugin", "rpc"); for (final RpcPlugin rpc : manager.rpc_plugins) { rpc.collectStats(collector); } } finally { collector.clearExtraTag("plugin"); } } if (manager.http_plugin_commands != null) { try { collector.addExtraTag("plugin", "httprpc"); for (final Map.Entry<String, HttpRpcPlugin> entry : manager.http_plugin_commands.entrySet()) { entry.getValue().collectStats(collector); } } finally { collector.clearExtraTag("plugin"); } } } } // ---------------------------- // // Individual command handlers. // // ---------------------------- // /** The "diediedie" command and "/diediedie" endpoint. */ private final class DieDieDie implements TelnetRpc, HttpRpc { public Deferred<Object> execute(final TSDB tsdb, final Channel chan, final String[] cmd) { LOG.warn("{} {}", chan, "shutdown requested"); chan.write("Cleaning up and exiting now.\n"); return doShutdown(tsdb, chan); } public void execute(final TSDB tsdb, final HttpQuery query) { LOG.warn("{} {}", query, "shutdown requested"); query.sendReply(HttpQuery.makePage("TSD Exiting", "You killed me", "Cleaning up and exiting now.")); doShutdown(tsdb, query.channel()); } private Deferred<Object> doShutdown(final TSDB tsdb, final Channel chan) { ((GraphHandler) http_commands.get("q")).shutdown(); ConnectionManager.closeAllConnections(); // Netty gets stuck in an infinite loop if we shut it down from within a // NIO thread. So do this from a newly created thread. final class ShutdownNetty extends Thread { ShutdownNetty() { super("ShutdownNetty"); } public void run() { chan.getFactory().releaseExternalResources(); } } new ShutdownNetty().start(); // Stop accepting new connections. // Log any error that might occur during shutdown. final class ShutdownTSDB implements Callback<Exception, Exception> { public Exception call(final Exception arg) { LOG.error("Unexpected exception while shutting down", arg); return arg; } public String toString() { return "shutdown callback"; } } return tsdb.shutdown().addErrback(new ShutdownTSDB()); } } /** The "exit" command. */ private static final class Exit implements TelnetRpc { public Deferred<Object> execute(final TSDB tsdb, final Channel chan, final String[] cmd) { chan.disconnect(); return Deferred.fromResult(null); } } /** The "help" command. */ private final class Help implements TelnetRpc { public Deferred<Object> execute(final TSDB tsdb, final Channel chan, final String[] cmd) { final StringBuilder buf = new StringBuilder(); buf.append("available commands: "); // TODO(tsuna): Maybe sort them? for (final String command : telnet_commands.keySet()) { buf.append(command).append(' '); } buf.append('\n'); chan.write(buf.toString()); return Deferred.fromResult(null); } } /** The home page ("GET /"). */ private static final class HomePage implements HttpRpc { public void execute(final TSDB tsdb, final HttpQuery query) throws IOException { final StringBuilder buf = new StringBuilder(2048); buf.append("<div id=queryuimain></div>" + "<noscript>You must have JavaScript enabled.</noscript>" + "<iframe src=javascript:'' id=__gwt_historyFrame tabIndex=-1" + " style=position:absolute;width:0;height:0;border:0>" + "</iframe>"); query.sendReply(HttpQuery.makePage( "<script type=text/javascript language=javascript" + " src=s/queryui.nocache.js></script>", "OpenTSDB", "", buf.toString())); } } /** The "/aggregators" endpoint. */ private static final class ListAggregators implements HttpRpc { public void execute(final TSDB tsdb, final HttpQuery query) throws IOException { // only accept GET / POST RpcUtil.allowedMethods(query.method(), HttpMethod.GET.getName(), HttpMethod.POST.getName()); if (query.apiVersion() > 0) { query.sendReply( query.serializer().formatAggregatorsV1(Aggregators.set())); } else { query.sendReply(JSON.serializeToBytes(Aggregators.set())); } } } /** The "version" command. */ private static final class Version implements TelnetRpc, HttpRpc { public Deferred<Object> execute(final TSDB tsdb, final Channel chan, final String[] cmd) { if (chan.isConnected()) { chan.write(BuildData.revisionString() + '\n' + BuildData.buildString() + '\n'); } return Deferred.fromResult(null); } public void execute(final TSDB tsdb, final HttpQuery query) throws IOException { // only accept GET / POST RpcUtil.allowedMethods(query.method(), HttpMethod.GET.getName(), HttpMethod.POST.getName()); final HashMap<String, String> version = new HashMap<String, String>(); version.put("version", BuildData.version); version.put("short_revision", BuildData.short_revision); version.put("full_revision", BuildData.full_revision); version.put("timestamp", Long.toString(BuildData.timestamp)); version.put("repo_status", BuildData.repo_status.toString()); version.put("user", BuildData.user); version.put("host", BuildData.host); version.put("repo", BuildData.repo); version.put("branch", BuildData.branch); if (query.apiVersion() > 0) { query.sendReply(query.serializer().formatVersionV1(version)); } else { final boolean json = query.request().getUri().endsWith("json"); if (json) { query.sendReply(JSON.serializeToBytes(version)); } else { final String revision = BuildData.revisionString(); final String build = BuildData.buildString(); StringBuilder buf; buf = new StringBuilder(2 // For the \n's + revision.length() + build.length()); buf.append(revision).append('\n').append(build).append('\n'); query.sendReply(buf); } } } } /** The /api/formatters endpoint * @since 2.0 */ private static final class Serializers implements HttpRpc { public void execute(final TSDB tsdb, final HttpQuery query) throws IOException { // only accept GET / POST RpcUtil.allowedMethods(query.method(), HttpMethod.GET.getName(), HttpMethod.POST.getName()); switch (query.apiVersion()) { case 0: case 1: query.sendReply(query.serializer().formatSerializersV1()); break; default: throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, "Requested API version not implemented", "Version " + query.apiVersion() + " is not implemented"); } } } private static final class ShowConfig implements HttpRpc { @Override public void execute(TSDB tsdb, HttpQuery query) throws IOException { // only accept GET/POST RpcUtil.allowedMethods(query.method(), HttpMethod.GET.getName(), HttpMethod.POST.getName()); final String[] uri = query.explodeAPIPath(); final String endpoint = uri.length > 1 ? uri[1].toLowerCase() : ""; if (endpoint.equals("filters")) { switch (query.apiVersion()) { case 0: case 1: query.sendReply(query.serializer().formatFilterConfigV1( TagVFilter.loadedFilters())); break; default: throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, "Requested API version not implemented", "Version " + query.apiVersion() + " is not implemented"); } } else { switch (query.apiVersion()) { case 0: case 1: query.sendReply(query.serializer().formatConfigV1(tsdb.getConfig())); break; default: throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, "Requested API version not implemented", "Version " + query.apiVersion() + " is not implemented"); } } } } }
OpenTSDB/opentsdb
src/tsd/RpcManager.java
2,111
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import static com.google.protobuf.Internal.checkNotNull; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.OneofDescriptor; import com.google.protobuf.Internal.BooleanList; import com.google.protobuf.Internal.DoubleList; import com.google.protobuf.Internal.FloatList; import com.google.protobuf.Internal.IntList; import com.google.protobuf.Internal.LongList; import com.google.protobuf.Internal.ProtobufList; import java.io.IOException; import java.io.InputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; /** * All generated protocol message classes extend this class. This class implements most of the * Message and Builder interfaces using Java reflection. Users can ignore this class and pretend * that generated messages implement the Message interface directly. * * @author [email protected] Kenton Varda */ public abstract class GeneratedMessage extends AbstractMessage implements Serializable { private static final long serialVersionUID = 1L; /** * For testing. Allows a test to disable the optimization that avoids using field builders for * nested messages until they are requested. By disabling this optimization, existing tests can be * reused to test the field builders. */ protected static boolean alwaysUseFieldBuilders = false; /** * For use by generated code only. * * <p>TODO: mark this private and final (breaking change) */ protected UnknownFieldSet unknownFields; protected GeneratedMessage() { unknownFields = UnknownFieldSet.getDefaultInstance(); } protected GeneratedMessage(Builder<?> builder) { unknownFields = builder.getUnknownFields(); } /** TODO: Remove this unnecessary intermediate implementation of this method. */ @Override public Parser<? extends GeneratedMessage> getParserForType() { throw new UnsupportedOperationException("This is supposed to be overridden by subclasses."); } /** * TODO: Stop using SingleFieldBuilder and remove this setting * * @see #setAlwaysUseFieldBuildersForTesting(boolean) */ static void enableAlwaysUseFieldBuildersForTesting() { setAlwaysUseFieldBuildersForTesting(true); } /** * For testing. Allows a test to disable/re-enable the optimization that avoids using field * builders for nested messages until they are requested. By disabling this optimization, existing * tests can be reused to test the field builders. See {@link RepeatedFieldBuilder} and {@link * SingleFieldBuilder}. * * <p>TODO: Stop using SingleFieldBuilder and remove this setting */ static void setAlwaysUseFieldBuildersForTesting(boolean useBuilders) { alwaysUseFieldBuilders = useBuilders; } /** * Get the FieldAccessorTable for this type. We can't have the message class pass this in to the * constructor because of bootstrapping trouble with DescriptorProtos. */ protected abstract FieldAccessorTable internalGetFieldAccessorTable(); @Override public Descriptor getDescriptorForType() { return internalGetFieldAccessorTable().descriptor; } /** * TODO: This method should be removed. It enables parsing directly into an * "immutable" message. Have to leave it for now to support old gencode. * * @deprecated use newBuilder().mergeFrom() instead */ @Deprecated protected void mergeFromAndMakeImmutableInternal( CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { Schema<GeneratedMessage> schema = Protobuf.getInstance().schemaFor(this); try { schema.mergeFrom(this, CodedInputStreamReader.forCodedInput(input), extensionRegistry); } catch (InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (IOException e) { throw new InvalidProtocolBufferException(e).setUnfinishedMessage(this); } schema.makeImmutable(this); } /** * Internal helper to return a modifiable map containing all the fields. The returned Map is * modifiable so that the caller can add additional extension fields to implement {@link * #getAllFields()}. * * @param getBytesForString whether to generate ByteString for string fields */ private Map<FieldDescriptor, Object> getAllFieldsMutable(boolean getBytesForString) { final TreeMap<FieldDescriptor, Object> result = new TreeMap<>(); final FieldAccessorTable fieldAccessorTable = internalGetFieldAccessorTable(); final Descriptor descriptor = fieldAccessorTable.descriptor; final List<FieldDescriptor> fields = descriptor.getFields(); for (int i = 0; i < fields.size(); i++) { FieldDescriptor field = fields.get(i); final OneofDescriptor oneofDescriptor = field.getContainingOneof(); /* * If the field is part of a Oneof, then at maximum one field in the Oneof is set * and it is not repeated. There is no need to iterate through the others. */ if (oneofDescriptor != null) { // Skip other fields in the Oneof we know are not set i += oneofDescriptor.getFieldCount() - 1; if (!hasOneof(oneofDescriptor)) { // If no field is set in the Oneof, skip all the fields in the Oneof continue; } // Get the pointer to the only field which is set in the Oneof field = getOneofFieldDescriptor(oneofDescriptor); } else { // If we are not in a Oneof, we need to check if the field is set and if it is repeated if (field.isRepeated()) { final List<?> value = (List<?>) getField(field); if (!value.isEmpty()) { result.put(field, value); } continue; } if (!hasField(field)) { continue; } } // Add the field to the map if (getBytesForString && field.getJavaType() == FieldDescriptor.JavaType.STRING) { result.put(field, getFieldRaw(field)); } else { result.put(field, getField(field)); } } return result; } // TODO: compute this at {@code build()} time in the Builder class. @Override public boolean isInitialized() { for (final FieldDescriptor field : getDescriptorForType().getFields()) { // Check that all required fields are present. if (field.isRequired()) { if (!hasField(field)) { return false; } } // Check that embedded messages are initialized. if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { if (field.isRepeated()) { @SuppressWarnings("unchecked") final List<Message> messageList = (List<Message>) getField(field); for (final Message element : messageList) { if (!element.isInitialized()) { return false; } } } else { if (hasField(field) && !((Message) getField(field)).isInitialized()) { return false; } } } } return true; } @Override public Map<FieldDescriptor, Object> getAllFields() { return Collections.unmodifiableMap(getAllFieldsMutable(/* getBytesForString= */ false)); } /** * Returns a collection of all the fields in this message which are set and their corresponding * values. A singular ("required" or "optional") field is set iff hasField() returns true for that * field. A "repeated" field is set iff getRepeatedFieldCount() is greater than zero. The values * are exactly what would be returned by calling {@link #getFieldRaw(Descriptors.FieldDescriptor)} * for each field. The map is guaranteed to be a sorted map, so iterating over it will return * fields in order by field number. */ Map<FieldDescriptor, Object> getAllFieldsRaw() { return Collections.unmodifiableMap(getAllFieldsMutable(/* getBytesForString= */ true)); } @Override public boolean hasOneof(final OneofDescriptor oneof) { return internalGetFieldAccessorTable().getOneof(oneof).has(this); } @Override public FieldDescriptor getOneofFieldDescriptor(final OneofDescriptor oneof) { return internalGetFieldAccessorTable().getOneof(oneof).get(this); } @Override public boolean hasField(final FieldDescriptor field) { return internalGetFieldAccessorTable().getField(field).has(this); } @Override public Object getField(final FieldDescriptor field) { return internalGetFieldAccessorTable().getField(field).get(this); } /** * Obtains the value of the given field, or the default value if it is not set. For primitive * fields, the boxed primitive value is returned. For enum fields, the EnumValueDescriptor for the * value is returned. For embedded message fields, the sub-message is returned. For repeated * fields, a java.util.List is returned. For present string fields, a ByteString is returned * representing the bytes that the field contains. */ Object getFieldRaw(final FieldDescriptor field) { return internalGetFieldAccessorTable().getField(field).getRaw(this); } @Override public int getRepeatedFieldCount(final FieldDescriptor field) { return internalGetFieldAccessorTable().getField(field).getRepeatedCount(this); } @Override public Object getRepeatedField(final FieldDescriptor field, final int index) { return internalGetFieldAccessorTable().getField(field).getRepeated(this, index); } // TODO: This method should be final. @Override public UnknownFieldSet getUnknownFields() { return unknownFields; } // TODO: This should go away when Schema classes cannot modify immutable // GeneratedMessage objects anymore. void setUnknownFields(UnknownFieldSet unknownFields) { this.unknownFields = unknownFields; } /** * Called by subclasses to parse an unknown field. * * <p>TODO remove this method * * @return {@code true} unless the tag is an end-group tag. */ protected boolean parseUnknownField( CodedInputStream input, UnknownFieldSet.Builder unknownFields, ExtensionRegistryLite extensionRegistry, int tag) throws IOException { if (input.shouldDiscardUnknownFields()) { return input.skipField(tag); } return unknownFields.mergeFieldFrom(tag, input); } /** * Delegates to parseUnknownField. This method is obsolete, but we must retain it for * compatibility with older generated code. * * <p>TODO remove this method */ protected boolean parseUnknownFieldProto3( CodedInputStream input, UnknownFieldSet.Builder unknownFields, ExtensionRegistryLite extensionRegistry, int tag) throws IOException { return parseUnknownField(input, unknownFields, extensionRegistry, tag); } /** Used by generated code. */ @SuppressWarnings("ProtoParseWithRegistry") protected static <M extends Message> M parseWithIOException(Parser<M> parser, InputStream input) throws IOException { try { return parser.parseFrom(input); } catch (InvalidProtocolBufferException e) { throw e.unwrapIOException(); } } /** Used by generated code. */ protected static <M extends Message> M parseWithIOException( Parser<M> parser, InputStream input, ExtensionRegistryLite extensions) throws IOException { try { return parser.parseFrom(input, extensions); } catch (InvalidProtocolBufferException e) { throw e.unwrapIOException(); } } /** Used by generated code. */ @SuppressWarnings("ProtoParseWithRegistry") protected static <M extends Message> M parseWithIOException( Parser<M> parser, CodedInputStream input) throws IOException { try { return parser.parseFrom(input); } catch (InvalidProtocolBufferException e) { throw e.unwrapIOException(); } } /** Used by generated code. */ protected static <M extends Message> M parseWithIOException( Parser<M> parser, CodedInputStream input, ExtensionRegistryLite extensions) throws IOException { try { return parser.parseFrom(input, extensions); } catch (InvalidProtocolBufferException e) { throw e.unwrapIOException(); } } /** Used by generated code. */ @SuppressWarnings("ProtoParseWithRegistry") protected static <M extends Message> M parseDelimitedWithIOException( Parser<M> parser, InputStream input) throws IOException { try { return parser.parseDelimitedFrom(input); } catch (InvalidProtocolBufferException e) { throw e.unwrapIOException(); } } /** Used by generated code. */ protected static <M extends Message> M parseDelimitedWithIOException( Parser<M> parser, InputStream input, ExtensionRegistryLite extensions) throws IOException { try { return parser.parseDelimitedFrom(input, extensions); } catch (InvalidProtocolBufferException e) { throw e.unwrapIOException(); } } protected static boolean canUseUnsafe() { return UnsafeUtil.hasUnsafeArrayOperations() && UnsafeUtil.hasUnsafeByteBufferOperations(); } protected static IntList emptyIntList() { return IntArrayList.emptyList(); } protected static LongList emptyLongList() { return LongArrayList.emptyList(); } protected static FloatList emptyFloatList() { return FloatArrayList.emptyList(); } protected static DoubleList emptyDoubleList() { return DoubleArrayList.emptyList(); } protected static BooleanList emptyBooleanList() { return BooleanArrayList.emptyList(); } protected static <ListT extends ProtobufList<?>> ListT makeMutableCopy(ListT list) { return makeMutableCopy(list, 0); } @SuppressWarnings("unchecked") // Guaranteed by proto runtime. protected static <ListT extends ProtobufList<?>> ListT makeMutableCopy( ListT list, int minCapacity) { int size = list.size(); if (minCapacity <= size) { minCapacity = size * 2; } if (minCapacity <= 0) { minCapacity = AbstractProtobufList.DEFAULT_CAPACITY; } return (ListT) list.mutableCopyWithCapacity(minCapacity); } @SuppressWarnings("unchecked") // The empty list can be safely cast protected static <T> ProtobufList<T> emptyList(Class<T> elementType) { return (ProtobufList<T>) ProtobufArrayList.emptyList(); } @Override public void writeTo(final CodedOutputStream output) throws IOException { MessageReflection.writeMessageTo(this, getAllFieldsRaw(), output, false); } @Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) { return size; } memoizedSize = MessageReflection.getSerializedSize( this, getAllFieldsRaw()); return memoizedSize; } /** * This class is used to make a generated protected method inaccessible from user's code (e.g., * the {@link #newInstance} method below). When this class is used as a parameter's type in a * generated protected method, the method is visible to user's code in the same package, but since * the constructor of this class is private to protobuf runtime, user's code can't obtain an * instance of this class and as such can't actually make a method call on the protected method. */ protected static final class UnusedPrivateParameter { static final UnusedPrivateParameter INSTANCE = new UnusedPrivateParameter(); private UnusedPrivateParameter() {} } /** Creates a new instance of this message type. Overridden in the generated code. */ @SuppressWarnings({"unused"}) protected Object newInstance(UnusedPrivateParameter unused) { throw new UnsupportedOperationException("This method must be overridden by the subclass."); } /** Builder class for {@link GeneratedMessage}. */ @SuppressWarnings("unchecked") public abstract static class Builder<BuilderT extends Builder<BuilderT>> extends AbstractMessage.Builder<BuilderT> { private BuilderParent builderParent; private BuilderParentImpl meAsParent; // Indicates that we've built a message and so we are now obligated // to dispatch dirty invalidations. See GeneratedMessage.BuilderListener. private boolean isClean; /** * This field holds either an {@link UnknownFieldSet} or {@link UnknownFieldSet.Builder}. * * <p>We use an object because it should only be one or the other of those things at a time and * Object is the only common base. This also saves space. * * <p>Conversions are lazy: if {@link #setUnknownFields} is called, this will contain {@link * UnknownFieldSet}. If unknown fields are merged into this builder, the current {@link * UnknownFieldSet} will be converted to a {@link UnknownFieldSet.Builder} and left that way * until either {@link #setUnknownFields} or {@link #buildPartial} or {@link #build} is called. */ private Object unknownFieldsOrBuilder = UnknownFieldSet.getDefaultInstance(); protected Builder() { this(null); } protected Builder(BuilderParent builderParent) { this.builderParent = builderParent; } @Override void dispose() { builderParent = null; } /** Called by the subclass when a message is built. */ protected void onBuilt() { if (builderParent != null) { markClean(); } } /** * Called by the subclass or a builder to notify us that a message was built and may be cached * and therefore invalidations are needed. */ @Override protected void markClean() { this.isClean = true; } /** * Gets whether invalidations are needed * * @return whether invalidations are needed */ protected boolean isClean() { return isClean; } @Override public BuilderT clone() { BuilderT builder = (BuilderT) getDefaultInstanceForType().newBuilderForType(); builder.mergeFrom(buildPartial()); return builder; } /** * Called by the initialization and clear code paths to allow subclasses to reset any of their * builtin fields back to the initial values. */ @Override public BuilderT clear() { unknownFieldsOrBuilder = UnknownFieldSet.getDefaultInstance(); onChanged(); return (BuilderT) this; } /** * Get the FieldAccessorTable for this type. We can't have the message class pass this in to the * constructor because of bootstrapping trouble with DescriptorProtos. */ protected abstract FieldAccessorTable internalGetFieldAccessorTable(); @Override public Descriptor getDescriptorForType() { return internalGetFieldAccessorTable().descriptor; } @Override public Map<FieldDescriptor, Object> getAllFields() { return Collections.unmodifiableMap(getAllFieldsMutable()); } /** Internal helper which returns a mutable map. */ private Map<FieldDescriptor, Object> getAllFieldsMutable() { final TreeMap<FieldDescriptor, Object> result = new TreeMap<>(); final FieldAccessorTable fieldAccessorTable = internalGetFieldAccessorTable(); final Descriptor descriptor = fieldAccessorTable.descriptor; final List<FieldDescriptor> fields = descriptor.getFields(); for (int i = 0; i < fields.size(); i++) { FieldDescriptor field = fields.get(i); final OneofDescriptor oneofDescriptor = field.getContainingOneof(); /* * If the field is part of a Oneof, then at maximum one field in the Oneof is set * and it is not repeated. There is no need to iterate through the others. */ if (oneofDescriptor != null) { // Skip other fields in the Oneof we know are not set i += oneofDescriptor.getFieldCount() - 1; if (!hasOneof(oneofDescriptor)) { // If no field is set in the Oneof, skip all the fields in the Oneof continue; } // Get the pointer to the only field which is set in the Oneof field = getOneofFieldDescriptor(oneofDescriptor); } else { // If we are not in a Oneof, we need to check if the field is set and if it is repeated if (field.isRepeated()) { final List<?> value = (List<?>) getField(field); if (!value.isEmpty()) { result.put(field, value); } continue; } if (!hasField(field)) { continue; } } // Add the field to the map result.put(field, getField(field)); } return result; } @Override public Message.Builder newBuilderForField(final FieldDescriptor field) { return internalGetFieldAccessorTable().getField(field).newBuilder(); } @Override public Message.Builder getFieldBuilder(final FieldDescriptor field) { return internalGetFieldAccessorTable().getField(field).getBuilder(this); } @Override public Message.Builder getRepeatedFieldBuilder(final FieldDescriptor field, int index) { return internalGetFieldAccessorTable().getField(field).getRepeatedBuilder(this, index); } @Override public boolean hasOneof(final OneofDescriptor oneof) { return internalGetFieldAccessorTable().getOneof(oneof).has(this); } @Override public FieldDescriptor getOneofFieldDescriptor(final OneofDescriptor oneof) { return internalGetFieldAccessorTable().getOneof(oneof).get(this); } @Override public boolean hasField(final FieldDescriptor field) { return internalGetFieldAccessorTable().getField(field).has(this); } @Override public Object getField(final FieldDescriptor field) { Object object = internalGetFieldAccessorTable().getField(field).get(this); if (field.isRepeated()) { // The underlying list object is still modifiable at this point. // Make sure not to expose the modifiable list to the caller. return Collections.unmodifiableList((List<?>) object); } else { return object; } } @Override public BuilderT setField(final FieldDescriptor field, final Object value) { internalGetFieldAccessorTable().getField(field).set(this, value); return (BuilderT) this; } @Override public BuilderT clearField(final FieldDescriptor field) { internalGetFieldAccessorTable().getField(field).clear(this); return (BuilderT) this; } @Override public BuilderT clearOneof(final OneofDescriptor oneof) { internalGetFieldAccessorTable().getOneof(oneof).clear(this); return (BuilderT) this; } @Override public int getRepeatedFieldCount(final FieldDescriptor field) { return internalGetFieldAccessorTable().getField(field).getRepeatedCount(this); } @Override public Object getRepeatedField(final FieldDescriptor field, final int index) { return internalGetFieldAccessorTable().getField(field).getRepeated(this, index); } @Override public BuilderT setRepeatedField( final FieldDescriptor field, final int index, final Object value) { internalGetFieldAccessorTable().getField(field).setRepeated(this, index, value); return (BuilderT) this; } @Override public BuilderT addRepeatedField(final FieldDescriptor field, final Object value) { internalGetFieldAccessorTable().getField(field).addRepeated(this, value); return (BuilderT) this; } private BuilderT setUnknownFieldsInternal(final UnknownFieldSet unknownFields) { unknownFieldsOrBuilder = unknownFields; onChanged(); return (BuilderT) this; } @Override public BuilderT setUnknownFields(final UnknownFieldSet unknownFields) { return setUnknownFieldsInternal(unknownFields); } /** * This method is obsolete, but we must retain it for compatibility with older generated code. */ protected BuilderT setUnknownFieldsProto3(final UnknownFieldSet unknownFields) { return setUnknownFieldsInternal(unknownFields); } @Override public BuilderT mergeUnknownFields(final UnknownFieldSet unknownFields) { if (UnknownFieldSet.getDefaultInstance().equals(unknownFields)) { return (BuilderT) this; } if (UnknownFieldSet.getDefaultInstance().equals(unknownFieldsOrBuilder)) { unknownFieldsOrBuilder = unknownFields; onChanged(); return (BuilderT) this; } getUnknownFieldSetBuilder().mergeFrom(unknownFields); onChanged(); return (BuilderT) this; } @Override public boolean isInitialized() { for (final FieldDescriptor field : getDescriptorForType().getFields()) { // Check that all required fields are present. if (field.isRequired()) { if (!hasField(field)) { return false; } } // Check that embedded messages are initialized. if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { if (field.isRepeated()) { @SuppressWarnings("unchecked") final List<Message> messageList = (List<Message>) getField(field); for (final Message element : messageList) { if (!element.isInitialized()) { return false; } } } else { if (hasField(field) && !((Message) getField(field)).isInitialized()) { return false; } } } } return true; } @Override public final UnknownFieldSet getUnknownFields() { if (unknownFieldsOrBuilder instanceof UnknownFieldSet) { return (UnknownFieldSet) unknownFieldsOrBuilder; } else { return ((UnknownFieldSet.Builder) unknownFieldsOrBuilder).buildPartial(); } } /** * Called by generated subclasses to parse an unknown field. * * @return {@code true} unless the tag is an end-group tag. */ protected boolean parseUnknownField( CodedInputStream input, ExtensionRegistryLite extensionRegistry, int tag) throws IOException { if (input.shouldDiscardUnknownFields()) { return input.skipField(tag); } return getUnknownFieldSetBuilder().mergeFieldFrom(tag, input); } /** Called by generated subclasses to add to the unknown field set. */ protected final void mergeUnknownLengthDelimitedField(int number, ByteString bytes) { getUnknownFieldSetBuilder().mergeLengthDelimitedField(number, bytes); } /** Called by generated subclasses to add to the unknown field set. */ protected final void mergeUnknownVarintField(int number, int value) { getUnknownFieldSetBuilder().mergeVarintField(number, value); } @Override protected UnknownFieldSet.Builder getUnknownFieldSetBuilder() { if (unknownFieldsOrBuilder instanceof UnknownFieldSet) { unknownFieldsOrBuilder = ((UnknownFieldSet) unknownFieldsOrBuilder).toBuilder(); } onChanged(); return (UnknownFieldSet.Builder) unknownFieldsOrBuilder; } @Override protected void setUnknownFieldSetBuilder(UnknownFieldSet.Builder builder) { unknownFieldsOrBuilder = builder; onChanged(); } /** * Implementation of {@link BuilderParent} for giving to our children. This small inner class * makes it so we don't publicly expose the BuilderParent methods. */ private class BuilderParentImpl implements BuilderParent { @Override public void markDirty() { onChanged(); } } /** * Gets the {@link BuilderParent} for giving to our children. * * @return The builder parent for our children. */ protected BuilderParent getParentForChildren() { if (meAsParent == null) { meAsParent = new BuilderParentImpl(); } return meAsParent; } /** * Called when a builder or one of its nested children has changed and any parent should be * notified of its invalidation. */ protected final void onChanged() { if (isClean && builderParent != null) { builderParent.markDirty(); // Don't keep dispatching invalidations until build is called again. isClean = false; } } /** * Gets the map field with the given field number. This method should be overridden in the * generated message class if the message contains map fields. * * <p>Unlike other field types, reflection support for map fields can't be implemented based on * generated public API because we need to access a map field as a list in reflection API but * the generated API only allows us to access it as a map. This method returns the underlying * map field directly and thus enables us to access the map field as a list. */ @SuppressWarnings({"unused", "rawtypes"}) protected MapFieldReflectionAccessor internalGetMapFieldReflection(int fieldNumber) { return internalGetMapField(fieldNumber); } /** TODO: Remove, exists for compatibility with generated code. */ @Deprecated @SuppressWarnings({"unused", "rawtypes"}) protected MapField internalGetMapField(int fieldNumber) { // Note that we can't use descriptor names here because this method will // be called when descriptor is being initialized. throw new IllegalArgumentException("No map fields found in " + getClass().getName()); } /** Like {@link #internalGetMapFieldReflection} but return a mutable version. */ @SuppressWarnings({"unused", "rawtypes"}) protected MapFieldReflectionAccessor internalGetMutableMapFieldReflection(int fieldNumber) { return internalGetMutableMapField(fieldNumber); } /** TODO: Remove, exists for compatibility with generated code. */ @Deprecated @SuppressWarnings({"unused", "rawtypes"}) protected MapField internalGetMutableMapField(int fieldNumber) { // Note that we can't use descriptor names here because this method will // be called when descriptor is being initialized. throw new IllegalArgumentException("No map fields found in " + getClass().getName()); } } // ================================================================= // Extensions-related stuff /** Extends {@link MessageOrBuilder} with extension-related functions. */ public interface ExtendableMessageOrBuilder<MessageT extends ExtendableMessage<MessageT>> extends MessageOrBuilder { // Re-define for return type covariance. @Override Message getDefaultInstanceForType(); /** Check if a singular extension is present. */ <T> boolean hasExtension(ExtensionLite<MessageT, T> extension); /** Get the number of elements in a repeated extension. */ <T> int getExtensionCount(ExtensionLite<MessageT, List<T>> extension); /** Get the value of an extension. */ <T> T getExtension(ExtensionLite<MessageT, T> extension); /** Get one element of a repeated extension. */ <T> T getExtension(ExtensionLite<MessageT, List<T>> extension, int index); } /** * Generated message classes for message types that contain extension ranges subclass this. * * <p>This class implements type-safe accessors for extensions. They implement all the same * operations that you can do with normal fields -- e.g. "has", "get", and "getCount" -- but for * extensions. The extensions are identified using instances of the class {@link * GeneratedExtension}; the protocol compiler generates a static instance of this class for every * extension in its input. Through the magic of generics, all is made type-safe. * * <p>For example, imagine you have the {@code .proto} file: * * <pre> * option java_class = "MyProto"; * * message Foo { * extensions 1000 to max; * } * * extend Foo { * optional int32 bar; * } * </pre> * * <p>Then you might write code like: * * <pre> * MyProto.Foo foo = getFoo(); * int i = foo.getExtension(MyProto.bar); * </pre> * * <p>See also {@link ExtendableBuilder}. */ public abstract static class ExtendableMessage<MessageT extends ExtendableMessage<MessageT>> extends GeneratedMessage implements ExtendableMessageOrBuilder<MessageT> { private static final long serialVersionUID = 1L; private final FieldSet<FieldDescriptor> extensions; protected ExtendableMessage() { this.extensions = FieldSet.newFieldSet(); } protected ExtendableMessage(ExtendableBuilder<MessageT, ?> builder) { super(builder); this.extensions = builder.buildExtensions(); } private void verifyExtensionContainingType(final Extension<MessageT, ?> extension) { if (extension.getDescriptor().getContainingType() != getDescriptorForType()) { // This can only happen if someone uses unchecked operations. throw new IllegalArgumentException( "Extension is for type \"" + extension.getDescriptor().getContainingType().getFullName() + "\" which does not match message type \"" + getDescriptorForType().getFullName() + "\"."); } } /** Check if a singular extension is present. */ @Override public final <T> boolean hasExtension(final ExtensionLite<MessageT, T> extensionLite) { Extension<MessageT, T> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); return extensions.hasField(extension.getDescriptor()); } /** Get the number of elements in a repeated extension. */ @Override public final <T> int getExtensionCount(final ExtensionLite<MessageT, List<T>> extensionLite) { Extension<MessageT, List<T>> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); final FieldDescriptor descriptor = extension.getDescriptor(); return extensions.getRepeatedFieldCount(descriptor); } /** Get the value of an extension. */ @Override @SuppressWarnings("unchecked") public final <T> T getExtension(final ExtensionLite<MessageT, T> extensionLite) { Extension<MessageT, T> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); FieldDescriptor descriptor = extension.getDescriptor(); final Object value = extensions.getField(descriptor); if (value == null) { if (descriptor.isRepeated()) { return (T) Collections.emptyList(); } else if (descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { return (T) extension.getMessageDefaultInstance(); } else { return (T) extension.fromReflectionType(descriptor.getDefaultValue()); } } else { return (T) extension.fromReflectionType(value); } } /** Get one element of a repeated extension. */ @Override @SuppressWarnings("unchecked") public final <T> T getExtension( final ExtensionLite<MessageT, List<T>> extensionLite, final int index) { Extension<MessageT, List<T>> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); FieldDescriptor descriptor = extension.getDescriptor(); return (T) extension.singularFromReflectionType(extensions.getRepeatedField(descriptor, index)); } /** Called by subclasses to check if all extensions are initialized. */ protected boolean extensionsAreInitialized() { return extensions.isInitialized(); } // TODO: compute this in the builder at {@code build()} time. @Override public boolean isInitialized() { return super.isInitialized() && extensionsAreInitialized(); } /** * Used by subclasses to serialize extensions. Extension ranges may be interleaved with field * numbers, but we must write them in canonical (sorted by field number) order. ExtensionWriter * helps us write individual ranges of extensions at once. */ protected class ExtensionWriter { // Imagine how much simpler this code would be if Java iterators had // a way to get the next element without advancing the iterator. private final Iterator<Map.Entry<FieldDescriptor, Object>> iter = extensions.iterator(); private Map.Entry<FieldDescriptor, Object> next; private final boolean messageSetWireFormat; private ExtensionWriter(final boolean messageSetWireFormat) { if (iter.hasNext()) { next = iter.next(); } this.messageSetWireFormat = messageSetWireFormat; } public void writeUntil(final int end, final CodedOutputStream output) throws IOException { while (next != null && next.getKey().getNumber() < end) { FieldDescriptor descriptor = next.getKey(); if (messageSetWireFormat && descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE && !descriptor.isRepeated()) { if (next instanceof LazyField.LazyEntry<?>) { output.writeRawMessageSetExtension( descriptor.getNumber(), ((LazyField.LazyEntry<?>) next).getField().toByteString()); } else { output.writeMessageSetExtension(descriptor.getNumber(), (Message) next.getValue()); } } else { // TODO: Taken care of following code, it may cause // problem when we use LazyField for normal fields/extensions. // Due to the optional field can be duplicated at the end of // serialized bytes, which will make the serialized size change // after lazy field parsed. So when we use LazyField globally, // we need to change the following write method to write cached // bytes directly rather than write the parsed message. FieldSet.writeField(descriptor, next.getValue(), output); } if (iter.hasNext()) { next = iter.next(); } else { next = null; } } } } protected ExtensionWriter newExtensionWriter() { return new ExtensionWriter(false); } protected ExtensionWriter newMessageSetExtensionWriter() { return new ExtensionWriter(true); } /** Called by subclasses to compute the size of extensions. */ protected int extensionsSerializedSize() { return extensions.getSerializedSize(); } protected int extensionsSerializedSizeAsMessageSet() { return extensions.getMessageSetSerializedSize(); } // --------------------------------------------------------------- // Reflection protected Map<FieldDescriptor, Object> getExtensionFields() { return extensions.getAllFields(); } @Override public Map<FieldDescriptor, Object> getAllFields() { final Map<FieldDescriptor, Object> result = super.getAllFieldsMutable(/* getBytesForString= */ false); result.putAll(getExtensionFields()); return Collections.unmodifiableMap(result); } @Override public Map<FieldDescriptor, Object> getAllFieldsRaw() { final Map<FieldDescriptor, Object> result = super.getAllFieldsMutable(/* getBytesForString= */ false); result.putAll(getExtensionFields()); return Collections.unmodifiableMap(result); } @Override public boolean hasField(final FieldDescriptor field) { if (field.isExtension()) { verifyContainingType(field); return extensions.hasField(field); } else { return super.hasField(field); } } @Override public Object getField(final FieldDescriptor field) { if (field.isExtension()) { verifyContainingType(field); final Object value = extensions.getField(field); if (value == null) { if (field.isRepeated()) { return Collections.emptyList(); } else if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { // Lacking an ExtensionRegistry, we have no way to determine the // extension's real type, so we return a DynamicMessage. return DynamicMessage.getDefaultInstance(field.getMessageType()); } else { return field.getDefaultValue(); } } else { return value; } } else { return super.getField(field); } } @Override public int getRepeatedFieldCount(final FieldDescriptor field) { if (field.isExtension()) { verifyContainingType(field); return extensions.getRepeatedFieldCount(field); } else { return super.getRepeatedFieldCount(field); } } @Override public Object getRepeatedField(final FieldDescriptor field, final int index) { if (field.isExtension()) { verifyContainingType(field); return extensions.getRepeatedField(field, index); } else { return super.getRepeatedField(field, index); } } private void verifyContainingType(final FieldDescriptor field) { if (field.getContainingType() != getDescriptorForType()) { throw new IllegalArgumentException("FieldDescriptor does not match message type."); } } } /** * Generated message builders for message types that contain extension ranges subclass this. * * <p>This class implements type-safe accessors for extensions. They implement all the same * operations that you can do with normal fields -- e.g. "get", "set", and "add" -- but for * extensions. The extensions are identified using instances of the class {@link * GeneratedExtension}; the protocol compiler generates a static instance of this class for every * extension in its input. Through the magic of generics, all is made type-safe. * * <p>For example, imagine you have the {@code .proto} file: * * <pre> * option java_class = "MyProto"; * * message Foo { * extensions 1000 to max; * } * * extend Foo { * optional int32 bar; * } * </pre> * * <p>Then you might write code like: * * <pre> * MyProto.Foo foo = * MyProto.Foo.newBuilder() * .setExtension(MyProto.bar, 123) * .build(); * </pre> * * <p>See also {@link ExtendableMessage}. */ @SuppressWarnings("unchecked") public abstract static class ExtendableBuilder< MessageT extends ExtendableMessage<MessageT>, BuilderT extends ExtendableBuilder<MessageT, BuilderT>> extends Builder<BuilderT> implements ExtendableMessageOrBuilder<MessageT> { private FieldSet.Builder<FieldDescriptor> extensions; protected ExtendableBuilder() {} protected ExtendableBuilder(BuilderParent parent) { super(parent); } // For immutable message conversion. void internalSetExtensionSet(FieldSet<FieldDescriptor> extensions) { this.extensions = FieldSet.Builder.fromFieldSet(extensions); } @Override public BuilderT clear() { extensions = null; return super.clear(); } private void ensureExtensionsIsMutable() { if (extensions == null) { extensions = FieldSet.newBuilder(); } } private void verifyExtensionContainingType(final Extension<MessageT, ?> extension) { if (extension.getDescriptor().getContainingType() != getDescriptorForType()) { // This can only happen if someone uses unchecked operations. throw new IllegalArgumentException( "Extension is for type \"" + extension.getDescriptor().getContainingType().getFullName() + "\" which does not match message type \"" + getDescriptorForType().getFullName() + "\"."); } } /** Check if a singular extension is present. */ @Override public final <T> boolean hasExtension(final ExtensionLite<MessageT, T> extensionLite) { Extension<MessageT, T> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); return extensions != null && extensions.hasField(extension.getDescriptor()); } /** Get the number of elements in a repeated extension. */ @Override public final <T> int getExtensionCount(final ExtensionLite<MessageT, List<T>> extensionLite) { Extension<MessageT, List<T>> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); final FieldDescriptor descriptor = extension.getDescriptor(); return extensions == null ? 0 : extensions.getRepeatedFieldCount(descriptor); } /** Get the value of an extension. */ @Override public final <T> T getExtension(final ExtensionLite<MessageT, T> extensionLite) { Extension<MessageT, T> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); FieldDescriptor descriptor = extension.getDescriptor(); final Object value = extensions == null ? null : extensions.getField(descriptor); if (value == null) { if (descriptor.isRepeated()) { return (T) Collections.emptyList(); } else if (descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { return (T) extension.getMessageDefaultInstance(); } else { return (T) extension.fromReflectionType(descriptor.getDefaultValue()); } } else { return (T) extension.fromReflectionType(value); } } /** Get one element of a repeated extension. */ @Override public final <T> T getExtension( final ExtensionLite<MessageT, List<T>> extensionLite, final int index) { Extension<MessageT, List<T>> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); FieldDescriptor descriptor = extension.getDescriptor(); if (extensions == null) { throw new IndexOutOfBoundsException(); } return (T) extension.singularFromReflectionType(extensions.getRepeatedField(descriptor, index)); } /** Set the value of an extension. */ public final <T> BuilderT setExtension( final ExtensionLite<MessageT, T> extensionLite, final T value) { Extension<MessageT, T> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); ensureExtensionsIsMutable(); final FieldDescriptor descriptor = extension.getDescriptor(); extensions.setField(descriptor, extension.toReflectionType(value)); onChanged(); return (BuilderT) this; } /** Set the value of one element of a repeated extension. */ public final <T> BuilderT setExtension( final ExtensionLite<MessageT, List<T>> extensionLite, final int index, final T value) { Extension<MessageT, List<T>> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); ensureExtensionsIsMutable(); final FieldDescriptor descriptor = extension.getDescriptor(); extensions.setRepeatedField(descriptor, index, extension.singularToReflectionType(value)); onChanged(); return (BuilderT) this; } /** Append a value to a repeated extension. */ public final <T> BuilderT addExtension( final ExtensionLite<MessageT, List<T>> extensionLite, final T value) { Extension<MessageT, List<T>> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); ensureExtensionsIsMutable(); final FieldDescriptor descriptor = extension.getDescriptor(); extensions.addRepeatedField(descriptor, extension.singularToReflectionType(value)); onChanged(); return (BuilderT) this; } /** Clear an extension. */ public final <T> BuilderT clearExtension(final ExtensionLite<MessageT, T> extensionLite) { Extension<MessageT, T> extension = checkNotLite(extensionLite); verifyExtensionContainingType(extension); ensureExtensionsIsMutable(); extensions.clearField(extension.getDescriptor()); onChanged(); return (BuilderT) this; } /** Called by subclasses to check if all extensions are initialized. */ protected boolean extensionsAreInitialized() { return extensions == null || extensions.isInitialized(); } /** * Called by the build code path to create a copy of the extensions for building the message. */ private FieldSet<FieldDescriptor> buildExtensions() { return extensions == null ? (FieldSet<FieldDescriptor>) FieldSet.emptySet() : extensions.buildPartial(); } @Override public boolean isInitialized() { return super.isInitialized() && extensionsAreInitialized(); } // --------------------------------------------------------------- // Reflection @Override public Map<FieldDescriptor, Object> getAllFields() { final Map<FieldDescriptor, Object> result = super.getAllFieldsMutable(); if (extensions != null) { result.putAll(extensions.getAllFields()); } return Collections.unmodifiableMap(result); } @Override public Object getField(final FieldDescriptor field) { if (field.isExtension()) { verifyContainingType(field); final Object value = extensions == null ? null : extensions.getField(field); if (value == null) { if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { // Lacking an ExtensionRegistry, we have no way to determine the // extension's real type, so we return a DynamicMessage. return DynamicMessage.getDefaultInstance(field.getMessageType()); } else { return field.getDefaultValue(); } } else { return value; } } else { return super.getField(field); } } @Override public Message.Builder getFieldBuilder(final FieldDescriptor field) { if (field.isExtension()) { verifyContainingType(field); if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { throw new UnsupportedOperationException( "getFieldBuilder() called on a non-Message type."); } ensureExtensionsIsMutable(); final Object value = extensions.getFieldAllowBuilders(field); if (value == null) { Message.Builder builder = DynamicMessage.newBuilder(field.getMessageType()); extensions.setField(field, builder); onChanged(); return builder; } else { if (value instanceof Message.Builder) { return (Message.Builder) value; } else if (value instanceof Message) { Message.Builder builder = ((Message) value).toBuilder(); extensions.setField(field, builder); onChanged(); return builder; } else { throw new UnsupportedOperationException( "getRepeatedFieldBuilder() called on a non-Message type."); } } } else { return super.getFieldBuilder(field); } } @Override public int getRepeatedFieldCount(final FieldDescriptor field) { if (field.isExtension()) { verifyContainingType(field); return extensions == null ? 0 : extensions.getRepeatedFieldCount(field); } else { return super.getRepeatedFieldCount(field); } } @Override public Object getRepeatedField(final FieldDescriptor field, final int index) { if (field.isExtension()) { verifyContainingType(field); if (extensions == null) { throw new IndexOutOfBoundsException(); } return extensions.getRepeatedField(field, index); } else { return super.getRepeatedField(field, index); } } @Override public Message.Builder getRepeatedFieldBuilder(final FieldDescriptor field, final int index) { if (field.isExtension()) { verifyContainingType(field); ensureExtensionsIsMutable(); if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { throw new UnsupportedOperationException( "getRepeatedFieldBuilder() called on a non-Message type."); } final Object value = extensions.getRepeatedFieldAllowBuilders(field, index); if (value instanceof Message.Builder) { return (Message.Builder) value; } else if (value instanceof Message) { Message.Builder builder = ((Message) value).toBuilder(); extensions.setRepeatedField(field, index, builder); onChanged(); return builder; } else { throw new UnsupportedOperationException( "getRepeatedFieldBuilder() called on a non-Message type."); } } else { return super.getRepeatedFieldBuilder(field, index); } } @Override public boolean hasField(final FieldDescriptor field) { if (field.isExtension()) { verifyContainingType(field); return extensions != null && extensions.hasField(field); } else { return super.hasField(field); } } @Override public BuilderT setField(final FieldDescriptor field, final Object value) { if (field.isExtension()) { verifyContainingType(field); ensureExtensionsIsMutable(); extensions.setField(field, value); onChanged(); return (BuilderT) this; } else { return super.setField(field, value); } } @Override public BuilderT clearField(final FieldDescriptor field) { if (field.isExtension()) { verifyContainingType(field); ensureExtensionsIsMutable(); extensions.clearField(field); onChanged(); return (BuilderT) this; } else { return super.clearField(field); } } @Override public BuilderT setRepeatedField( final FieldDescriptor field, final int index, final Object value) { if (field.isExtension()) { verifyContainingType(field); ensureExtensionsIsMutable(); extensions.setRepeatedField(field, index, value); onChanged(); return (BuilderT) this; } else { return super.setRepeatedField(field, index, value); } } @Override public BuilderT addRepeatedField(final FieldDescriptor field, final Object value) { if (field.isExtension()) { verifyContainingType(field); ensureExtensionsIsMutable(); extensions.addRepeatedField(field, value); onChanged(); return (BuilderT) this; } else { return super.addRepeatedField(field, value); } } @Override public Message.Builder newBuilderForField(final FieldDescriptor field) { if (field.isExtension()) { return DynamicMessage.newBuilder(field.getMessageType()); } else { return super.newBuilderForField(field); } } protected final void mergeExtensionFields(final ExtendableMessage<?> other) { if (other.extensions != null) { ensureExtensionsIsMutable(); extensions.mergeFrom(other.extensions); onChanged(); } } @Override protected boolean parseUnknownField( CodedInputStream input, ExtensionRegistryLite extensionRegistry, int tag) throws IOException { ensureExtensionsIsMutable(); return MessageReflection.mergeFieldFrom( input, input.shouldDiscardUnknownFields() ? null : getUnknownFieldSetBuilder(), extensionRegistry, getDescriptorForType(), new MessageReflection.ExtensionBuilderAdapter(extensions), tag); } private void verifyContainingType(final FieldDescriptor field) { if (field.getContainingType() != getDescriptorForType()) { throw new IllegalArgumentException("FieldDescriptor does not match message type."); } } } // ----------------------------------------------------------------- /** * Gets the descriptor for an extension. The implementation depends on whether the extension is * scoped in the top level of a file or scoped in a Message. */ interface ExtensionDescriptorRetriever { FieldDescriptor getDescriptor(); } /** For use by generated code only. */ public static <ContainingT extends Message, T> GeneratedExtension<ContainingT, T> newMessageScopedGeneratedExtension( final Message scope, final int descriptorIndex, final Class<?> singularType, final Message defaultInstance) { // For extensions scoped within a Message, we use the Message to resolve // the outer class's descriptor, from which the extension descriptor is // obtained. return new GeneratedExtension<>( new CachedDescriptorRetriever() { @Override public FieldDescriptor loadDescriptor() { return scope.getDescriptorForType().getExtensions().get(descriptorIndex); } }, singularType, defaultInstance, Extension.ExtensionType.IMMUTABLE); } /** For use by generated code only. */ public static <ContainingT extends Message, T> GeneratedExtension<ContainingT, T> newFileScopedGeneratedExtension( final Class<?> singularType, final Message defaultInstance) { // For extensions scoped within a file, we rely on the outer class's // static initializer to call internalInit() on the extension when the // descriptor is available. return new GeneratedExtension<>( null, // ExtensionDescriptorRetriever is initialized in internalInit(); singularType, defaultInstance, Extension.ExtensionType.IMMUTABLE); } private abstract static class CachedDescriptorRetriever implements ExtensionDescriptorRetriever { private volatile FieldDescriptor descriptor; protected abstract FieldDescriptor loadDescriptor(); @Override public FieldDescriptor getDescriptor() { if (descriptor == null) { FieldDescriptor tmpDescriptor = loadDescriptor(); synchronized (this) { if (descriptor == null) { descriptor = tmpDescriptor; } } } return descriptor; } } /** * Type used to represent generated extensions. The protocol compiler generates a static singleton * instance of this class for each extension. * * <p>For example, imagine you have the {@code .proto} file: * * <pre> * option java_class = "MyProto"; * * message Foo { * extensions 1000 to max; * } * * extend Foo { * optional int32 bar; * } * </pre> * * <p>Then, {@code MyProto.Foo.bar} has type {@code GeneratedExtension<MyProto.Foo, Integer>}. * * <p>In general, users should ignore the details of this type, and simply use these static * singletons as parameters to the extension accessors defined in {@link ExtendableMessage} and * {@link ExtendableBuilder}. */ public static class GeneratedExtension<ContainingT extends Message, T> extends Extension<ContainingT, T> { // We can't always initialize the descriptor of a GeneratedExtension when // we first construct it due to initialization order difficulties (namely, // the descriptor may not have been constructed yet, since it is often // constructed by the initializer of a separate module). // // In the case of nested extensions, we initialize the // ExtensionDescriptorRetriever with an instance that uses the scoping // Message's default instance to retrieve the extension's descriptor. // // In the case of non-nested extensions, we initialize the // ExtensionDescriptorRetriever to null and rely on the outer class's static // initializer to call internalInit() after the descriptor has been parsed. GeneratedExtension( ExtensionDescriptorRetriever descriptorRetriever, Class<?> singularType, Message messageDefaultInstance, ExtensionType extensionType) { if (Message.class.isAssignableFrom(singularType) && !singularType.isInstance(messageDefaultInstance)) { throw new IllegalArgumentException( "Bad messageDefaultInstance for " + singularType.getName()); } this.descriptorRetriever = descriptorRetriever; this.singularType = singularType; this.messageDefaultInstance = messageDefaultInstance; if (ProtocolMessageEnum.class.isAssignableFrom(singularType)) { this.enumValueOf = getMethodOrDie(singularType, "valueOf", EnumValueDescriptor.class); this.enumGetValueDescriptor = getMethodOrDie(singularType, "getValueDescriptor"); } else { this.enumValueOf = null; this.enumGetValueDescriptor = null; } this.extensionType = extensionType; } /** For use by generated code only. */ public void internalInit(final FieldDescriptor descriptor) { if (descriptorRetriever != null) { throw new IllegalStateException("Already initialized."); } descriptorRetriever = new ExtensionDescriptorRetriever() { @Override public FieldDescriptor getDescriptor() { return descriptor; } }; } private ExtensionDescriptorRetriever descriptorRetriever; private final Class<?> singularType; private final Message messageDefaultInstance; private final Method enumValueOf; private final Method enumGetValueDescriptor; private final ExtensionType extensionType; @Override public FieldDescriptor getDescriptor() { if (descriptorRetriever == null) { throw new IllegalStateException("getDescriptor() called before internalInit()"); } return descriptorRetriever.getDescriptor(); } /** * If the extension is an embedded message or group, returns the default instance of the * message. */ @Override public Message getMessageDefaultInstance() { return messageDefaultInstance; } @Override protected ExtensionType getExtensionType() { return extensionType; } /** * Convert from the type used by the reflection accessors to the type used by native accessors. * E.g., for enums, the reflection accessors use EnumValueDescriptors but the native accessors * use the generated enum type. */ @Override protected Object fromReflectionType(final Object value) { FieldDescriptor descriptor = getDescriptor(); if (descriptor.isRepeated()) { if (descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE || descriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) { // Must convert the whole list. final List<Object> result = new ArrayList<>(); for (final Object element : (List<?>) value) { result.add(singularFromReflectionType(element)); } return result; } else { return value; } } else { return singularFromReflectionType(value); } } /** * Like {@link #fromReflectionType(Object)}, but if the type is a repeated type, this converts a * single element. */ @Override protected Object singularFromReflectionType(final Object value) { FieldDescriptor descriptor = getDescriptor(); switch (descriptor.getJavaType()) { case MESSAGE: if (singularType.isInstance(value)) { return value; } else { return messageDefaultInstance.newBuilderForType().mergeFrom((Message) value).build(); } case ENUM: return invokeOrDie(enumValueOf, null, value); default: return value; } } /** * Convert from the type used by the native accessors to the type used by reflection accessors. * E.g., for enums, the reflection accessors use EnumValueDescriptors but the native accessors * use the generated enum type. */ @Override protected Object toReflectionType(final Object value) { FieldDescriptor descriptor = getDescriptor(); if (descriptor.isRepeated()) { if (descriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) { // Must convert the whole list. final List<Object> result = new ArrayList<>(); for (final Object element : (List<?>) value) { result.add(singularToReflectionType(element)); } return result; } else { return value; } } else { return singularToReflectionType(value); } } /** * Like {@link #toReflectionType(Object)}, but if the type is a repeated type, this converts a * single element. */ @Override protected Object singularToReflectionType(final Object value) { FieldDescriptor descriptor = getDescriptor(); switch (descriptor.getJavaType()) { case ENUM: return invokeOrDie(enumGetValueDescriptor, value); default: return value; } } @Override public int getNumber() { return getDescriptor().getNumber(); } @Override public WireFormat.FieldType getLiteType() { return getDescriptor().getLiteType(); } @Override public boolean isRepeated() { return getDescriptor().isRepeated(); } @Override @SuppressWarnings("unchecked") public T getDefaultValue() { if (isRepeated()) { return (T) Collections.emptyList(); } if (getDescriptor().getJavaType() == FieldDescriptor.JavaType.MESSAGE) { return (T) messageDefaultInstance; } return (T) singularFromReflectionType(getDescriptor().getDefaultValue()); } } // ================================================================= /** Calls Class.getMethod and throws a RuntimeException if it fails. */ private static Method getMethodOrDie( final Class<?> clazz, final String name, final Class<?>... params) { try { return clazz.getMethod(name, params); } catch (NoSuchMethodException e) { throw new IllegalStateException( "Generated message class \"" + clazz.getName() + "\" missing method \"" + name + "\".", e); } } /** Calls invoke and throws a RuntimeException if it fails. */ @CanIgnoreReturnValue private static Object invokeOrDie( final Method method, final Object object, final Object... params) { try { return method.invoke(object, params); } catch (IllegalAccessException e) { throw new IllegalStateException( "Couldn't use Java reflection to implement protocol message reflection.", e); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error) cause; } else { throw new IllegalStateException( "Unexpected exception thrown by generated accessor method.", cause); } } } /** * Gets the map field with the given field number. This method should be overridden in the * generated message class if the message contains map fields. * * <p>Unlike other field types, reflection support for map fields can't be implemented based on * generated public API because we need to access a map field as a list in reflection API but the * generated API only allows us to access it as a map. This method returns the underlying map * field directly and thus enables us to access the map field as a list. */ @SuppressWarnings("unused") protected MapFieldReflectionAccessor internalGetMapFieldReflection(int fieldNumber) { return internalGetMapField(fieldNumber); } /** TODO: Remove, exists for compatibility with generated code. */ @Deprecated @SuppressWarnings({"rawtypes", "unused"}) protected MapField internalGetMapField(int fieldNumber) { // Note that we can't use descriptor names here because this method will // be called when descriptor is being initialized. throw new IllegalArgumentException("No map fields found in " + getClass().getName()); } /** * Users should ignore this class. This class provides the implementation with access to the * fields of a message object using Java reflection. */ public static final class FieldAccessorTable { /** * Construct a FieldAccessorTable for a particular message class. Only one FieldAccessorTable * should ever be constructed per class. * * @param descriptor The type's descriptor. * @param camelCaseNames The camelcase names of all fields in the message. These are used to * derive the accessor method names. * @param messageClass The message type. * @param builderClass The builder type. */ public FieldAccessorTable( final Descriptor descriptor, final String[] camelCaseNames, final Class<? extends GeneratedMessage> messageClass, final Class<? extends Builder<?>> builderClass) { this(descriptor, camelCaseNames); ensureFieldAccessorsInitialized(messageClass, builderClass); } /** * Construct a FieldAccessorTable for a particular message class without initializing * FieldAccessors. */ public FieldAccessorTable(final Descriptor descriptor, final String[] camelCaseNames) { this.descriptor = descriptor; this.camelCaseNames = camelCaseNames; fields = new FieldAccessor[descriptor.getFields().size()]; oneofs = new OneofAccessor[descriptor.getOneofs().size()]; initialized = false; } /** * Ensures the field accessors are initialized. This method is thread-safe. * * @param messageClass The message type. * @param builderClass The builder type. * @return this */ public FieldAccessorTable ensureFieldAccessorsInitialized( Class<? extends GeneratedMessage> messageClass, Class<? extends Builder<?>> builderClass) { if (initialized) { return this; } synchronized (this) { if (initialized) { return this; } int fieldsSize = fields.length; for (int i = 0; i < fieldsSize; i++) { FieldDescriptor field = descriptor.getFields().get(i); String containingOneofCamelCaseName = null; if (field.getContainingOneof() != null) { int index = fieldsSize + field.getContainingOneof().getIndex(); if (index < camelCaseNames.length) { containingOneofCamelCaseName = camelCaseNames[index]; } } if (field.isRepeated()) { if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { if (field.isMapField()) { fields[i] = new MapFieldAccessor(field, messageClass); } else { fields[i] = new RepeatedMessageFieldAccessor( field, camelCaseNames[i], messageClass, builderClass); } } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) { fields[i] = new RepeatedEnumFieldAccessor( field, camelCaseNames[i], messageClass, builderClass); } else { fields[i] = new RepeatedFieldAccessor(field, camelCaseNames[i], messageClass, builderClass); } } else { if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { fields[i] = new SingularMessageFieldAccessor( field, camelCaseNames[i], messageClass, builderClass, containingOneofCamelCaseName); } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) { fields[i] = new SingularEnumFieldAccessor( field, camelCaseNames[i], messageClass, builderClass, containingOneofCamelCaseName); } else if (field.getJavaType() == FieldDescriptor.JavaType.STRING) { fields[i] = new SingularStringFieldAccessor( field, camelCaseNames[i], messageClass, builderClass, containingOneofCamelCaseName); } else { fields[i] = new SingularFieldAccessor( field, camelCaseNames[i], messageClass, builderClass, containingOneofCamelCaseName); } } } for (int i = 0; i < descriptor.getOneofs().size(); i++) { if (i < descriptor.getRealOneofs().size()) { oneofs[i] = new RealOneofAccessor( descriptor, i, camelCaseNames[i + fieldsSize], messageClass, builderClass); } else { oneofs[i] = new SyntheticOneofAccessor(descriptor, i); } } initialized = true; camelCaseNames = null; return this; } } private final Descriptor descriptor; private final FieldAccessor[] fields; private String[] camelCaseNames; private final OneofAccessor[] oneofs; private volatile boolean initialized; /** Get the FieldAccessor for a particular field. */ private FieldAccessor getField(final FieldDescriptor field) { if (field.getContainingType() != descriptor) { throw new IllegalArgumentException("FieldDescriptor does not match message type."); } else if (field.isExtension()) { // If this type had extensions, it would subclass ExtendableMessage, // which overrides the reflection interface to handle extensions. throw new IllegalArgumentException("This type does not have extensions."); } return fields[field.getIndex()]; } /** Get the OneofAccessor for a particular oneof. */ private OneofAccessor getOneof(final OneofDescriptor oneof) { if (oneof.getContainingType() != descriptor) { throw new IllegalArgumentException("OneofDescriptor does not match message type."); } return oneofs[oneof.getIndex()]; } /** * Abstract interface that provides access to a single field. This is implemented differently * depending on the field type and cardinality. */ private interface FieldAccessor { Object get(GeneratedMessage message); Object get(GeneratedMessage.Builder<?> builder); Object getRaw(GeneratedMessage message); void set(Builder<?> builder, Object value); Object getRepeated(GeneratedMessage message, int index); Object getRepeated(GeneratedMessage.Builder<?> builder, int index); void setRepeated(Builder<?> builder, int index, Object value); void addRepeated(Builder<?> builder, Object value); boolean has(GeneratedMessage message); boolean has(GeneratedMessage.Builder<?> builder); int getRepeatedCount(GeneratedMessage message); int getRepeatedCount(GeneratedMessage.Builder<?> builder); void clear(Builder<?> builder); Message.Builder newBuilder(); Message.Builder getBuilder(GeneratedMessage.Builder<?> builder); Message.Builder getRepeatedBuilder(GeneratedMessage.Builder<?> builder, int index); } /** OneofAccessor provides access to a single oneof. */ private static interface OneofAccessor { public boolean has(final GeneratedMessage message); public boolean has(GeneratedMessage.Builder<?> builder); public FieldDescriptor get(final GeneratedMessage message); public FieldDescriptor get(GeneratedMessage.Builder<?> builder); public void clear(final Builder<?> builder); } /** RealOneofAccessor provides access to a single real oneof. */ private static class RealOneofAccessor implements OneofAccessor { RealOneofAccessor( final Descriptor descriptor, final int oneofIndex, final String camelCaseName, final Class<? extends GeneratedMessage> messageClass, final Class<? extends Builder<?>> builderClass) { this.descriptor = descriptor; caseMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "Case"); caseMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Case"); clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); } private final Descriptor descriptor; private final Method caseMethod; private final Method caseMethodBuilder; private final Method clearMethod; @Override public boolean has(final GeneratedMessage message) { return ((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber() != 0; } @Override public boolean has(GeneratedMessage.Builder<?> builder) { return ((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber() != 0; } @Override public FieldDescriptor get(final GeneratedMessage message) { int fieldNumber = ((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber(); if (fieldNumber > 0) { return descriptor.findFieldByNumber(fieldNumber); } return null; } @Override public FieldDescriptor get(GeneratedMessage.Builder<?> builder) { int fieldNumber = ((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber(); if (fieldNumber > 0) { return descriptor.findFieldByNumber(fieldNumber); } return null; } @Override public void clear(final Builder<?> builder) { // TODO: remove the unused variable Object unused = invokeOrDie(clearMethod, builder); } } /** SyntheticOneofAccessor provides access to a single synthetic oneof. */ private static class SyntheticOneofAccessor implements OneofAccessor { SyntheticOneofAccessor(final Descriptor descriptor, final int oneofIndex) { OneofDescriptor oneofDescriptor = descriptor.getOneofs().get(oneofIndex); fieldDescriptor = oneofDescriptor.getFields().get(0); } private final FieldDescriptor fieldDescriptor; @Override public boolean has(final GeneratedMessage message) { return message.hasField(fieldDescriptor); } @Override public boolean has(GeneratedMessage.Builder<?> builder) { return builder.hasField(fieldDescriptor); } @Override public FieldDescriptor get(final GeneratedMessage message) { return message.hasField(fieldDescriptor) ? fieldDescriptor : null; } public FieldDescriptor get(GeneratedMessage.Builder<?> builder) { return builder.hasField(fieldDescriptor) ? fieldDescriptor : null; } @Override public void clear(final Builder<?> builder) { builder.clearField(fieldDescriptor); } } // --------------------------------------------------------------- @SuppressWarnings("SameNameButDifferent") private static class SingularFieldAccessor implements FieldAccessor { private interface MethodInvoker { Object get(final GeneratedMessage message); Object get(GeneratedMessage.Builder<?> builder); int getOneofFieldNumber(final GeneratedMessage message); int getOneofFieldNumber(final GeneratedMessage.Builder<?> builder); void set(final GeneratedMessage.Builder<?> builder, final Object value); boolean has(final GeneratedMessage message); boolean has(GeneratedMessage.Builder<?> builder); void clear(final GeneratedMessage.Builder<?> builder); } private static final class ReflectionInvoker implements MethodInvoker { private final Method getMethod; private final Method getMethodBuilder; private final Method setMethod; private final Method hasMethod; private final Method hasMethodBuilder; private final Method clearMethod; private final Method caseMethod; private final Method caseMethodBuilder; ReflectionInvoker( final FieldDescriptor descriptor, final String camelCaseName, final Class<? extends GeneratedMessage> messageClass, final Class<? extends Builder<?>> builderClass, final String containingOneofCamelCaseName, boolean isOneofField, boolean hasHasMethod) { getMethod = getMethodOrDie(messageClass, "get" + camelCaseName); getMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName); Class<?> type = getMethod.getReturnType(); setMethod = getMethodOrDie(builderClass, "set" + camelCaseName, type); hasMethod = hasHasMethod ? getMethodOrDie(messageClass, "has" + camelCaseName) : null; hasMethodBuilder = hasHasMethod ? getMethodOrDie(builderClass, "has" + camelCaseName) : null; clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); caseMethod = isOneofField ? getMethodOrDie(messageClass, "get" + containingOneofCamelCaseName + "Case") : null; caseMethodBuilder = isOneofField ? getMethodOrDie(builderClass, "get" + containingOneofCamelCaseName + "Case") : null; } @Override public Object get(final GeneratedMessage message) { return invokeOrDie(getMethod, message); } @Override public Object get(GeneratedMessage.Builder<?> builder) { return invokeOrDie(getMethodBuilder, builder); } @Override public int getOneofFieldNumber(final GeneratedMessage message) { return ((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber(); } @Override public int getOneofFieldNumber(final GeneratedMessage.Builder<?> builder) { return ((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber(); } @Override public void set(final GeneratedMessage.Builder<?> builder, final Object value) { // TODO: remove the unused variable Object unused = invokeOrDie(setMethod, builder, value); } @Override public boolean has(final GeneratedMessage message) { return (Boolean) invokeOrDie(hasMethod, message); } @Override public boolean has(GeneratedMessage.Builder<?> builder) { return (Boolean) invokeOrDie(hasMethodBuilder, builder); } @Override public void clear(final GeneratedMessage.Builder<?> builder) { // TODO: remove the unused variable Object unused = invokeOrDie(clearMethod, builder); } } SingularFieldAccessor( final FieldDescriptor descriptor, final String camelCaseName, final Class<? extends GeneratedMessage> messageClass, final Class<? extends Builder<?>> builderClass, final String containingOneofCamelCaseName) { isOneofField = descriptor.getRealContainingOneof() != null; hasHasMethod = descriptor.hasPresence(); ReflectionInvoker reflectionInvoker = new ReflectionInvoker( descriptor, camelCaseName, messageClass, builderClass, containingOneofCamelCaseName, isOneofField, hasHasMethod); field = descriptor; type = reflectionInvoker.getMethod.getReturnType(); invoker = getMethodInvoker(reflectionInvoker); } static MethodInvoker getMethodInvoker(ReflectionInvoker accessor) { return accessor; } // Note: We use Java reflection to call public methods rather than // access private fields directly as this avoids runtime security // checks. protected final Class<?> type; protected final FieldDescriptor field; protected final boolean isOneofField; protected final boolean hasHasMethod; protected final MethodInvoker invoker; @Override public Object get(final GeneratedMessage message) { return invoker.get(message); } @Override public Object get(GeneratedMessage.Builder<?> builder) { return invoker.get(builder); } @Override public Object getRaw(final GeneratedMessage message) { return get(message); } @Override public void set(final Builder<?> builder, final Object value) { invoker.set(builder, value); } @Override public Object getRepeated(final GeneratedMessage message, final int index) { throw new UnsupportedOperationException("getRepeatedField() called on a singular field."); } @Override public Object getRepeated(GeneratedMessage.Builder<?> builder, int index) { throw new UnsupportedOperationException("getRepeatedField() called on a singular field."); } @Override public void setRepeated(final Builder<?> builder, final int index, final Object value) { throw new UnsupportedOperationException("setRepeatedField() called on a singular field."); } @Override public void addRepeated(final Builder<?> builder, final Object value) { throw new UnsupportedOperationException("addRepeatedField() called on a singular field."); } @Override public boolean has(final GeneratedMessage message) { if (!hasHasMethod) { if (isOneofField) { return invoker.getOneofFieldNumber(message) == field.getNumber(); } return !get(message).equals(field.getDefaultValue()); } return invoker.has(message); } @Override public boolean has(GeneratedMessage.Builder<?> builder) { if (!hasHasMethod) { if (isOneofField) { return invoker.getOneofFieldNumber(builder) == field.getNumber(); } return !get(builder).equals(field.getDefaultValue()); } return invoker.has(builder); } @Override public int getRepeatedCount(final GeneratedMessage message) { throw new UnsupportedOperationException( "getRepeatedFieldSize() called on a singular field."); } @Override public int getRepeatedCount(GeneratedMessage.Builder<?> builder) { throw new UnsupportedOperationException( "getRepeatedFieldSize() called on a singular field."); } @Override public void clear(final Builder<?> builder) { invoker.clear(builder); } @Override public Message.Builder newBuilder() { throw new UnsupportedOperationException( "newBuilderForField() called on a non-Message type."); } @Override public Message.Builder getBuilder(GeneratedMessage.Builder<?> builder) { throw new UnsupportedOperationException("getFieldBuilder() called on a non-Message type."); } @Override public Message.Builder getRepeatedBuilder(GeneratedMessage.Builder<?> builder, int index) { throw new UnsupportedOperationException( "getRepeatedFieldBuilder() called on a non-Message type."); } } @SuppressWarnings("SameNameButDifferent") private static class RepeatedFieldAccessor implements FieldAccessor { interface MethodInvoker { Object get(final GeneratedMessage message); Object get(GeneratedMessage.Builder<?> builder); Object getRepeated(final GeneratedMessage message, final int index); Object getRepeated(GeneratedMessage.Builder<?> builder, int index); void setRepeated( final GeneratedMessage.Builder<?> builder, final int index, final Object value); void addRepeated(final GeneratedMessage.Builder<?> builder, final Object value); int getRepeatedCount(final GeneratedMessage message); int getRepeatedCount(GeneratedMessage.Builder<?> builder); void clear(final GeneratedMessage.Builder<?> builder); } private static final class ReflectionInvoker implements MethodInvoker { private final Method getMethod; private final Method getMethodBuilder; private final Method getRepeatedMethod; private final Method getRepeatedMethodBuilder; private final Method setRepeatedMethod; private final Method addRepeatedMethod; private final Method getCountMethod; private final Method getCountMethodBuilder; private final Method clearMethod; ReflectionInvoker( final FieldDescriptor descriptor, final String camelCaseName, final Class<? extends GeneratedMessage> messageClass, final Class<? extends Builder<?>> builderClass) { getMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "List"); getMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "List"); getRepeatedMethod = getMethodOrDie(messageClass, "get" + camelCaseName, Integer.TYPE); getRepeatedMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName, Integer.TYPE); Class<?> type = getRepeatedMethod.getReturnType(); setRepeatedMethod = getMethodOrDie(builderClass, "set" + camelCaseName, Integer.TYPE, type); addRepeatedMethod = getMethodOrDie(builderClass, "add" + camelCaseName, type); getCountMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "Count"); getCountMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Count"); clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); } @Override public Object get(final GeneratedMessage message) { return invokeOrDie(getMethod, message); } @Override public Object get(GeneratedMessage.Builder<?> builder) { return invokeOrDie(getMethodBuilder, builder); } @Override public Object getRepeated(final GeneratedMessage message, final int index) { return invokeOrDie(getRepeatedMethod, message, index); } @Override public Object getRepeated(GeneratedMessage.Builder<?> builder, int index) { return invokeOrDie(getRepeatedMethodBuilder, builder, index); } @Override public void setRepeated( final GeneratedMessage.Builder<?> builder, final int index, final Object value) { // TODO: remove the unused variable Object unused = invokeOrDie(setRepeatedMethod, builder, index, value); } @Override public void addRepeated(final GeneratedMessage.Builder<?> builder, final Object value) { // TODO: remove the unused variable Object unused = invokeOrDie(addRepeatedMethod, builder, value); } @Override public int getRepeatedCount(final GeneratedMessage message) { return (Integer) invokeOrDie(getCountMethod, message); } @Override public int getRepeatedCount(GeneratedMessage.Builder<?> builder) { return (Integer) invokeOrDie(getCountMethodBuilder, builder); } @Override public void clear(final GeneratedMessage.Builder<?> builder) { // TODO: remove the unused variable Object unused = invokeOrDie(clearMethod, builder); } } protected final Class<?> type; protected final MethodInvoker invoker; RepeatedFieldAccessor( final FieldDescriptor descriptor, final String camelCaseName, final Class<? extends GeneratedMessage> messageClass, final Class<? extends Builder<?>> builderClass) { ReflectionInvoker reflectionInvoker = new ReflectionInvoker(descriptor, camelCaseName, messageClass, builderClass); type = reflectionInvoker.getRepeatedMethod.getReturnType(); invoker = getMethodInvoker(reflectionInvoker); } static MethodInvoker getMethodInvoker(ReflectionInvoker accessor) { return accessor; } @Override public Object get(final GeneratedMessage message) { return invoker.get(message); } @Override public Object get(GeneratedMessage.Builder<?> builder) { return invoker.get(builder); } @Override public Object getRaw(final GeneratedMessage message) { return get(message); } @Override public void set(final Builder<?> builder, final Object value) { // Add all the elements individually. This serves two purposes: // 1) Verifies that each element has the correct type. // 2) Insures that the caller cannot modify the list later on and // have the modifications be reflected in the message. clear(builder); for (final Object element : (List<?>) value) { addRepeated(builder, element); } } @Override public Object getRepeated(final GeneratedMessage message, final int index) { return invoker.getRepeated(message, index); } @Override public Object getRepeated(GeneratedMessage.Builder<?> builder, int index) { return invoker.getRepeated(builder, index); } @Override public void setRepeated(final Builder<?> builder, final int index, final Object value) { invoker.setRepeated(builder, index, value); } @Override public void addRepeated(final Builder<?> builder, final Object value) { invoker.addRepeated(builder, value); } @Override public boolean has(final GeneratedMessage message) { throw new UnsupportedOperationException("hasField() called on a repeated field."); } @Override public boolean has(GeneratedMessage.Builder<?> builder) { throw new UnsupportedOperationException("hasField() called on a repeated field."); } @Override public int getRepeatedCount(final GeneratedMessage message) { return invoker.getRepeatedCount(message); } @Override public int getRepeatedCount(GeneratedMessage.Builder<?> builder) { return invoker.getRepeatedCount(builder); } @Override public void clear(final Builder<?> builder) { invoker.clear(builder); } @Override public Message.Builder newBuilder() { throw new UnsupportedOperationException( "newBuilderForField() called on a non-Message type."); } @Override public Message.Builder getBuilder(GeneratedMessage.Builder<?> builder) { throw new UnsupportedOperationException("getFieldBuilder() called on a non-Message type."); } @Override public Message.Builder getRepeatedBuilder(GeneratedMessage.Builder<?> builder, int index) { throw new UnsupportedOperationException( "getRepeatedFieldBuilder() called on a non-Message type."); } } private static class MapFieldAccessor implements FieldAccessor { MapFieldAccessor( final FieldDescriptor descriptor, final Class<? extends GeneratedMessage> messageClass) { field = descriptor; Method getDefaultInstanceMethod = getMethodOrDie(messageClass, "getDefaultInstance"); MapFieldReflectionAccessor defaultMapField = getMapField((GeneratedMessage) invokeOrDie(getDefaultInstanceMethod, null)); mapEntryMessageDefaultInstance = defaultMapField.getMapEntryMessageDefaultInstance(); } private final FieldDescriptor field; private final Message mapEntryMessageDefaultInstance; private MapFieldReflectionAccessor getMapField(GeneratedMessage message) { return message.internalGetMapFieldReflection(field.getNumber()); } private MapFieldReflectionAccessor getMapField(GeneratedMessage.Builder<?> builder) { return builder.internalGetMapFieldReflection(field.getNumber()); } private MapFieldReflectionAccessor getMutableMapField(GeneratedMessage.Builder<?> builder) { return builder.internalGetMutableMapFieldReflection(field.getNumber()); } private Message coerceType(Message value) { if (value == null) { return null; } if (mapEntryMessageDefaultInstance.getClass().isInstance(value)) { return value; } // The value is not the exact right message type. However, if it // is an alternative implementation of the same type -- e.g. a // DynamicMessage -- we should accept it. In this case we can make // a copy of the message. return mapEntryMessageDefaultInstance.toBuilder().mergeFrom(value).build(); } @Override public Object get(GeneratedMessage message) { List<Object> result = new ArrayList<>(); for (int i = 0; i < getRepeatedCount(message); i++) { result.add(getRepeated(message, i)); } return Collections.unmodifiableList(result); } @Override public Object get(Builder<?> builder) { List<Object> result = new ArrayList<>(); for (int i = 0; i < getRepeatedCount(builder); i++) { result.add(getRepeated(builder, i)); } return Collections.unmodifiableList(result); } @Override public Object getRaw(GeneratedMessage message) { return get(message); } @Override public void set(Builder<?> builder, Object value) { clear(builder); for (Object entry : (List<?>) value) { addRepeated(builder, entry); } } @Override public Object getRepeated(GeneratedMessage message, int index) { return getMapField(message).getList().get(index); } @Override public Object getRepeated(Builder<?> builder, int index) { return getMapField(builder).getList().get(index); } @Override public void setRepeated(Builder<?> builder, int index, Object value) { getMutableMapField(builder).getMutableList().set(index, coerceType((Message) value)); } @Override public void addRepeated(Builder<?> builder, Object value) { getMutableMapField(builder).getMutableList().add(coerceType((Message) value)); } @Override public boolean has(GeneratedMessage message) { throw new UnsupportedOperationException("hasField() is not supported for repeated fields."); } @Override public boolean has(Builder<?> builder) { throw new UnsupportedOperationException("hasField() is not supported for repeated fields."); } @Override public int getRepeatedCount(GeneratedMessage message) { return getMapField(message).getList().size(); } @Override public int getRepeatedCount(Builder<?> builder) { return getMapField(builder).getList().size(); } @Override public void clear(Builder<?> builder) { getMutableMapField(builder).getMutableList().clear(); } @Override public Message.Builder newBuilder() { return mapEntryMessageDefaultInstance.newBuilderForType(); } @Override public Message.Builder getBuilder(Builder<?> builder) { throw new UnsupportedOperationException("Nested builder not supported for map fields."); } @Override public Message.Builder getRepeatedBuilder(Builder<?> builder, int index) { throw new UnsupportedOperationException("Map fields cannot be repeated"); } } // --------------------------------------------------------------- private static final class SingularEnumFieldAccessor extends SingularFieldAccessor { SingularEnumFieldAccessor( final FieldDescriptor descriptor, final String camelCaseName, final Class<? extends GeneratedMessage> messageClass, final Class<? extends Builder<?>> builderClass, final String containingOneofCamelCaseName) { super(descriptor, camelCaseName, messageClass, builderClass, containingOneofCamelCaseName); enumDescriptor = descriptor.getEnumType(); valueOfMethod = getMethodOrDie(type, "valueOf", EnumValueDescriptor.class); getValueDescriptorMethod = getMethodOrDie(type, "getValueDescriptor"); supportUnknownEnumValue = !descriptor.legacyEnumFieldTreatedAsClosed(); if (supportUnknownEnumValue) { getValueMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "Value"); getValueMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Value"); setValueMethod = getMethodOrDie(builderClass, "set" + camelCaseName + "Value", int.class); } } private final EnumDescriptor enumDescriptor; private final Method valueOfMethod; private final Method getValueDescriptorMethod; private final boolean supportUnknownEnumValue; private Method getValueMethod; private Method getValueMethodBuilder; private Method setValueMethod; @Override public Object get(final GeneratedMessage message) { if (supportUnknownEnumValue) { int value = (Integer) invokeOrDie(getValueMethod, message); return enumDescriptor.findValueByNumberCreatingIfUnknown(value); } return invokeOrDie(getValueDescriptorMethod, super.get(message)); } @Override public Object get(final GeneratedMessage.Builder<?> builder) { if (supportUnknownEnumValue) { int value = (Integer) invokeOrDie(getValueMethodBuilder, builder); return enumDescriptor.findValueByNumberCreatingIfUnknown(value); } return invokeOrDie(getValueDescriptorMethod, super.get(builder)); } @Override public void set(final Builder<?> builder, final Object value) { if (supportUnknownEnumValue) { // TODO: remove the unused variable Object unused = invokeOrDie(setValueMethod, builder, ((EnumValueDescriptor) value).getNumber()); return; } super.set(builder, invokeOrDie(valueOfMethod, null, value)); } } private static final class RepeatedEnumFieldAccessor extends RepeatedFieldAccessor { RepeatedEnumFieldAccessor( final FieldDescriptor descriptor, final String camelCaseName, final Class<? extends GeneratedMessage> messageClass, final Class<? extends Builder<?>> builderClass) { super(descriptor, camelCaseName, messageClass, builderClass); enumDescriptor = descriptor.getEnumType(); valueOfMethod = getMethodOrDie(type, "valueOf", EnumValueDescriptor.class); getValueDescriptorMethod = getMethodOrDie(type, "getValueDescriptor"); supportUnknownEnumValue = !descriptor.legacyEnumFieldTreatedAsClosed(); if (supportUnknownEnumValue) { getRepeatedValueMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "Value", int.class); getRepeatedValueMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Value", int.class); setRepeatedValueMethod = getMethodOrDie(builderClass, "set" + camelCaseName + "Value", int.class, int.class); addRepeatedValueMethod = getMethodOrDie(builderClass, "add" + camelCaseName + "Value", int.class); } } private final EnumDescriptor enumDescriptor; private final Method valueOfMethod; private final Method getValueDescriptorMethod; private final boolean supportUnknownEnumValue; private Method getRepeatedValueMethod; private Method getRepeatedValueMethodBuilder; private Method setRepeatedValueMethod; private Method addRepeatedValueMethod; @Override public Object get(final GeneratedMessage message) { final List<Object> newList = new ArrayList<>(); final int size = getRepeatedCount(message); for (int i = 0; i < size; i++) { newList.add(getRepeated(message, i)); } return Collections.unmodifiableList(newList); } @Override public Object get(final GeneratedMessage.Builder<?> builder) { final List<Object> newList = new ArrayList<>(); final int size = getRepeatedCount(builder); for (int i = 0; i < size; i++) { newList.add(getRepeated(builder, i)); } return Collections.unmodifiableList(newList); } @Override public Object getRepeated(final GeneratedMessage message, final int index) { if (supportUnknownEnumValue) { int value = (Integer) invokeOrDie(getRepeatedValueMethod, message, index); return enumDescriptor.findValueByNumberCreatingIfUnknown(value); } return invokeOrDie(getValueDescriptorMethod, super.getRepeated(message, index)); } @Override public Object getRepeated(final GeneratedMessage.Builder<?> builder, final int index) { if (supportUnknownEnumValue) { int value = (Integer) invokeOrDie(getRepeatedValueMethodBuilder, builder, index); return enumDescriptor.findValueByNumberCreatingIfUnknown(value); } return invokeOrDie(getValueDescriptorMethod, super.getRepeated(builder, index)); } @Override public void setRepeated(final Builder<?> builder, final int index, final Object value) { if (supportUnknownEnumValue) { // TODO: remove the unused variable Object unused = invokeOrDie( setRepeatedValueMethod, builder, index, ((EnumValueDescriptor) value).getNumber()); return; } super.setRepeated(builder, index, invokeOrDie(valueOfMethod, null, value)); } @Override public void addRepeated(final Builder<?> builder, final Object value) { if (supportUnknownEnumValue) { // TODO: remove the unused variable Object unused = invokeOrDie( addRepeatedValueMethod, builder, ((EnumValueDescriptor) value).getNumber()); return; } super.addRepeated(builder, invokeOrDie(valueOfMethod, null, value)); } } // --------------------------------------------------------------- /** * Field accessor for string fields. * * <p>This class makes getFooBytes() and setFooBytes() available for reflection API so that * reflection based serialize/parse functions can access the raw bytes of the field to preserve * non-UTF8 bytes in the string. * * <p>This ensures the serialize/parse round-trip safety, which is important for servers which * forward messages. */ private static final class SingularStringFieldAccessor extends SingularFieldAccessor { SingularStringFieldAccessor( final FieldDescriptor descriptor, final String camelCaseName, final Class<? extends GeneratedMessage> messageClass, final Class<? extends Builder<?>> builderClass, final String containingOneofCamelCaseName) { super(descriptor, camelCaseName, messageClass, builderClass, containingOneofCamelCaseName); getBytesMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "Bytes"); setBytesMethodBuilder = getMethodOrDie(builderClass, "set" + camelCaseName + "Bytes", ByteString.class); } private final Method getBytesMethod; private final Method setBytesMethodBuilder; @Override public Object getRaw(final GeneratedMessage message) { return invokeOrDie(getBytesMethod, message); } @Override public void set(GeneratedMessage.Builder<?> builder, Object value) { if (value instanceof ByteString) { // TODO: remove the unused variable Object unused = invokeOrDie(setBytesMethodBuilder, builder, value); } else { super.set(builder, value); } } } // --------------------------------------------------------------- private static final class SingularMessageFieldAccessor extends SingularFieldAccessor { SingularMessageFieldAccessor( final FieldDescriptor descriptor, final String camelCaseName, final Class<? extends GeneratedMessage> messageClass, final Class<? extends Builder<?>> builderClass, final String containingOneofCamelCaseName) { super(descriptor, camelCaseName, messageClass, builderClass, containingOneofCamelCaseName); newBuilderMethod = getMethodOrDie(type, "newBuilder"); getBuilderMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Builder"); } private final Method newBuilderMethod; private final Method getBuilderMethodBuilder; private Object coerceType(final Object value) { if (type.isInstance(value)) { return value; } else { // The value is not the exact right message type. However, if it // is an alternative implementation of the same type -- e.g. a // DynamicMessage -- we should accept it. In this case we can make // a copy of the message. return ((Message.Builder) invokeOrDie(newBuilderMethod, null)) .mergeFrom((Message) value) .buildPartial(); } } @Override public void set(final Builder<?> builder, final Object value) { super.set(builder, coerceType(value)); } @Override public Message.Builder newBuilder() { return (Message.Builder) invokeOrDie(newBuilderMethod, null); } @Override public Message.Builder getBuilder(GeneratedMessage.Builder<?> builder) { return (Message.Builder) invokeOrDie(getBuilderMethodBuilder, builder); } } private static final class RepeatedMessageFieldAccessor extends RepeatedFieldAccessor { RepeatedMessageFieldAccessor( final FieldDescriptor descriptor, final String camelCaseName, final Class<? extends GeneratedMessage> messageClass, final Class<? extends Builder<?>> builderClass) { super(descriptor, camelCaseName, messageClass, builderClass); newBuilderMethod = getMethodOrDie(type, "newBuilder"); getBuilderMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Builder", Integer.TYPE); } private final Method newBuilderMethod; private final Method getBuilderMethodBuilder; private Object coerceType(final Object value) { if (type.isInstance(value)) { return value; } else { // The value is not the exact right message type. However, if it // is an alternative implementation of the same type -- e.g. a // DynamicMessage -- we should accept it. In this case we can make // a copy of the message. return ((Message.Builder) invokeOrDie(newBuilderMethod, null)) .mergeFrom((Message) value) .build(); } } @Override public void setRepeated(final Builder<?> builder, final int index, final Object value) { super.setRepeated(builder, index, coerceType(value)); } @Override public void addRepeated(final Builder<?> builder, final Object value) { super.addRepeated(builder, coerceType(value)); } @Override public Message.Builder newBuilder() { return (Message.Builder) invokeOrDie(newBuilderMethod, null); } @Override public Message.Builder getRepeatedBuilder( final GeneratedMessage.Builder<?> builder, final int index) { return (Message.Builder) invokeOrDie(getBuilderMethodBuilder, builder, index); } } } /** * Replaces this object in the output stream with a serialized form. Part of Java's serialization * magic. Generated sub-classes must override this method by calling {@code return * super.writeReplace();} * * @return a SerializedForm of this message */ protected Object writeReplace() throws ObjectStreamException { return new GeneratedMessageLite.SerializedForm(this); } /** * Checks that the {@link Extension} is non-Lite and returns it as a {@link GeneratedExtension}. */ private static <MessageT extends ExtendableMessage<MessageT>, T> Extension<MessageT, T> checkNotLite(ExtensionLite<MessageT, T> extension) { if (extension.isLite()) { throw new IllegalArgumentException("Expected non-lite extension."); } return (Extension<MessageT, T>) extension; } protected static boolean isStringEmpty(final Object value) { if (value instanceof String) { return ((String) value).isEmpty(); } else { return ((ByteString) value).isEmpty(); } } protected static int computeStringSize(final int fieldNumber, final Object value) { if (value instanceof String) { return CodedOutputStream.computeStringSize(fieldNumber, (String) value); } else { return CodedOutputStream.computeBytesSize(fieldNumber, (ByteString) value); } } protected static int computeStringSizeNoTag(final Object value) { if (value instanceof String) { return CodedOutputStream.computeStringSizeNoTag((String) value); } else { return CodedOutputStream.computeBytesSizeNoTag((ByteString) value); } } protected static void writeString( CodedOutputStream output, final int fieldNumber, final Object value) throws IOException { if (value instanceof String) { output.writeString(fieldNumber, (String) value); } else { output.writeBytes(fieldNumber, (ByteString) value); } } protected static void writeStringNoTag(CodedOutputStream output, final Object value) throws IOException { if (value instanceof String) { output.writeStringNoTag((String) value); } else { output.writeBytesNoTag((ByteString) value); } } protected static <V> void serializeIntegerMapTo( CodedOutputStream out, MapField<Integer, V> field, MapEntry<Integer, V> defaultEntry, int fieldNumber) throws IOException { Map<Integer, V> m = field.getMap(); if (!out.isSerializationDeterministic()) { serializeMapTo(out, m, defaultEntry, fieldNumber); return; } // Sorting the unboxed keys and then look up the values during serialization is 2x faster // than sorting map entries with a custom comparator directly. int[] keys = new int[m.size()]; int index = 0; for (int k : m.keySet()) { keys[index++] = k; } Arrays.sort(keys); for (int key : keys) { out.writeMessage( fieldNumber, defaultEntry.newBuilderForType().setKey(key).setValue(m.get(key)).build()); } } protected static <V> void serializeLongMapTo( CodedOutputStream out, MapField<Long, V> field, MapEntry<Long, V> defaultEntry, int fieldNumber) throws IOException { Map<Long, V> m = field.getMap(); if (!out.isSerializationDeterministic()) { serializeMapTo(out, m, defaultEntry, fieldNumber); return; } long[] keys = new long[m.size()]; int index = 0; for (long k : m.keySet()) { keys[index++] = k; } Arrays.sort(keys); for (long key : keys) { out.writeMessage( fieldNumber, defaultEntry.newBuilderForType().setKey(key).setValue(m.get(key)).build()); } } protected static <V> void serializeStringMapTo( CodedOutputStream out, MapField<String, V> field, MapEntry<String, V> defaultEntry, int fieldNumber) throws IOException { Map<String, V> m = field.getMap(); if (!out.isSerializationDeterministic()) { serializeMapTo(out, m, defaultEntry, fieldNumber); return; } // Sorting the String keys and then look up the values during serialization is 25% faster than // sorting map entries with a custom comparator directly. String[] keys = new String[m.size()]; keys = m.keySet().toArray(keys); Arrays.sort(keys); for (String key : keys) { out.writeMessage( fieldNumber, defaultEntry.newBuilderForType().setKey(key).setValue(m.get(key)).build()); } } protected static <V> void serializeBooleanMapTo( CodedOutputStream out, MapField<Boolean, V> field, MapEntry<Boolean, V> defaultEntry, int fieldNumber) throws IOException { Map<Boolean, V> m = field.getMap(); if (!out.isSerializationDeterministic()) { serializeMapTo(out, m, defaultEntry, fieldNumber); return; } maybeSerializeBooleanEntryTo(out, m, defaultEntry, fieldNumber, false); maybeSerializeBooleanEntryTo(out, m, defaultEntry, fieldNumber, true); } private static <V> void maybeSerializeBooleanEntryTo( CodedOutputStream out, Map<Boolean, V> m, MapEntry<Boolean, V> defaultEntry, int fieldNumber, boolean key) throws IOException { if (m.containsKey(key)) { out.writeMessage( fieldNumber, defaultEntry.newBuilderForType().setKey(key).setValue(m.get(key)).build()); } } /** Serialize the map using the iteration order. */ private static <K, V> void serializeMapTo( CodedOutputStream out, Map<K, V> m, MapEntry<K, V> defaultEntry, int fieldNumber) throws IOException { for (Map.Entry<K, V> entry : m.entrySet()) { out.writeMessage( fieldNumber, defaultEntry .newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build()); } } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/GeneratedMessage.java
2,112
// Copyright 2020 The Bazel Authors. 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.google.devtools.build.lib.worker; import com.google.common.hash.HashCode; import com.google.devtools.build.lib.actions.UserExecException; import com.google.devtools.build.lib.events.EventHandler; import com.google.devtools.build.lib.sandbox.CgroupsInfo; import com.google.devtools.build.lib.sandbox.SandboxHelpers.SandboxInputs; import com.google.devtools.build.lib.sandbox.SandboxHelpers.SandboxOutputs; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; import com.google.devtools.build.lib.worker.WorkerProtocol.WorkRequest; import com.google.devtools.build.lib.worker.WorkerProtocol.WorkResponse; import java.io.IOException; import java.util.Optional; import java.util.Set; import java.util.SortedMap; import javax.annotation.Nullable; /** * An abstract superclass for persistent workers. Workers execute actions in long-running processes * that can handle multiple actions. */ public abstract class Worker { /** An unique identifier of the work process. */ protected final WorkerKey workerKey; /** An unique ID of the worker. It will be used in WorkRequest and WorkResponse as well. */ protected final int workerId; /** The path of the log file for this worker. */ protected final Path logFile; public Worker(WorkerKey workerKey, int workerId, Path logFile, WorkerProcessStatus status) { this.workerKey = workerKey; this.workerId = workerId; this.logFile = logFile; this.status = status; } protected final WorkerProcessStatus status; @Nullable protected CgroupsInfo cgroup = null; /** * Returns a unique id for this worker. This is used to distinguish different worker processes in * logs and messages. */ public int getWorkerId() { return this.workerId; } /** Returns the path of the log file for this worker. */ public Path getLogFile() { return logFile; } /** Returns the worker key of this worker */ public WorkerKey getWorkerKey() { return workerKey; } public WorkerProcessStatus getStatus() { return status; } @Nullable public CgroupsInfo getCgroup() { return cgroup; } HashCode getWorkerFilesCombinedHash() { return workerKey.getWorkerFilesCombinedHash(); } SortedMap<PathFragment, byte[]> getWorkerFilesWithDigests() { return workerKey.getWorkerFilesWithDigests(); } /** Returns true if this worker is sandboxed. */ public abstract boolean isSandboxed(); /** * Sets the reporter this {@code Worker} should report anomalous events to, or clears it. We * expect the reporter to be cleared at end of build. */ void setReporter(EventHandler reporter) {} /** * Performs the necessary steps to prepare for execution. Once this is done, the worker should be * able to receive a WorkRequest without further setup. */ public abstract void prepareExecution( SandboxInputs inputFiles, SandboxOutputs outputs, Set<PathFragment> workerFiles) throws IOException, InterruptedException, UserExecException; /** * Sends a WorkRequest to the worker. * * @param request The request to send. * @throws IOException If there was a problem doing I/O, or this thread was interrupted at a time * where some or all of the expected I/O has been done. */ abstract void putRequest(WorkRequest request) throws IOException; /** * Waits to receive a response from the worker. This method should return as soon as a response * has been received, moving of files and cleanup should wait until finishExecution(). * * @param requestId ID of the request to retrieve a response for. * @return The WorkResponse received. * @throws IOException If there was a problem doing I/O. * @throws InterruptedException If this thread was interrupted, which can also happen during IO. */ abstract WorkResponse getResponse(int requestId) throws IOException, InterruptedException; /** * Does whatever cleanup may be required after execution is done. * * @param execRoot The global execRoot, where outputs must go. * @param outputs The expected outputs. */ public void finishExecution(Path execRoot, SandboxOutputs outputs) throws IOException { status.maybeUpdateStatus(WorkerProcessStatus.Status.ALIVE); } /** * Destroys this worker. Once this has been called, we assume it's safe to clean up related * directories. */ abstract void destroy(); /** Returns true if this worker is dead but we didn't deliberately kill it. */ abstract boolean diedUnexpectedly(); /** Returns the exit value of this worker's process, if it has exited. */ public abstract Optional<Integer> getExitValue(); /** * Returns the last message received on the InputStream, if an unparseable message has been * received. */ abstract String getRecordingStreamMessage(); /** Returns process id pf worker, if process started. Otherwise returns -1. */ abstract long getProcessId(); }
bazelbuild/bazel
src/main/java/com/google/devtools/build/lib/worker/Worker.java
2,113
/* * 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.channel; import io.netty.channel.Channel.Unsafe; import io.netty.util.ReferenceCountUtil; import io.netty.util.ResourceLeakDetector; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.FastThreadLocal; import io.netty.util.internal.ObjectUtil; import io.netty.util.internal.StringUtil; import io.netty.util.internal.UnstableApi; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.net.SocketAddress; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.WeakHashMap; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; /** * The default {@link ChannelPipeline} implementation. It is usually created * by a {@link Channel} implementation when the {@link Channel} is created. */ public class DefaultChannelPipeline implements ChannelPipeline { static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelPipeline.class); private static final String HEAD_NAME = generateName0(HeadContext.class); private static final String TAIL_NAME = generateName0(TailContext.class); private static final FastThreadLocal<Map<Class<?>, String>> nameCaches = new FastThreadLocal<Map<Class<?>, String>>() { @Override protected Map<Class<?>, String> initialValue() { return new WeakHashMap<Class<?>, String>(); } }; private static final AtomicReferenceFieldUpdater<DefaultChannelPipeline, MessageSizeEstimator.Handle> ESTIMATOR = AtomicReferenceFieldUpdater.newUpdater( DefaultChannelPipeline.class, MessageSizeEstimator.Handle.class, "estimatorHandle"); final HeadContext head; final TailContext tail; private final Channel channel; private final ChannelFuture succeededFuture; private final VoidChannelPromise voidPromise; private final boolean touch = ResourceLeakDetector.isEnabled(); private Map<EventExecutorGroup, EventExecutor> childExecutors; private volatile MessageSizeEstimator.Handle estimatorHandle; private boolean firstRegistration = true; /** * This is the head of a linked list that is processed by {@link #callHandlerAddedForAllHandlers()} and so process * all the pending {@link #callHandlerAdded0(AbstractChannelHandlerContext)}. * * We only keep the head because it is expected that the list is used infrequently and its size is small. * Thus full iterations to do insertions is assumed to be a good compromised to saving memory and tail management * complexity. */ private PendingHandlerCallback pendingHandlerCallbackHead; /** * Set to {@code true} once the {@link AbstractChannel} is registered.Once set to {@code true} the value will never * change. */ private boolean registered; protected DefaultChannelPipeline(Channel channel) { this.channel = ObjectUtil.checkNotNull(channel, "channel"); succeededFuture = new SucceededChannelFuture(channel, null); voidPromise = new VoidChannelPromise(channel, true); tail = new TailContext(this); head = new HeadContext(this); head.next = tail; tail.prev = head; } final MessageSizeEstimator.Handle estimatorHandle() { MessageSizeEstimator.Handle handle = estimatorHandle; if (handle == null) { handle = channel.config().getMessageSizeEstimator().newHandle(); if (!ESTIMATOR.compareAndSet(this, null, handle)) { handle = estimatorHandle; } } return handle; } final Object touch(Object msg, AbstractChannelHandlerContext next) { return touch ? ReferenceCountUtil.touch(msg, next) : msg; } private AbstractChannelHandlerContext newContext(EventExecutorGroup group, String name, ChannelHandler handler) { return new DefaultChannelHandlerContext(this, childExecutor(group), name, handler); } private EventExecutor childExecutor(EventExecutorGroup group) { if (group == null) { return null; } Boolean pinEventExecutor = channel.config().getOption(ChannelOption.SINGLE_EVENTEXECUTOR_PER_GROUP); if (pinEventExecutor != null && !pinEventExecutor) { return group.next(); } Map<EventExecutorGroup, EventExecutor> childExecutors = this.childExecutors; if (childExecutors == null) { // Use size of 4 as most people only use one extra EventExecutor. childExecutors = this.childExecutors = new IdentityHashMap<EventExecutorGroup, EventExecutor>(4); } // Pin one of the child executors once and remember it so that the same child executor // is used to fire events for the same channel. EventExecutor childExecutor = childExecutors.get(group); if (childExecutor == null) { childExecutor = group.next(); childExecutors.put(group, childExecutor); } return childExecutor; } @Override public final Channel channel() { return channel; } @Override public final ChannelPipeline addFirst(String name, ChannelHandler handler) { return addFirst(null, name, handler); } @Override public final ChannelPipeline addFirst(EventExecutorGroup group, String name, ChannelHandler handler) { final AbstractChannelHandlerContext newCtx; synchronized (this) { checkMultiplicity(handler); name = filterName(name, handler); newCtx = newContext(group, name, handler); addFirst0(newCtx); // If the registered is false it means that the channel was not registered on an eventLoop yet. // In this case we add the context to the pipeline and add a task that will call // ChannelHandler.handlerAdded(...) once the channel is registered. if (!registered) { newCtx.setAddPending(); callHandlerCallbackLater(newCtx, true); return this; } EventExecutor executor = newCtx.executor(); if (!executor.inEventLoop()) { callHandlerAddedInEventLoop(newCtx, executor); return this; } } callHandlerAdded0(newCtx); return this; } private void addFirst0(AbstractChannelHandlerContext newCtx) { AbstractChannelHandlerContext nextCtx = head.next; newCtx.prev = head; newCtx.next = nextCtx; head.next = newCtx; nextCtx.prev = newCtx; } @Override public final ChannelPipeline addLast(String name, ChannelHandler handler) { return addLast(null, name, handler); } @Override public final ChannelPipeline addLast(EventExecutorGroup group, String name, ChannelHandler handler) { final AbstractChannelHandlerContext newCtx; synchronized (this) { checkMultiplicity(handler); newCtx = newContext(group, filterName(name, handler), handler); addLast0(newCtx); // If the registered is false it means that the channel was not registered on an eventLoop yet. // In this case we add the context to the pipeline and add a task that will call // ChannelHandler.handlerAdded(...) once the channel is registered. if (!registered) { newCtx.setAddPending(); callHandlerCallbackLater(newCtx, true); return this; } EventExecutor executor = newCtx.executor(); if (!executor.inEventLoop()) { callHandlerAddedInEventLoop(newCtx, executor); return this; } } callHandlerAdded0(newCtx); return this; } private void addLast0(AbstractChannelHandlerContext newCtx) { AbstractChannelHandlerContext prev = tail.prev; newCtx.prev = prev; newCtx.next = tail; prev.next = newCtx; tail.prev = newCtx; } @Override public final ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler) { return addBefore(null, baseName, name, handler); } @Override public final ChannelPipeline addBefore( EventExecutorGroup group, String baseName, String name, ChannelHandler handler) { final AbstractChannelHandlerContext newCtx; final AbstractChannelHandlerContext ctx; synchronized (this) { checkMultiplicity(handler); name = filterName(name, handler); ctx = getContextOrDie(baseName); newCtx = newContext(group, name, handler); addBefore0(ctx, newCtx); // If the registered is false it means that the channel was not registered on an eventLoop yet. // In this case we add the context to the pipeline and add a task that will call // ChannelHandler.handlerAdded(...) once the channel is registered. if (!registered) { newCtx.setAddPending(); callHandlerCallbackLater(newCtx, true); return this; } EventExecutor executor = newCtx.executor(); if (!executor.inEventLoop()) { callHandlerAddedInEventLoop(newCtx, executor); return this; } } callHandlerAdded0(newCtx); return this; } private static void addBefore0(AbstractChannelHandlerContext ctx, AbstractChannelHandlerContext newCtx) { newCtx.prev = ctx.prev; newCtx.next = ctx; ctx.prev.next = newCtx; ctx.prev = newCtx; } private String filterName(String name, ChannelHandler handler) { if (name == null) { return generateName(handler); } checkDuplicateName(name); return name; } @Override public final ChannelPipeline addAfter(String baseName, String name, ChannelHandler handler) { return addAfter(null, baseName, name, handler); } @Override public final ChannelPipeline addAfter( EventExecutorGroup group, String baseName, String name, ChannelHandler handler) { final AbstractChannelHandlerContext newCtx; final AbstractChannelHandlerContext ctx; synchronized (this) { checkMultiplicity(handler); name = filterName(name, handler); ctx = getContextOrDie(baseName); newCtx = newContext(group, name, handler); addAfter0(ctx, newCtx); // If the registered is false it means that the channel was not registered on an eventLoop yet. // In this case we remove the context from the pipeline and add a task that will call // ChannelHandler.handlerRemoved(...) once the channel is registered. if (!registered) { newCtx.setAddPending(); callHandlerCallbackLater(newCtx, true); return this; } EventExecutor executor = newCtx.executor(); if (!executor.inEventLoop()) { callHandlerAddedInEventLoop(newCtx, executor); return this; } } callHandlerAdded0(newCtx); return this; } private static void addAfter0(AbstractChannelHandlerContext ctx, AbstractChannelHandlerContext newCtx) { newCtx.prev = ctx; newCtx.next = ctx.next; ctx.next.prev = newCtx; ctx.next = newCtx; } public final ChannelPipeline addFirst(ChannelHandler handler) { return addFirst(null, handler); } @Override public final ChannelPipeline addFirst(ChannelHandler... handlers) { return addFirst(null, handlers); } @Override public final ChannelPipeline addFirst(EventExecutorGroup executor, ChannelHandler... handlers) { ObjectUtil.checkNotNull(handlers, "handlers"); if (handlers.length == 0 || handlers[0] == null) { return this; } int size; for (size = 1; size < handlers.length; size ++) { if (handlers[size] == null) { break; } } for (int i = size - 1; i >= 0; i --) { ChannelHandler h = handlers[i]; addFirst(executor, null, h); } return this; } public final ChannelPipeline addLast(ChannelHandler handler) { return addLast(null, handler); } @Override public final ChannelPipeline addLast(ChannelHandler... handlers) { return addLast(null, handlers); } @Override public final ChannelPipeline addLast(EventExecutorGroup executor, ChannelHandler... handlers) { ObjectUtil.checkNotNull(handlers, "handlers"); for (ChannelHandler h: handlers) { if (h == null) { break; } addLast(executor, null, h); } return this; } private String generateName(ChannelHandler handler) { Map<Class<?>, String> cache = nameCaches.get(); Class<?> handlerType = handler.getClass(); String name = cache.get(handlerType); if (name == null) { name = generateName0(handlerType); cache.put(handlerType, name); } // It's not very likely for a user to put more than one handler of the same type, but make sure to avoid // any name conflicts. Note that we don't cache the names generated here. if (context0(name) != null) { String baseName = name.substring(0, name.length() - 1); // Strip the trailing '0'. for (int i = 1;; i ++) { String newName = baseName + i; if (context0(newName) == null) { name = newName; break; } } } return name; } private static String generateName0(Class<?> handlerType) { return StringUtil.simpleClassName(handlerType) + "#0"; } @Override public final ChannelPipeline remove(ChannelHandler handler) { remove(getContextOrDie(handler)); return this; } @Override public final ChannelHandler remove(String name) { return remove(getContextOrDie(name)).handler(); } @SuppressWarnings("unchecked") @Override public final <T extends ChannelHandler> T remove(Class<T> handlerType) { return (T) remove(getContextOrDie(handlerType)).handler(); } public final <T extends ChannelHandler> T removeIfExists(String name) { return removeIfExists(context(name)); } public final <T extends ChannelHandler> T removeIfExists(Class<T> handlerType) { return removeIfExists(context(handlerType)); } public final <T extends ChannelHandler> T removeIfExists(ChannelHandler handler) { return removeIfExists(context(handler)); } @SuppressWarnings("unchecked") private <T extends ChannelHandler> T removeIfExists(ChannelHandlerContext ctx) { if (ctx == null) { return null; } return (T) remove((AbstractChannelHandlerContext) ctx).handler(); } private AbstractChannelHandlerContext remove(final AbstractChannelHandlerContext ctx) { assert ctx != head && ctx != tail; synchronized (this) { atomicRemoveFromHandlerList(ctx); // If the registered is false it means that the channel was not registered on an eventloop yet. // In this case we remove the context from the pipeline and add a task that will call // ChannelHandler.handlerRemoved(...) once the channel is registered. if (!registered) { callHandlerCallbackLater(ctx, false); return ctx; } EventExecutor executor = ctx.executor(); if (!executor.inEventLoop()) { executor.execute(new Runnable() { @Override public void run() { callHandlerRemoved0(ctx); } }); return ctx; } } callHandlerRemoved0(ctx); return ctx; } /** * Method is synchronized to make the handler removal from the double linked list atomic. */ private synchronized void atomicRemoveFromHandlerList(AbstractChannelHandlerContext ctx) { AbstractChannelHandlerContext prev = ctx.prev; AbstractChannelHandlerContext next = ctx.next; prev.next = next; next.prev = prev; } @Override public final ChannelHandler removeFirst() { if (head.next == tail) { throw new NoSuchElementException(); } return remove(head.next).handler(); } @Override public final ChannelHandler removeLast() { if (head.next == tail) { throw new NoSuchElementException(); } return remove(tail.prev).handler(); } @Override public final ChannelPipeline replace(ChannelHandler oldHandler, String newName, ChannelHandler newHandler) { replace(getContextOrDie(oldHandler), newName, newHandler); return this; } @Override public final ChannelHandler replace(String oldName, String newName, ChannelHandler newHandler) { return replace(getContextOrDie(oldName), newName, newHandler); } @Override @SuppressWarnings("unchecked") public final <T extends ChannelHandler> T replace( Class<T> oldHandlerType, String newName, ChannelHandler newHandler) { return (T) replace(getContextOrDie(oldHandlerType), newName, newHandler); } private ChannelHandler replace( final AbstractChannelHandlerContext ctx, String newName, ChannelHandler newHandler) { assert ctx != head && ctx != tail; final AbstractChannelHandlerContext newCtx; synchronized (this) { checkMultiplicity(newHandler); if (newName == null) { newName = generateName(newHandler); } else { boolean sameName = ctx.name().equals(newName); if (!sameName) { checkDuplicateName(newName); } } newCtx = newContext(ctx.executor, newName, newHandler); replace0(ctx, newCtx); // If the registered is false it means that the channel was not registered on an eventloop yet. // In this case we replace the context in the pipeline // and add a task that will call ChannelHandler.handlerAdded(...) and // ChannelHandler.handlerRemoved(...) once the channel is registered. if (!registered) { callHandlerCallbackLater(newCtx, true); callHandlerCallbackLater(ctx, false); return ctx.handler(); } EventExecutor executor = ctx.executor(); if (!executor.inEventLoop()) { executor.execute(new Runnable() { @Override public void run() { // Invoke newHandler.handlerAdded() first (i.e. before oldHandler.handlerRemoved() is invoked) // because callHandlerRemoved() will trigger channelRead() or flush() on newHandler and // those event handlers must be called after handlerAdded(). callHandlerAdded0(newCtx); callHandlerRemoved0(ctx); } }); return ctx.handler(); } } // Invoke newHandler.handlerAdded() first (i.e. before oldHandler.handlerRemoved() is invoked) // because callHandlerRemoved() will trigger channelRead() or flush() on newHandler and those // event handlers must be called after handlerAdded(). callHandlerAdded0(newCtx); callHandlerRemoved0(ctx); return ctx.handler(); } private static void replace0(AbstractChannelHandlerContext oldCtx, AbstractChannelHandlerContext newCtx) { AbstractChannelHandlerContext prev = oldCtx.prev; AbstractChannelHandlerContext next = oldCtx.next; newCtx.prev = prev; newCtx.next = next; // Finish the replacement of oldCtx with newCtx in the linked list. // Note that this doesn't mean events will be sent to the new handler immediately // because we are currently at the event handler thread and no more than one handler methods can be invoked // at the same time (we ensured that in replace().) prev.next = newCtx; next.prev = newCtx; // update the reference to the replacement so forward of buffered content will work correctly oldCtx.prev = newCtx; oldCtx.next = newCtx; } private static void checkMultiplicity(ChannelHandler handler) { if (handler instanceof ChannelHandlerAdapter) { ChannelHandlerAdapter h = (ChannelHandlerAdapter) handler; if (!h.isSharable() && h.added) { throw new ChannelPipelineException( h.getClass().getName() + " is not a @Sharable handler, so can't be added or removed multiple times."); } h.added = true; } } private void callHandlerAdded0(final AbstractChannelHandlerContext ctx) { try { ctx.callHandlerAdded(); } catch (Throwable t) { boolean removed = false; try { atomicRemoveFromHandlerList(ctx); ctx.callHandlerRemoved(); removed = true; } catch (Throwable t2) { if (logger.isWarnEnabled()) { logger.warn("Failed to remove a handler: " + ctx.name(), t2); } } if (removed) { fireExceptionCaught(new ChannelPipelineException( ctx.handler().getClass().getName() + ".handlerAdded() has thrown an exception; removed.", t)); } else { fireExceptionCaught(new ChannelPipelineException( ctx.handler().getClass().getName() + ".handlerAdded() has thrown an exception; also failed to remove.", t)); } } } private void callHandlerRemoved0(final AbstractChannelHandlerContext ctx) { // Notify the complete removal. try { ctx.callHandlerRemoved(); } catch (Throwable t) { fireExceptionCaught(new ChannelPipelineException( ctx.handler().getClass().getName() + ".handlerRemoved() has thrown an exception.", t)); } } final void invokeHandlerAddedIfNeeded() { assert channel.eventLoop().inEventLoop(); if (firstRegistration) { firstRegistration = false; // We are now registered to the EventLoop. It's time to call the callbacks for the ChannelHandlers, // that were added before the registration was done. callHandlerAddedForAllHandlers(); } } @Override public final ChannelHandler first() { ChannelHandlerContext first = firstContext(); if (first == null) { return null; } return first.handler(); } @Override public final ChannelHandlerContext firstContext() { AbstractChannelHandlerContext first = head.next; if (first == tail) { return null; } return head.next; } @Override public final ChannelHandler last() { AbstractChannelHandlerContext last = tail.prev; if (last == head) { return null; } return last.handler(); } @Override public final ChannelHandlerContext lastContext() { AbstractChannelHandlerContext last = tail.prev; if (last == head) { return null; } return last; } @Override public final ChannelHandler get(String name) { ChannelHandlerContext ctx = context(name); if (ctx == null) { return null; } else { return ctx.handler(); } } @SuppressWarnings("unchecked") @Override public final <T extends ChannelHandler> T get(Class<T> handlerType) { ChannelHandlerContext ctx = context(handlerType); if (ctx == null) { return null; } else { return (T) ctx.handler(); } } @Override public final ChannelHandlerContext context(String name) { return context0(ObjectUtil.checkNotNull(name, "name")); } @Override public final ChannelHandlerContext context(ChannelHandler handler) { ObjectUtil.checkNotNull(handler, "handler"); AbstractChannelHandlerContext ctx = head.next; for (;;) { if (ctx == null) { return null; } if (ctx.handler() == handler) { return ctx; } ctx = ctx.next; } } @Override public final ChannelHandlerContext context(Class<? extends ChannelHandler> handlerType) { ObjectUtil.checkNotNull(handlerType, "handlerType"); AbstractChannelHandlerContext ctx = head.next; for (;;) { if (ctx == null) { return null; } if (handlerType.isAssignableFrom(ctx.handler().getClass())) { return ctx; } ctx = ctx.next; } } @Override public final List<String> names() { List<String> list = new ArrayList<String>(); AbstractChannelHandlerContext ctx = head.next; for (;;) { if (ctx == null) { return list; } list.add(ctx.name()); ctx = ctx.next; } } @Override public final Map<String, ChannelHandler> toMap() { Map<String, ChannelHandler> map = new LinkedHashMap<String, ChannelHandler>(); AbstractChannelHandlerContext ctx = head.next; for (;;) { if (ctx == tail) { return map; } map.put(ctx.name(), ctx.handler()); ctx = ctx.next; } } @Override public final Iterator<Map.Entry<String, ChannelHandler>> iterator() { return toMap().entrySet().iterator(); } /** * Returns the {@link String} representation of this pipeline. */ @Override public final String toString() { StringBuilder buf = new StringBuilder() .append(StringUtil.simpleClassName(this)) .append('{'); AbstractChannelHandlerContext ctx = head.next; for (;;) { if (ctx == tail) { break; } buf.append('(') .append(ctx.name()) .append(" = ") .append(ctx.handler().getClass().getName()) .append(')'); ctx = ctx.next; if (ctx == tail) { break; } buf.append(", "); } buf.append('}'); return buf.toString(); } @Override public final ChannelPipeline fireChannelRegistered() { AbstractChannelHandlerContext.invokeChannelRegistered(head); return this; } @Override public final ChannelPipeline fireChannelUnregistered() { AbstractChannelHandlerContext.invokeChannelUnregistered(head); return this; } /** * Removes all handlers from the pipeline one by one from tail (exclusive) to head (exclusive) to trigger * handlerRemoved(). * * Note that we traverse up the pipeline ({@link #destroyUp(AbstractChannelHandlerContext, boolean)}) * before traversing down ({@link #destroyDown(Thread, AbstractChannelHandlerContext, boolean)}) so that * the handlers are removed after all events are handled. * * See: https://github.com/netty/netty/issues/3156 */ private synchronized void destroy() { destroyUp(head.next, false); } private void destroyUp(AbstractChannelHandlerContext ctx, boolean inEventLoop) { final Thread currentThread = Thread.currentThread(); final AbstractChannelHandlerContext tail = this.tail; for (;;) { if (ctx == tail) { destroyDown(currentThread, tail.prev, inEventLoop); break; } final EventExecutor executor = ctx.executor(); if (!inEventLoop && !executor.inEventLoop(currentThread)) { final AbstractChannelHandlerContext finalCtx = ctx; executor.execute(new Runnable() { @Override public void run() { destroyUp(finalCtx, true); } }); break; } ctx = ctx.next; inEventLoop = false; } } private void destroyDown(Thread currentThread, AbstractChannelHandlerContext ctx, boolean inEventLoop) { // We have reached at tail; now traverse backwards. final AbstractChannelHandlerContext head = this.head; for (;;) { if (ctx == head) { break; } final EventExecutor executor = ctx.executor(); if (inEventLoop || executor.inEventLoop(currentThread)) { atomicRemoveFromHandlerList(ctx); callHandlerRemoved0(ctx); } else { final AbstractChannelHandlerContext finalCtx = ctx; executor.execute(new Runnable() { @Override public void run() { destroyDown(Thread.currentThread(), finalCtx, true); } }); break; } ctx = ctx.prev; inEventLoop = false; } } @Override public final ChannelPipeline fireChannelActive() { AbstractChannelHandlerContext.invokeChannelActive(head); return this; } @Override public final ChannelPipeline fireChannelInactive() { AbstractChannelHandlerContext.invokeChannelInactive(head); return this; } @Override public final ChannelPipeline fireExceptionCaught(Throwable cause) { AbstractChannelHandlerContext.invokeExceptionCaught(head, cause); return this; } @Override public final ChannelPipeline fireUserEventTriggered(Object event) { AbstractChannelHandlerContext.invokeUserEventTriggered(head, event); return this; } @Override public final ChannelPipeline fireChannelRead(Object msg) { AbstractChannelHandlerContext.invokeChannelRead(head, msg); return this; } @Override public final ChannelPipeline fireChannelReadComplete() { AbstractChannelHandlerContext.invokeChannelReadComplete(head); return this; } @Override public final ChannelPipeline fireChannelWritabilityChanged() { AbstractChannelHandlerContext.invokeChannelWritabilityChanged(head); return this; } @Override public final ChannelFuture bind(SocketAddress localAddress) { return tail.bind(localAddress); } @Override public final ChannelFuture connect(SocketAddress remoteAddress) { return tail.connect(remoteAddress); } @Override public final ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { return tail.connect(remoteAddress, localAddress); } @Override public final ChannelFuture disconnect() { return tail.disconnect(); } @Override public final ChannelFuture close() { return tail.close(); } @Override public final ChannelFuture deregister() { return tail.deregister(); } @Override public final ChannelPipeline flush() { tail.flush(); return this; } @Override public final ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { return tail.bind(localAddress, promise); } @Override public final ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { return tail.connect(remoteAddress, promise); } @Override public final ChannelFuture connect( SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { return tail.connect(remoteAddress, localAddress, promise); } @Override public final ChannelFuture disconnect(ChannelPromise promise) { return tail.disconnect(promise); } @Override public final ChannelFuture close(ChannelPromise promise) { return tail.close(promise); } @Override public final ChannelFuture deregister(final ChannelPromise promise) { return tail.deregister(promise); } @Override public final ChannelPipeline read() { tail.read(); return this; } @Override public final ChannelFuture write(Object msg) { return tail.write(msg); } @Override public final ChannelFuture write(Object msg, ChannelPromise promise) { return tail.write(msg, promise); } @Override public final ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { return tail.writeAndFlush(msg, promise); } @Override public final ChannelFuture writeAndFlush(Object msg) { return tail.writeAndFlush(msg); } @Override public final ChannelPromise newPromise() { return new DefaultChannelPromise(channel); } @Override public final ChannelProgressivePromise newProgressivePromise() { return new DefaultChannelProgressivePromise(channel); } @Override public final ChannelFuture newSucceededFuture() { return succeededFuture; } @Override public final ChannelFuture newFailedFuture(Throwable cause) { return new FailedChannelFuture(channel, null, cause); } @Override public final ChannelPromise voidPromise() { return voidPromise; } private void checkDuplicateName(String name) { if (context0(name) != null) { throw new IllegalArgumentException("Duplicate handler name: " + name); } } private AbstractChannelHandlerContext context0(String name) { AbstractChannelHandlerContext context = head.next; while (context != tail) { if (context.name().equals(name)) { return context; } context = context.next; } return null; } private AbstractChannelHandlerContext getContextOrDie(String name) { AbstractChannelHandlerContext ctx = (AbstractChannelHandlerContext) context(name); if (ctx == null) { throw new NoSuchElementException(name); } else { return ctx; } } private AbstractChannelHandlerContext getContextOrDie(ChannelHandler handler) { AbstractChannelHandlerContext ctx = (AbstractChannelHandlerContext) context(handler); if (ctx == null) { throw new NoSuchElementException(handler.getClass().getName()); } else { return ctx; } } private AbstractChannelHandlerContext getContextOrDie(Class<? extends ChannelHandler> handlerType) { AbstractChannelHandlerContext ctx = (AbstractChannelHandlerContext) context(handlerType); if (ctx == null) { throw new NoSuchElementException(handlerType.getName()); } else { return ctx; } } private void callHandlerAddedForAllHandlers() { final PendingHandlerCallback pendingHandlerCallbackHead; synchronized (this) { assert !registered; // This Channel itself was registered. registered = true; pendingHandlerCallbackHead = this.pendingHandlerCallbackHead; // Null out so it can be GC'ed. this.pendingHandlerCallbackHead = null; } // This must happen outside of the synchronized(...) block as otherwise handlerAdded(...) may be called while // holding the lock and so produce a deadlock if handlerAdded(...) will try to add another handler from outside // the EventLoop. PendingHandlerCallback task = pendingHandlerCallbackHead; while (task != null) { task.execute(); task = task.next; } } private void callHandlerCallbackLater(AbstractChannelHandlerContext ctx, boolean added) { assert !registered; PendingHandlerCallback task = added ? new PendingHandlerAddedTask(ctx) : new PendingHandlerRemovedTask(ctx); PendingHandlerCallback pending = pendingHandlerCallbackHead; if (pending == null) { pendingHandlerCallbackHead = task; } else { // Find the tail of the linked-list. while (pending.next != null) { pending = pending.next; } pending.next = task; } } private void callHandlerAddedInEventLoop(final AbstractChannelHandlerContext newCtx, EventExecutor executor) { newCtx.setAddPending(); executor.execute(new Runnable() { @Override public void run() { callHandlerAdded0(newCtx); } }); } /** * Called once a {@link Throwable} hit the end of the {@link ChannelPipeline} without been handled by the user * in {@link ChannelHandler#exceptionCaught(ChannelHandlerContext, Throwable)}. */ protected void onUnhandledInboundException(Throwable cause) { try { logger.warn( "An exceptionCaught() event was fired, and it reached at the tail of the pipeline. " + "It usually means the last handler in the pipeline did not handle the exception.", cause); } finally { ReferenceCountUtil.release(cause); } } /** * Called once the {@link ChannelInboundHandler#channelActive(ChannelHandlerContext)}event hit * the end of the {@link ChannelPipeline}. */ protected void onUnhandledInboundChannelActive() { } /** * Called once the {@link ChannelInboundHandler#channelInactive(ChannelHandlerContext)} event hit * the end of the {@link ChannelPipeline}. */ protected void onUnhandledInboundChannelInactive() { } /** * Called once a message hit the end of the {@link ChannelPipeline} without been handled by the user * in {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)}. This method is responsible * to call {@link ReferenceCountUtil#release(Object)} on the given msg at some point. */ protected void onUnhandledInboundMessage(Object msg) { try { logger.debug( "Discarded inbound message {} that reached at the tail of the pipeline. " + "Please check your pipeline configuration.", msg); } finally { ReferenceCountUtil.release(msg); } } /** * Called once a message hit the end of the {@link ChannelPipeline} without been handled by the user * in {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)}. This method is responsible * to call {@link ReferenceCountUtil#release(Object)} on the given msg at some point. */ protected void onUnhandledInboundMessage(ChannelHandlerContext ctx, Object msg) { onUnhandledInboundMessage(msg); if (logger.isDebugEnabled()) { logger.debug("Discarded message pipeline : {}. Channel : {}.", ctx.pipeline().names(), ctx.channel()); } } /** * Called once the {@link ChannelInboundHandler#channelReadComplete(ChannelHandlerContext)} event hit * the end of the {@link ChannelPipeline}. */ protected void onUnhandledInboundChannelReadComplete() { } /** * Called once an user event hit the end of the {@link ChannelPipeline} without been handled by the user * in {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)}. This method is responsible * to call {@link ReferenceCountUtil#release(Object)} on the given event at some point. */ protected void onUnhandledInboundUserEventTriggered(Object evt) { // This may not be a configuration error and so don't log anything. // The event may be superfluous for the current pipeline configuration. ReferenceCountUtil.release(evt); } /** * Called once the {@link ChannelInboundHandler#channelWritabilityChanged(ChannelHandlerContext)} event hit * the end of the {@link ChannelPipeline}. */ protected void onUnhandledChannelWritabilityChanged() { } @UnstableApi protected void incrementPendingOutboundBytes(long size) { ChannelOutboundBuffer buffer = channel.unsafe().outboundBuffer(); if (buffer != null) { buffer.incrementPendingOutboundBytes(size); } } @UnstableApi protected void decrementPendingOutboundBytes(long size) { ChannelOutboundBuffer buffer = channel.unsafe().outboundBuffer(); if (buffer != null) { buffer.decrementPendingOutboundBytes(size); } } // A special catch-all handler that handles both bytes and messages. final class TailContext extends AbstractChannelHandlerContext implements ChannelInboundHandler { TailContext(DefaultChannelPipeline pipeline) { super(pipeline, null, TAIL_NAME, TailContext.class); setAddComplete(); } @Override public ChannelHandler handler() { return this; } @Override public void channelRegistered(ChannelHandlerContext ctx) { } @Override public void channelUnregistered(ChannelHandlerContext ctx) { } @Override public void channelActive(ChannelHandlerContext ctx) { onUnhandledInboundChannelActive(); } @Override public void channelInactive(ChannelHandlerContext ctx) { onUnhandledInboundChannelInactive(); } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) { onUnhandledChannelWritabilityChanged(); } @Override public void handlerAdded(ChannelHandlerContext ctx) { } @Override public void handlerRemoved(ChannelHandlerContext ctx) { } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { onUnhandledInboundUserEventTriggered(evt); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { onUnhandledInboundException(cause); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { onUnhandledInboundMessage(ctx, msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { onUnhandledInboundChannelReadComplete(); } } final class HeadContext extends AbstractChannelHandlerContext implements ChannelOutboundHandler, ChannelInboundHandler { private final Unsafe unsafe; HeadContext(DefaultChannelPipeline pipeline) { super(pipeline, null, HEAD_NAME, HeadContext.class); unsafe = pipeline.channel().unsafe(); setAddComplete(); } @Override public ChannelHandler handler() { return this; } @Override public void handlerAdded(ChannelHandlerContext ctx) { // NOOP } @Override public void handlerRemoved(ChannelHandlerContext ctx) { // NOOP } @Override public void bind( ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) { unsafe.bind(localAddress, promise); } @Override public void connect( ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { unsafe.connect(remoteAddress, localAddress, promise); } @Override public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) { unsafe.disconnect(promise); } @Override public void close(ChannelHandlerContext ctx, ChannelPromise promise) { unsafe.close(promise); } @Override public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) { unsafe.deregister(promise); } @Override public void read(ChannelHandlerContext ctx) { unsafe.beginRead(); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { unsafe.write(msg, promise); } @Override public void flush(ChannelHandlerContext ctx) { unsafe.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { ctx.fireExceptionCaught(cause); } @Override public void channelRegistered(ChannelHandlerContext ctx) { invokeHandlerAddedIfNeeded(); ctx.fireChannelRegistered(); } @Override public void channelUnregistered(ChannelHandlerContext ctx) { ctx.fireChannelUnregistered(); // Remove all handlers sequentially if channel is closed and unregistered. if (!channel.isOpen()) { destroy(); } } @Override public void channelActive(ChannelHandlerContext ctx) { ctx.fireChannelActive(); readIfIsAutoRead(); } @Override public void channelInactive(ChannelHandlerContext ctx) { ctx.fireChannelInactive(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ctx.fireChannelRead(msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.fireChannelReadComplete(); readIfIsAutoRead(); } private void readIfIsAutoRead() { if (channel.config().isAutoRead()) { channel.read(); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { ctx.fireUserEventTriggered(evt); } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) { ctx.fireChannelWritabilityChanged(); } } private abstract static class PendingHandlerCallback implements Runnable { final AbstractChannelHandlerContext ctx; PendingHandlerCallback next; PendingHandlerCallback(AbstractChannelHandlerContext ctx) { this.ctx = ctx; } abstract void execute(); } private final class PendingHandlerAddedTask extends PendingHandlerCallback { PendingHandlerAddedTask(AbstractChannelHandlerContext ctx) { super(ctx); } @Override public void run() { callHandlerAdded0(ctx); } @Override void execute() { EventExecutor executor = ctx.executor(); if (executor.inEventLoop()) { callHandlerAdded0(ctx); } else { try { executor.execute(this); } catch (RejectedExecutionException e) { if (logger.isWarnEnabled()) { logger.warn( "Can't invoke handlerAdded() as the EventExecutor {} rejected it, removing handler {}.", executor, ctx.name(), e); } atomicRemoveFromHandlerList(ctx); ctx.setRemoved(); } } } } private final class PendingHandlerRemovedTask extends PendingHandlerCallback { PendingHandlerRemovedTask(AbstractChannelHandlerContext ctx) { super(ctx); } @Override public void run() { callHandlerRemoved0(ctx); } @Override void execute() { EventExecutor executor = ctx.executor(); if (executor.inEventLoop()) { callHandlerRemoved0(ctx); } else { try { executor.execute(this); } catch (RejectedExecutionException e) { if (logger.isWarnEnabled()) { logger.warn( "Can't invoke handlerRemoved() as the EventExecutor {} rejected it," + " removing handler {}.", executor, ctx.name(), e); } // remove0(...) was call before so just call AbstractChannelHandlerContext.setRemoved(). ctx.setRemoved(); } } } } }
netty/netty
transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java
2,114
package cn.hutool.core.thread; import cn.hutool.core.util.RuntimeUtil; import java.lang.Thread.UncaughtExceptionHandler; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; /** * 线程池工具 * * @author luxiaolei */ public class ThreadUtil { /** * 新建一个线程池,默认的策略如下: * <pre> * 1. 初始线程数为corePoolSize指定的大小 * 2. 没有最大线程数限制 * 3. 默认使用LinkedBlockingQueue,默认队列大小为1024 * </pre> * * @param corePoolSize 同时执行的线程数大小 * @return ExecutorService */ public static ExecutorService newExecutor(int corePoolSize) { ExecutorBuilder builder = ExecutorBuilder.create(); if (corePoolSize > 0) { builder.setCorePoolSize(corePoolSize); } return builder.build(); } /** * 获得一个新的线程池,默认的策略如下: * <pre> * 1. 初始线程数为 0 * 2. 最大线程数为Integer.MAX_VALUE * 3. 使用SynchronousQueue * 4. 任务直接提交给线程而不保持它们 * </pre> * * @return ExecutorService */ public static ExecutorService newExecutor() { return ExecutorBuilder.create().useSynchronousQueue().build(); } /** * 获得一个新的线程池,只有单个线程,策略如下: * <pre> * 1. 初始线程数为 1 * 2. 最大线程数为 1 * 3. 默认使用LinkedBlockingQueue,默认队列大小为1024 * 4. 同时只允许一个线程工作,剩余放入队列等待,等待数超过1024报错 * </pre> * * @return ExecutorService */ public static ExecutorService newSingleExecutor() { return ExecutorBuilder.create()// .setCorePoolSize(1)// .setMaxPoolSize(1)// .setKeepAliveTime(0)// .buildFinalizable(); } /** * 获得一个新的线程池<br> * 如果maximumPoolSize &gt;= corePoolSize,在没有新任务加入的情况下,多出的线程将最多保留60s * * @param corePoolSize 初始线程池大小 * @param maximumPoolSize 最大线程池大小 * @return {@link ThreadPoolExecutor} */ public static ThreadPoolExecutor newExecutor(int corePoolSize, int maximumPoolSize) { return ExecutorBuilder.create() .setCorePoolSize(corePoolSize) .setMaxPoolSize(maximumPoolSize) .build(); } /** * 获得一个新的线程池,并指定最大任务队列大小<br> * 如果maximumPoolSize &gt;= corePoolSize,在没有新任务加入的情况下,多出的线程将最多保留60s * * @param corePoolSize 初始线程池大小 * @param maximumPoolSize 最大线程池大小 * @param maximumQueueSize 最大任务队列大小 * @return {@link ThreadPoolExecutor} * @since 5.4.1 */ public static ExecutorService newExecutor(int corePoolSize, int maximumPoolSize, int maximumQueueSize) { return ExecutorBuilder.create() .setCorePoolSize(corePoolSize) .setMaxPoolSize(maximumPoolSize) .setWorkQueue(new LinkedBlockingQueue<>(maximumQueueSize)) .build(); } /** * 获得一个新的线程池<br> * 传入阻塞系数,线程池的大小计算公式为:CPU可用核心数 / (1 - 阻塞因子)<br> * Blocking Coefficient(阻塞系数) = 阻塞时间/(阻塞时间+使用CPU的时间)<br> * 计算密集型任务的阻塞系数为0,而IO密集型任务的阻塞系数则接近于1。 * <p> * see: <a href="http://blog.csdn.net/partner4java/article/details/9417663">http://blog.csdn.net/partner4java/article/details/9417663</a> * * @param blockingCoefficient 阻塞系数,阻塞因子介于0~1之间的数,阻塞因子越大,线程池中的线程数越多。 * @return {@link ThreadPoolExecutor} * @since 3.0.6 */ public static ThreadPoolExecutor newExecutorByBlockingCoefficient(float blockingCoefficient) { if (blockingCoefficient >= 1 || blockingCoefficient < 0) { throw new IllegalArgumentException("[blockingCoefficient] must between 0 and 1, or equals 0."); } // 最佳的线程数 = CPU可用核心数 / (1 - 阻塞系数) int poolSize = (int) (RuntimeUtil.getProcessorCount() / (1 - blockingCoefficient)); return ExecutorBuilder.create().setCorePoolSize(poolSize).setMaxPoolSize(poolSize).setKeepAliveTime(0L).build(); } /** * 获取一个新的线程池,默认的策略如下<br> * <pre> * 1. 核心线程数与最大线程数为nThreads指定的大小 * 2. 默认使用LinkedBlockingQueue,默认队列大小为1024 * 3. 如果isBlocked为{@code true},当执行拒绝策略的时候会处于阻塞状态,直到能添加到队列中或者被{@link Thread#interrupt()}中断 * </pre> * * @param nThreads 线程池大小 * @param threadNamePrefix 线程名称前缀 * @param isBlocked 是否使用{@link BlockPolicy}策略 * @return ExecutorService * @author luozongle * @since 5.8.0 */ public static ExecutorService newFixedExecutor(int nThreads, String threadNamePrefix, boolean isBlocked) { return newFixedExecutor(nThreads, 1024, threadNamePrefix, isBlocked); } /** * 获取一个新的线程池,默认的策略如下<br> * <pre> * 1. 核心线程数与最大线程数为nThreads指定的大小 * 2. 默认使用LinkedBlockingQueue * 3. 如果isBlocked为{@code true},当执行拒绝策略的时候会处于阻塞状态,直到能添加到队列中或者被{@link Thread#interrupt()}中断 * </pre> * * @param nThreads 线程池大小 * @param maximumQueueSize 队列大小 * @param threadNamePrefix 线程名称前缀 * @param isBlocked 是否使用{@link BlockPolicy}策略 * @return ExecutorService * @author luozongle * @since 5.8.0 */ public static ExecutorService newFixedExecutor(int nThreads, int maximumQueueSize, String threadNamePrefix, boolean isBlocked) { return newFixedExecutor(nThreads, maximumQueueSize, threadNamePrefix, (isBlocked ? RejectPolicy.BLOCK : RejectPolicy.ABORT).getValue()); } /** * 获得一个新的线程池,默认策略如下<br> * <pre> * 1. 核心线程数与最大线程数为nThreads指定的大小 * 2. 默认使用LinkedBlockingQueue * </pre> * * @param nThreads 线程池大小 * @param maximumQueueSize 队列大小 * @param threadNamePrefix 线程名称前缀 * @param handler 拒绝策略 * @return ExecutorService * @author luozongle * @since 5.8.0 */ public static ExecutorService newFixedExecutor(int nThreads, int maximumQueueSize, String threadNamePrefix, RejectedExecutionHandler handler) { return ExecutorBuilder.create() .setCorePoolSize(nThreads).setMaxPoolSize(nThreads) .setWorkQueue(new LinkedBlockingQueue<>(maximumQueueSize)) .setThreadFactory(createThreadFactory(threadNamePrefix)) .setHandler(handler) .build(); } /** * 直接在公共线程池中执行线程 * * @param runnable 可运行对象 */ public static void execute(Runnable runnable) { GlobalThreadPool.execute(runnable); } /** * 执行异步方法 * * @param runnable 需要执行的方法体 * @param isDaemon 是否守护线程。守护线程会在主线程结束后自动结束 * @return 执行的方法体 */ public static Runnable execAsync(Runnable runnable, boolean isDaemon) { Thread thread = new Thread(runnable); thread.setDaemon(isDaemon); thread.start(); return runnable; } /** * 执行有返回值的异步方法<br> * Future代表一个异步执行的操作,通过get()方法可以获得操作的结果,如果异步操作还没有完成,则,get()会使当前线程阻塞 * * @param <T> 回调对象类型 * @param task {@link Callable} * @return Future */ public static <T> Future<T> execAsync(Callable<T> task) { return GlobalThreadPool.submit(task); } /** * 执行有返回值的异步方法<br> * Future代表一个异步执行的操作,通过get()方法可以获得操作的结果,如果异步操作还没有完成,则,get()会使当前线程阻塞 * * @param runnable 可运行对象 * @return {@link Future} * @since 3.0.5 */ public static Future<?> execAsync(Runnable runnable) { return GlobalThreadPool.submit(runnable); } /** * 新建一个CompletionService,调用其submit方法可以异步执行多个任务,最后调用take方法按照完成的顺序获得其结果。<br> * 若未完成,则会阻塞 * * @param <T> 回调对象类型 * @return CompletionService */ public static <T> CompletionService<T> newCompletionService() { return new ExecutorCompletionService<>(GlobalThreadPool.getExecutor()); } /** * 新建一个CompletionService,调用其submit方法可以异步执行多个任务,最后调用take方法按照完成的顺序获得其结果。<br> * 若未完成,则会阻塞 * * @param <T> 回调对象类型 * @param executor 执行器 {@link ExecutorService} * @return CompletionService */ public static <T> CompletionService<T> newCompletionService(ExecutorService executor) { return new ExecutorCompletionService<>(executor); } /** * 新建一个CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。 * * @param threadCount 线程数量 * @return CountDownLatch */ public static CountDownLatch newCountDownLatch(int threadCount) { return new CountDownLatch(threadCount); } /** * 创建新线程,非守护线程,正常优先级,线程组与当前线程的线程组一致 * * @param runnable {@link Runnable} * @param name 线程名 * @return {@link Thread} * @since 3.1.2 */ public static Thread newThread(Runnable runnable, String name) { final Thread t = newThread(runnable, name, false); if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } /** * 创建新线程 * * @param runnable {@link Runnable} * @param name 线程名 * @param isDaemon 是否守护线程 * @return {@link Thread} * @since 4.1.2 */ public static Thread newThread(Runnable runnable, String name, boolean isDaemon) { final Thread t = new Thread(null, runnable, name); t.setDaemon(isDaemon); return t; } /** * 挂起当前线程 * * @param timeout 挂起的时长 * @param timeUnit 时长单位 * @return 被中断返回false,否则true */ public static boolean sleep(Number timeout, TimeUnit timeUnit) { try { timeUnit.sleep(timeout.longValue()); } catch (InterruptedException e) { return false; } return true; } /** * 挂起当前线程 * * @param millis 挂起的毫秒数 * @return 被中断返回false,否则true */ public static boolean sleep(Number millis) { if (millis == null) { return true; } return sleep(millis.longValue()); } /** * 挂起当前线程 * * @param millis 挂起的毫秒数 * @return 被中断返回false,否则true * @since 5.3.2 */ public static boolean sleep(long millis) { if (millis > 0) { try { Thread.sleep(millis); } catch (InterruptedException e) { return false; } } return true; } /** * 考虑{@link Thread#sleep(long)}方法有可能时间不足给定毫秒数,此方法保证sleep时间不小于给定的毫秒数 * * @param millis 给定的sleep时间 * @return 被中断返回false,否则true * @see ThreadUtil#sleep(Number) */ public static boolean safeSleep(Number millis) { if (millis == null) { return true; } return safeSleep(millis.longValue()); } /** * 考虑{@link Thread#sleep(long)}方法有可能时间不足给定毫秒数,此方法保证sleep时间不小于给定的毫秒数 * * @param millis 给定的sleep时间 * @return 被中断返回false,否则true * @see ThreadUtil#sleep(Number) * @since 5.3.2 */ public static boolean safeSleep(long millis) { long done = 0; long before; // done表示实际花费的时间,确保实际花费时间大于应该sleep的时间 while (done < millis) { before = System.nanoTime(); if (!sleep(millis - done)) { return false; } // done始终为正 done += (System.nanoTime() - before) / 1_000_000; } return true; } /** * @return 获得堆栈列表 */ public static StackTraceElement[] getStackTrace() { return Thread.currentThread().getStackTrace(); } /** * 获得堆栈项 * * @param i 第几个堆栈项 * @return 堆栈项 */ public static StackTraceElement getStackTraceElement(int i) { StackTraceElement[] stackTrace = getStackTrace(); if (i < 0) { i += stackTrace.length; } return stackTrace[i]; } /** * 创建本地线程对象 * * @param <T> 持有对象类型 * @param isInheritable 是否为子线程提供从父线程那里继承的值 * @return 本地线程 */ public static <T> ThreadLocal<T> createThreadLocal(boolean isInheritable) { if (isInheritable) { return new InheritableThreadLocal<>(); } else { return new ThreadLocal<>(); } } /** * 创建本地线程对象 * * @param <T> 持有对象类型 * @param supplier 初始化线程对象函数 * @return 本地线程 * @see ThreadLocal#withInitial(Supplier) * @since 5.6.7 */ public static <T> ThreadLocal<T> createThreadLocal(Supplier<? extends T> supplier) { return ThreadLocal.withInitial(supplier); } /** * 创建ThreadFactoryBuilder * * @return ThreadFactoryBuilder * @see ThreadFactoryBuilder#build() * @since 4.1.13 */ public static ThreadFactoryBuilder createThreadFactoryBuilder() { return ThreadFactoryBuilder.create(); } /** * 创建自定义线程名称前缀的{@link ThreadFactory} * * @param threadNamePrefix 线程名称前缀 * @return {@link ThreadFactory} * @see ThreadFactoryBuilder#build() * @since 5.8.0 */ public static ThreadFactory createThreadFactory(String threadNamePrefix) { return ThreadFactoryBuilder.create().setNamePrefix(threadNamePrefix).build(); } /** * 结束线程,调用此方法后,线程将抛出 {@link InterruptedException}异常 * * @param thread 线程 * @param isJoin 是否等待结束 */ public static void interrupt(Thread thread, boolean isJoin) { if (null != thread && false == thread.isInterrupted()) { thread.interrupt(); if (isJoin) { waitForDie(thread); } } } /** * 等待当前线程结束. 调用 {@link Thread#join()} 并忽略 {@link InterruptedException} */ public static void waitForDie() { waitForDie(Thread.currentThread()); } /** * 等待线程结束. 调用 {@link Thread#join()} 并忽略 {@link InterruptedException} * * @param thread 线程 */ public static void waitForDie(Thread thread) { if (null == thread) { return; } boolean dead = false; do { try { thread.join(); dead = true; } catch (InterruptedException e) { // ignore } } while (false == dead); } /** * 获取JVM中与当前线程同组的所有线程<br> * * @return 线程对象数组 */ public static Thread[] getThreads() { return getThreads(Thread.currentThread().getThreadGroup().getParent()); } /** * 获取JVM中与当前线程同组的所有线程<br> * 使用数组二次拷贝方式,防止在线程列表获取过程中线程终止<br> * from Voovan * * @param group 线程组 * @return 线程对象数组 */ public static Thread[] getThreads(ThreadGroup group) { final Thread[] slackList = new Thread[group.activeCount() * 2]; final int actualSize = group.enumerate(slackList); final Thread[] result = new Thread[actualSize]; System.arraycopy(slackList, 0, result, 0, actualSize); return result; } /** * 获取进程的主线程<br> * from Voovan * * @return 进程的主线程 */ public static Thread getMainThread() { for (Thread thread : getThreads()) { if (thread.getId() == 1) { return thread; } } return null; } /** * 获取当前线程的线程组 * * @return 线程组 * @since 3.1.2 */ public static ThreadGroup currentThreadGroup() { final SecurityManager s = System.getSecurityManager(); return (null != s) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); } /** * 创建线程工厂 * * @param prefix 线程名前缀 * @param isDaemon 是否守护线程 * @return {@link ThreadFactory} * @since 4.0.0 */ public static ThreadFactory newNamedThreadFactory(String prefix, boolean isDaemon) { return new NamedThreadFactory(prefix, isDaemon); } /** * 创建线程工厂 * * @param prefix 线程名前缀 * @param threadGroup 线程组,可以为null * @param isDaemon 是否守护线程 * @return {@link ThreadFactory} * @since 4.0.0 */ public static ThreadFactory newNamedThreadFactory(String prefix, ThreadGroup threadGroup, boolean isDaemon) { return new NamedThreadFactory(prefix, threadGroup, isDaemon); } /** * 创建线程工厂 * * @param prefix 线程名前缀 * @param threadGroup 线程组,可以为null * @param isDaemon 是否守护线程 * @param handler 未捕获异常处理 * @return {@link ThreadFactory} * @since 4.0.0 */ public static ThreadFactory newNamedThreadFactory(String prefix, ThreadGroup threadGroup, boolean isDaemon, UncaughtExceptionHandler handler) { return new NamedThreadFactory(prefix, threadGroup, isDaemon, handler); } /** * 阻塞当前线程,保证在main方法中执行不被退出 * * @param obj 对象所在线程 * @since 4.5.6 */ @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") public static void sync(Object obj) { synchronized (obj) { try { obj.wait(); } catch (InterruptedException e) { // ignore } } } /** * 并发测试<br> * 此方法用于测试多线程下执行某些逻辑的并发性能<br> * 调用此方法会导致当前线程阻塞。<br> * 结束后可调用{@link ConcurrencyTester#getInterval()} 方法获取执行时间 * * @param threadSize 并发线程数 * @param runnable 执行的逻辑实现 * @return {@link ConcurrencyTester} * @since 4.5.8 */ @SuppressWarnings("resource") public static ConcurrencyTester concurrencyTest(int threadSize, Runnable runnable) { return (new ConcurrencyTester(threadSize)).test(runnable); } /** * 创建{@link ScheduledThreadPoolExecutor} * * @param corePoolSize 初始线程池大小 * @return {@link ScheduledThreadPoolExecutor} * @since 5.5.8 */ public static ScheduledThreadPoolExecutor createScheduledExecutor(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } /** * 开始执行一个定时任务,执行方式分fixedRate模式和fixedDelay模式。<br> * 注意:此方法的延迟和周期的单位均为毫秒。 * * <ul> * <li>fixedRate 模式:以固定的频率执行。每period的时刻检查,如果上个任务完成,启动下个任务,否则等待上个任务结束后立即启动。</li> * <li>fixedDelay模式:以固定的延时执行。上次任务结束后等待period再执行下个任务。</li> * </ul> * * @param executor 定时任务线程池,{@code null}新建一个默认线程池 * @param command 需要定时执行的逻辑 * @param initialDelay 初始延迟,单位毫秒 * @param period 执行周期,单位毫秒 * @param fixedRateOrFixedDelay {@code true}表示fixedRate模式,{@code false}表示fixedDelay模式 * @return {@link ScheduledThreadPoolExecutor} * @since 5.5.8 */ public static ScheduledThreadPoolExecutor schedule(ScheduledThreadPoolExecutor executor, Runnable command, long initialDelay, long period, boolean fixedRateOrFixedDelay) { return schedule(executor, command, initialDelay, period, TimeUnit.MILLISECONDS, fixedRateOrFixedDelay); } /** * 开始执行一个定时任务,执行方式分fixedRate模式和fixedDelay模式。 * * <ul> * <li>fixedRate 模式:以固定的频率执行。每period的时刻检查,如果上个任务完成,启动下个任务,否则等待上个任务结束后立即启动。</li> * <li>fixedDelay模式:以固定的延时执行。上次任务结束后等待period再执行下个任务。</li> * </ul> * * @param executor 定时任务线程池,{@code null}新建一个默认线程池 * @param command 需要定时执行的逻辑 * @param initialDelay 初始延迟 * @param period 执行周期 * @param timeUnit 时间单位 * @param fixedRateOrFixedDelay {@code true}表示fixedRate模式,{@code false}表示fixedDelay模式 * @return {@link ScheduledThreadPoolExecutor} * @since 5.6.5 */ public static ScheduledThreadPoolExecutor schedule(ScheduledThreadPoolExecutor executor, Runnable command, long initialDelay, long period, TimeUnit timeUnit, boolean fixedRateOrFixedDelay) { if (null == executor) { executor = createScheduledExecutor(2); } if (fixedRateOrFixedDelay) { executor.scheduleAtFixedRate(command, initialDelay, period, timeUnit); } else { executor.scheduleWithFixedDelay(command, initialDelay, period, timeUnit); } return executor; } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/thread/ThreadUtil.java
2,115
/* Copyright 2018 The TensorFlow Authors. 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 org.tensorflow.op.core; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.tensorflow.Graph; import org.tensorflow.Operand; import org.tensorflow.Output; import org.tensorflow.op.Op; import org.tensorflow.op.Operands; import org.tensorflow.op.Scope; import org.tensorflow.op.annotation.Operator; /** * Adds operations to compute the partial derivatives of sum of {@code y}s w.r.t {@code x}s, * i.e., {@code d(y_1 + y_2 + ...)/dx_1, d(y_1 + y_2 + ...)/dx_2...} * <p> * If {@code Options.dx()} values are set, they are as the initial symbolic partial derivatives of some loss * function {@code L} w.r.t. {@code y}. {@code Options.dx()} must have the size of {@code y}. * <p> * If {@code Options.dx()} is not set, the implementation will use dx of {@code OnesLike} for all * shapes in {@code y}. * <p> * The partial derivatives are returned in output {@code dy}, with the size of {@code x}. * <p> * Example of usage: * <pre>{@code * Gradients gradients = Gradients.create(scope, Arrays.asList(loss), Arrays.asList(w, b)); * * Constant<Float> alpha = ops.constant(1.0f, Float.class); * ApplyGradientDescent.create(scope, w, alpha, gradients.<Float>dy(0)); * ApplyGradientDescent.create(scope, b, alpha, gradients.<Float>dy(1)); * }</pre> */ @Operator public class Gradients implements Op, Iterable<Operand<?>> { /** * Optional attributes for {@link Gradients} */ public static class Options { /** * @param dx partial derivatives of some loss function {@code L} w.r.t. {@code y} * @return this option builder */ public Options dx(Iterable<? extends Operand<?>> dx) { this.dx = dx; return this; } private Iterable<? extends Operand<?>> dx; private Options() { } } /** * Adds gradients computation ops to the graph according to scope. * * @param scope current graph scope * @param y outputs of the function to derive * @param x inputs of the function for which partial derivatives are computed * @param options carries optional attributes values * @return a new instance of {@code Gradients} * @throws IllegalArgumentException if execution environment is not a graph */ public static Gradients create( Scope scope, Iterable<? extends Operand<?>> y, Iterable<? extends Operand<?>> x, Options... options) { if (!(scope.env() instanceof Graph)) { throw new IllegalArgumentException( "Gradients can be computed only in a graph execution environment"); } Graph graph = (Graph) scope.env(); Output<?>[] dx = null; if (options != null) { for (Options opts : options) { if (opts.dx != null) { dx = Operands.asOutputs(opts.dx); } } } Output<?>[] dy = graph.addGradients( scope.makeOpName("Gradients"), Operands.asOutputs(y), Operands.asOutputs(x), dx); return new Gradients(Arrays.asList(dy)); } /** * Adds gradients computation ops to the graph according to scope. * * <p>This is a simplified version of {@link #create(Scope, Iterable, Iterable, Options...)} where * {@code y} is a single output. * * @param scope current graph scope * @param y output of the function to derive * @param x inputs of the function for which partial derivatives are computed * @param options carries optional attributes values * @return a new instance of {@code Gradients} * @throws IllegalArgumentException if execution environment is not a graph */ @SuppressWarnings({"unchecked", "rawtypes"}) public static Gradients create( Scope scope, Operand<?> y, Iterable<? extends Operand<?>> x, Options... options) { return create(scope, (Iterable) Arrays.asList(y), x, options); } /** * @param dx partial derivatives of some loss function {@code L} w.r.t. {@code y} * @return builder to add more options to this operation */ public static Options dx(Iterable<? extends Operand<?>> dx) { return new Options().dx(dx); } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public Iterator<Operand<?>> iterator() { return (Iterator) dy.iterator(); } /** * Partial derivatives of {@code y}s w.r.t. {@code x}s, with the size of {@code x} */ public List<Output<?>> dy() { return dy; } /** * Returns a symbolic handle to one of the gradient operation output * * <p>Warning: Does not check that the type of the tensor matches T. It is recommended to call * this method with an explicit type parameter rather than letting it be inferred, e.g. {@code * gradients.<Float>dy(0)} * * @param <T> The expected element type of the tensors produced by this output. * @param index The index of the output among the gradients added by this operation */ @SuppressWarnings("unchecked") public <T> Output<T> dy(int index) { return (Output<T>) dy.get(index); } private List<Output<?>> dy; private Gradients(List<Output<?>> dy) { this.dy = dy; } }
tensorflow/tensorflow
tensorflow/java/src/main/java/org/tensorflow/op/core/Gradients.java
2,116
package edu.stanford.nlp.io; import edu.stanford.nlp.util.*; import edu.stanford.nlp.util.logging.Redwood; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.net.InetAddress; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.function.Consumer; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * Helper Class for various I/O related things. * * @author Kayur Patel * @author Teg Grenager * @author Christopher Manning */ public class IOUtils { private static final int SLURP_BUFFER_SIZE = 16384; public static final String eolChar = System.lineSeparator(); // todo: Inline public static final String defaultEncoding = "utf-8"; /** A logger for this class */ private static final Redwood.RedwoodChannels logger = Redwood.channels(IOUtils.class); // A class of static methods private IOUtils() { } /** * Write object to a file with the specified name. The file is silently gzipped if the filename ends with .gz. * * @param o Object to be written to file * @param filename Name of the temp file * @throws IOException If can't write file. * @return File containing the object */ public static File writeObjectToFile(Object o, String filename) throws IOException { return writeObjectToFile(o, new File(filename)); } /** * Write an object to a specified File. The file is silently gzipped if the filename ends with .gz. * * @param o Object to be written to file * @param file The temp File * @throws IOException If File cannot be written * @return File containing the object */ public static File writeObjectToFile(Object o, File file) throws IOException { return writeObjectToFile(o, file, false); } /** * Write an object to a specified File. The file is silently gzipped if the filename ends with .gz. * * @param o Object to be written to file * @param file The temp File * @param append If true, append to this file instead of overwriting it * @throws IOException If File cannot be written * @return File containing the object */ public static File writeObjectToFile(Object o, File file, boolean append) throws IOException { // file.createNewFile(); // cdm may 2005: does nothing needed OutputStream os = new FileOutputStream(file, append); if (file.getName().endsWith(".gz")) { os = new GZIPOutputStream(os); } os = new BufferedOutputStream(os); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(o); oos.close(); return file; } /** * Write object to a file with the specified name. * * @param o Object to be written to file * @param filename Name of the temp file * @return File containing the object, or null if an exception was caught */ public static File writeObjectToFileNoExceptions(Object o, String filename) { File file = null; ObjectOutputStream oos = null; try { file = new File(filename); // file.createNewFile(); // cdm may 2005: does nothing needed oos = new ObjectOutputStream(new BufferedOutputStream( new GZIPOutputStream(new FileOutputStream(file)))); oos.writeObject(o); oos.close(); } catch (Exception e) { logger.err(throwableToStackTrace(e)); } finally { closeIgnoringExceptions(oos); } return file; } /** * Write object to temp file which is destroyed when the program exits. * * @param o Object to be written to file * @param filename Name of the temp file * @throws IOException If file cannot be written * @return File containing the object */ public static File writeObjectToTempFile(Object o, String filename) throws IOException { File file = File.createTempFile(filename, ".tmp"); file.deleteOnExit(); writeObjectToFile(o, file); return file; } /** * Write object to a temp file and ignore exceptions. * * @param o Object to be written to file * @param filename Name of the temp file * @return File containing the object */ public static File writeObjectToTempFileNoExceptions(Object o, String filename) { try { return writeObjectToTempFile(o, filename); } catch (Exception e) { logger.error("Error writing object to file " + filename); logger.err(throwableToStackTrace(e)); return null; } } private static OutputStream getBufferedOutputStream(String path) throws IOException { OutputStream os = new BufferedOutputStream(new FileOutputStream(path)); if (path.endsWith(".gz")) { os = new GZIPOutputStream(os); } return os; } //++ todo [cdm, Aug 2012]: Do we need the below methods? They're kind of weird in unnecessarily bypassing using a Writer. /** * Writes a string to a file. * * @param contents The string to write * @param path The file path * @param encoding The encoding to encode in * @throws IOException In case of failure */ public static void writeStringToFile(String contents, String path, String encoding) throws IOException { OutputStream writer = getBufferedOutputStream(path); writer.write(contents.getBytes(encoding)); writer.close(); } /** * Writes a string to a file, squashing exceptions * * @param contents The string to write * @param path The file path * @param encoding The encoding to encode in * */ public static void writeStringToFileNoExceptions(String contents, String path, String encoding) { OutputStream writer = null; try{ if (path.endsWith(".gz")) { writer = new GZIPOutputStream(new FileOutputStream(path)); } else { writer = new BufferedOutputStream(new FileOutputStream(path)); } writer.write(contents.getBytes(encoding)); } catch (Exception e) { logger.err(throwableToStackTrace(e)); } finally { closeIgnoringExceptions(writer); } } /** * Writes a string to a temporary file. * * @param contents The string to write * @param path The file path * @param encoding The encoding to encode in * @throws IOException In case of failure * @return The File written to */ public static File writeStringToTempFile(String contents, String path, String encoding) throws IOException { OutputStream writer; File tmp = File.createTempFile(path,".tmp"); if (path.endsWith(".gz")) { writer = new GZIPOutputStream(new FileOutputStream(tmp)); } else { writer = new BufferedOutputStream(new FileOutputStream(tmp)); } writer.write(contents.getBytes(encoding)); writer.close(); return tmp; } /** * Writes a string to a temporary file, as UTF-8 * * @param contents The string to write * @param path The file path * @throws IOException In case of failure */ public static void writeStringToTempFile(String contents, String path) throws IOException { writeStringToTempFile(contents, path, "UTF-8"); } /** * Writes a string to a temporary file, squashing exceptions * * @param contents The string to write * @param path The file path * @param encoding The encoding to encode in * @return The File that was written to */ public static File writeStringToTempFileNoExceptions(String contents, String path, String encoding) { OutputStream writer = null; File tmp = null; try { tmp = File.createTempFile(path,".tmp"); if (path.endsWith(".gz")) { writer = new GZIPOutputStream(new FileOutputStream(tmp)); } else { writer = new BufferedOutputStream(new FileOutputStream(tmp)); } writer.write(contents.getBytes(encoding)); } catch (Exception e) { logger.err(throwableToStackTrace(e)); } finally { closeIgnoringExceptions(writer); } return tmp; } /** * Writes a string to a temporary file with UTF-8 encoding, squashing exceptions * * @param contents The string to write * @param path The file path */ public static void writeStringToTempFileNoExceptions(String contents, String path) { writeStringToTempFileNoExceptions(contents, path, "UTF-8"); } //-- todo [cdm, Aug 2012]: Do we need the below methods? They're kind of weird in unnecessarily bypassing using a Writer. // todo [cdm, Sep 2013]: Can we remove this next method and its friends? (Weird in silently gzipping, overlaps other functionality.) /** * Read an object from a stored file. It is silently ungzipped, regardless of name. * * @param file The file pointing to the object to be retrieved * @throws IOException If file cannot be read * @throws ClassNotFoundException If reading serialized object fails * @return The object read from the file. */ public static <T> T readObjectFromFile(File file) throws IOException, ClassNotFoundException { try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream( new GZIPInputStream(new FileInputStream(file))))) { Object o = ois.readObject(); return ErasureUtils.uncheckedCast(o); } catch (java.util.zip.ZipException e) { try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream( new FileInputStream(file)))) { Object o = ois.readObject(); return ErasureUtils.uncheckedCast(o); } } } public static DataInputStream getDataInputStream(String filenameUrlOrClassPath) throws IOException { return new DataInputStream(getInputStreamFromURLOrClasspathOrFileSystem(filenameUrlOrClassPath)); } public static DataOutputStream getDataOutputStream(String filename) throws IOException { return new DataOutputStream(getBufferedOutputStream((filename))); } /** * Read an object from a stored file. The file can be anything obtained * via a URL, the filesystem, or the classpath (eg in a jar file). * * @param filename The file pointing to the object to be retrieved * @throws IOException If file cannot be read * @throws ClassNotFoundException If reading serialized object fails * @return The object read from the file. */ public static <T> T readObjectFromURLOrClasspathOrFileSystem(String filename) throws IOException, ClassNotFoundException { try (ObjectInputStream ois = new ObjectInputStream(getInputStreamFromURLOrClasspathOrFileSystem(filename))) { Object o = ois.readObject(); return ErasureUtils.uncheckedCast(o); } } public static <T> T readObjectAnnouncingTimingFromURLOrClasspathOrFileSystem(Redwood.RedwoodChannels log, String msg, String path) { T obj; Timing timing = new Timing(); try { obj = IOUtils.readObjectFromURLOrClasspathOrFileSystem(path); log.info(msg + ' ' + path + " ... done [" + timing.toSecondsString() + " sec]."); } catch (IOException | ClassNotFoundException e) { log.info(msg + ' ' + path + " ... failed! [" + timing.toSecondsString() + " sec]."); throw new RuntimeIOException(e); } return obj; } public static <T> T readObjectFromObjectStream(ObjectInputStream ois) throws IOException, ClassNotFoundException { Object o = ois.readObject(); return ErasureUtils.uncheckedCast(o); } /** * Read an object from a stored file. * * @param filename The filename of the object to be retrieved * @throws IOException If file cannot be read * @throws ClassNotFoundException If reading serialized object fails * @return The object read from the file. */ public static <T> T readObjectFromFile(String filename) throws IOException, ClassNotFoundException { return ErasureUtils.uncheckedCast(readObjectFromFile(new File(filename))); } /** * Read an object from a stored file without throwing exceptions. * * @param file The file pointing to the object to be retrieved * @return The object read from the file, or null if an exception occurred. */ public static <T> T readObjectFromFileNoExceptions(File file) { Object o = null; try { ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream( new GZIPInputStream(new FileInputStream(file)))); o = ois.readObject(); ois.close(); } catch (IOException | ClassNotFoundException e) { logger.err(throwableToStackTrace(e)); } return ErasureUtils.uncheckedCast(o); } public static int lineCount(String textFileOrUrl) throws IOException { try (BufferedReader r = readerFromString(textFileOrUrl)) { int numLines = 0; while (r.readLine() != null) { numLines++; } return numLines; } } public static ObjectOutputStream writeStreamFromString(String serializePath) throws IOException { ObjectOutputStream oos; if (serializePath.endsWith(".gz")) { oos = new ObjectOutputStream(new BufferedOutputStream( new GZIPOutputStream(new FileOutputStream(serializePath)))); } else { oos = new ObjectOutputStream(new BufferedOutputStream( new FileOutputStream(serializePath))); } return oos; } /** * Returns an ObjectInputStream reading from any of a URL, a CLASSPATH resource, or a file. * The CLASSPATH takes priority over the file system. * This stream is buffered and, if necessary, gunzipped. * * @param filenameOrUrl The String specifying the URL/resource/file to load * @return An ObjectInputStream for loading a resource * @throws RuntimeIOException On any IO error * @throws NullPointerException Input parameter is null */ public static ObjectInputStream readStreamFromString(String filenameOrUrl) throws IOException { InputStream is = getInputStreamFromURLOrClasspathOrFileSystem(filenameOrUrl); return new ObjectInputStream(is); } /** * Locates a file in the CLASSPATH if it exists. Checks both the * System classloader and the IOUtils classloader, since we had * separate users asking for both of those changes. */ private static InputStream findStreamInClassLoader(String name) { InputStream is = ClassLoader.getSystemResourceAsStream(name); if (is != null) return is; // windows File.separator is \, but getting resources only works with / is = ClassLoader.getSystemResourceAsStream(name.replaceAll("\\\\", "/")); if (is != null) return is; // Classpath doesn't like double slashes (e.g., /home/user//foo.txt) is = ClassLoader.getSystemResourceAsStream(name.replaceAll("\\\\", "/").replaceAll("/+", "/")); if (is != null) return is; is = IOUtils.class.getClassLoader().getResourceAsStream(name); if (is != null) return is; is = IOUtils.class.getClassLoader().getResourceAsStream(name.replaceAll("\\\\", "/")); if (is != null) return is; is = IOUtils.class.getClassLoader().getResourceAsStream(name.replaceAll("\\\\", "/").replaceAll("/+", "/")); // at this point we've tried everything return is; } /** * Locates this file either in the CLASSPATH or in the file system. The CLASSPATH takes priority. * Note that this method uses the ClassLoader methods, so that classpath resources must be specified as * absolute resource paths without a leading "/". * * @param name The file or resource name * @throws FileNotFoundException If the file does not exist * @return The InputStream of name, or null if not found */ private static InputStream findStreamInClasspathOrFileSystem(String name) throws FileNotFoundException { // ms 10-04-2010: // - even though this may look like a regular file, it may be a path inside a jar in the CLASSPATH // - check for this first. This takes precedence over the file system. InputStream is = findStreamInClassLoader(name); // if not found in the CLASSPATH, load from the file system if (is == null) { is = new FileInputStream(name); } return is; } /** * Check if this path exists either in the classpath or on the filesystem. * * @param name The file or resource name. * @return true if a call to {@link IOUtils#getBufferedReaderFromClasspathOrFileSystem(String)} would return a valid stream. */ public static boolean existsInClasspathOrFileSystem(String name) { InputStream is = findStreamInClassLoader(name); return is != null || new File(name).exists(); } /** * Locates this file either using the given URL, or in the CLASSPATH, or in the file system * The CLASSPATH takes priority over the file system! * This stream is buffered and gunzipped (if necessary). * * @param textFileOrUrl The String specifying the URL/resource/file to load * @return An InputStream for loading a resource * @throws IOException On any IO error * @throws NullPointerException Input parameter is null */ public static InputStream getInputStreamFromURLOrClasspathOrFileSystem(String textFileOrUrl) throws IOException, NullPointerException { InputStream in; if (textFileOrUrl == null) { throw new NullPointerException("Attempt to open file with null name"); } else if (textFileOrUrl.matches("https?://.*")) { URL u = new URL(textFileOrUrl); URLConnection uc = u.openConnection(); in = uc.getInputStream(); } else { try { in = findStreamInClasspathOrFileSystem(textFileOrUrl); } catch (FileNotFoundException e) { try { // Maybe this happens to be some other format of URL? URL u = new URL(textFileOrUrl); URLConnection uc = u.openConnection(); in = uc.getInputStream(); } catch (IOException e2) { // Don't make the original exception a cause, since it is usually bogus throw new IOException("Unable to open \"" + textFileOrUrl + "\" as " + "class path, filename or URL"); // , e2); } } } // If it is a GZIP stream then ungzip it if (textFileOrUrl.endsWith(".gz")) { try { in = new GZIPInputStream(in); } catch (Exception e) { throw new RuntimeIOException("Resource or file looks like a gzip file, but is not: " + textFileOrUrl, e); } } // buffer this stream. even gzip streams benefit from buffering, // such as for the shift reduce parser [cdm 2016: I think this is only because default buffer is small; see below] in = new BufferedInputStream(in); return in; } // todo [cdm 2015]: I think GZIPInputStream has its own buffer and so we don't need to buffer in that case. // todo: Though it's default size is 512 bytes so need to make 8K in constructor. Or else buffering outside gzip is faster // todo: final InputStream is = new GZIPInputStream( new FileInputStream( file ), 65536 ); /** * Quietly opens a File. If the file ends with a ".gz" extension, * automatically opens a GZIPInputStream to wrap the constructed * FileInputStream. */ public static InputStream inputStreamFromFile(File file) throws RuntimeIOException { InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); if (file.getName().endsWith(".gz")) { is = new GZIPInputStream(is); } return is; } catch (IOException e) { IOUtils.closeIgnoringExceptions(is); throw new RuntimeIOException(e); } } /** * Open a BufferedReader to a File. If the file's getName() ends in .gz, * it is interpreted as a gzipped file (and uncompressed). The file is then * interpreted as a utf-8 text file. * * @param file What to read from * @return The BufferedReader * @throws RuntimeIOException If there is an I/O problem */ public static BufferedReader readerFromFile(File file) { InputStream is = inputStreamFromFile(file); return new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); } // todo [cdm 2014]: get rid of this method, using other methods. This will change the semantics to null meaning UTF-8, but that seems better in 2015. /** * Open a BufferedReader to a File. If the file's getName() ends in .gz, * it is interpreted as a gzipped file (and uncompressed). The file is then * turned into a BufferedReader with the given encoding. * If the encoding passed in is null, then the system default encoding is used. * * @param file What to read from * @param encoding What charset to use. A null String is interpreted as platform default encoding * @return The BufferedReader * @throws RuntimeIOException If there is an I/O problem */ public static BufferedReader readerFromFile(File file, String encoding) { InputStream is = null; try { is = inputStreamFromFile(file); if (encoding == null) { return new BufferedReader(new InputStreamReader(is)); } else { return new BufferedReader(new InputStreamReader(is, encoding)); } } catch (IOException ioe) { IOUtils.closeIgnoringExceptions(is); throw new RuntimeIOException(ioe); } } /** * Open a BufferedReader on stdin. Use the user's default encoding. * * @return The BufferedReader */ public static BufferedReader readerFromStdin() { return new BufferedReader(new InputStreamReader(System.in)); } /** * Open a BufferedReader on stdin. Use the specified character encoding. * * @param encoding CharSet encoding. Maybe be null, in which case the * platform default encoding is used * @return The BufferedReader * @throws IOException If there is an I/O problem */ public static BufferedReader readerFromStdin(String encoding) throws IOException { if (encoding == null) { return new BufferedReader(new InputStreamReader(System.in)); } return new BufferedReader(new InputStreamReader(System.in, encoding)); } // TODO [cdm 2015]: Should we rename these methods. Sort of misleading: They really read files, resources, etc. specified by a String /** * Open a BufferedReader to a file, class path entry or URL specified by a String name. * If the String starts with https?://, then it is first tried as a URL. It * is next tried as a resource on the CLASSPATH, and then it is tried * as a local file. Finally, it is then tried again in case it is some network-available * file accessible by URL. If the String ends in .gz, it * is interpreted as a gzipped file (and uncompressed). The file is then * interpreted as a utf-8 text file. * Note that this method uses the ClassLoader methods, so that classpath resources must be specified as * absolute resource paths without a leading "/". * * @param textFileOrUrl What to read from * @return The BufferedReader * @throws IOException If there is an I/O problem */ public static BufferedReader readerFromString(String textFileOrUrl) throws IOException { return new BufferedReader(new InputStreamReader( getInputStreamFromURLOrClasspathOrFileSystem(textFileOrUrl), StandardCharsets.UTF_8)); } /** * Open a BufferedReader to a file or URL specified by a String name. If the * String starts with https?://, then it is first tried as a URL, otherwise it * is next tried as a resource on the CLASSPATH, and then finally it is tried * as a local file or other network-available file . If the String ends in .gz, it * is interpreted as a gzipped file (and uncompressed), else it is interpreted as * a regular text file in the given encoding. * If the encoding passed in is null, then the system default encoding is used. * * @param textFileOrUrl What to read from * @param encoding CharSet encoding. Maybe be null, in which case the * platform default encoding is used * @return The BufferedReader * @throws IOException If there is an I/O problem */ public static BufferedReader readerFromString(String textFileOrUrl, String encoding) throws IOException { InputStream is = getInputStreamFromURLOrClasspathOrFileSystem(textFileOrUrl); if (encoding == null) { return new BufferedReader(new InputStreamReader(is)); } return new BufferedReader(new InputStreamReader(is, encoding)); } /** * Returns an Iterable of the lines in the file. * * The file reader will be closed when the iterator is exhausted. IO errors * will throw an (unchecked) RuntimeIOException * * @param path The file whose lines are to be read. * @return An Iterable containing the lines from the file. */ public static Iterable<String> readLines(String path) { return readLines(path, null); } /** * Returns an Iterable of the lines in the file. * * The file reader will be closed when the iterator is exhausted. IO errors * will throw an (unchecked) RuntimeIOException * * @param path The file whose lines are to be read. * @param encoding The encoding to use when reading lines. * @return An Iterable containing the lines from the file. */ public static Iterable<String> readLines(String path, String encoding) { return new GetLinesIterable(path, null, encoding); } /** * Returns an Iterable of the lines in the file. * * The file reader will be closed when the iterator is exhausted. * * @param file The file whose lines are to be read. * @return An Iterable containing the lines from the file. */ public static Iterable<String> readLines(final File file) { return readLines(file, null, null); } /** * Returns an Iterable of the lines in the file. * * The file reader will be closed when the iterator is exhausted. * * @param file The file whose lines are to be read. * @param fileInputStreamWrapper * The class to wrap the InputStream with, e.g. GZIPInputStream. Note * that the class must have a constructor that accepts an * InputStream. * @return An Iterable containing the lines from the file. */ public static Iterable<String> readLines(final File file, final Class<? extends InputStream> fileInputStreamWrapper) { return readLines(file, fileInputStreamWrapper, null); } /** * Returns an Iterable of the lines in the file, wrapping the generated * FileInputStream with an instance of the supplied class. IO errors will * throw an (unchecked) RuntimeIOException * * @param file The file whose lines are to be read. * @param fileInputStreamWrapper * The class to wrap the InputStream with, e.g. GZIPInputStream. Note * that the class must have a constructor that accepts an * InputStream. * @param encoding The encoding to use when reading lines. * @return An Iterable containing the lines from the file. */ public static Iterable<String> readLines(final File file, final Class<? extends InputStream> fileInputStreamWrapper, final String encoding) { return new GetLinesIterable(file, fileInputStreamWrapper, encoding); } static class GetLinesIterable implements Iterable<String> { final File file; final String path; final Class<? extends InputStream> fileInputStreamWrapper; final String encoding; // TODO: better programming style would be to make this two // separate classes, but we don't expect to make more versions of // this class anyway GetLinesIterable(final File file, final Class<? extends InputStream> fileInputStreamWrapper, final String encoding) { this.file = file; this.path = null; this.fileInputStreamWrapper = fileInputStreamWrapper; this.encoding = encoding; } GetLinesIterable(final String path, final Class<? extends InputStream> fileInputStreamWrapper, final String encoding) { this.file = null; this.path = path; this.fileInputStreamWrapper = fileInputStreamWrapper; this.encoding = encoding; } private InputStream getStream() throws IOException { if (file != null) { return inputStreamFromFile(file); } else if (path != null) { return getInputStreamFromURLOrClasspathOrFileSystem(path); } else { throw new AssertionError("No known path to read"); } } @Override public Iterator<String> iterator() { return new Iterator<String>() { protected final BufferedReader reader = this.getReader(); protected String line = this.getLine(); private boolean readerOpen = true; @Override public boolean hasNext() { return this.line != null; } @Override public String next() { String nextLine = this.line; if (nextLine == null) { throw new NoSuchElementException(); } line = getLine(); return nextLine; } protected String getLine() { try { String result = this.reader.readLine(); if (result == null) { readerOpen = false; this.reader.close(); } return result; } catch (IOException e) { throw new RuntimeIOException(e); } } protected BufferedReader getReader() { try { InputStream stream = getStream(); if (fileInputStreamWrapper != null) { stream = fileInputStreamWrapper.getConstructor(InputStream.class).newInstance(stream); } if (encoding == null) { return new BufferedReader(new InputStreamReader(stream)); } else { return new BufferedReader(new InputStreamReader(stream, encoding)); } } catch (Exception e) { throw new RuntimeIOException(e); } } @Override public void remove() { throw new UnsupportedOperationException(); } // todo [cdm 2018]: Probably should remove this but in current implementation reader is internal and can only close by getting to eof. protected void finalize() throws Throwable { super.finalize(); if (readerOpen) { logger.warn("Forgot to close FileIterable -- closing from finalize()"); reader.close(); } } }; } } // end static class GetLinesIterable /** * Given a reader, returns the lines from the reader as an Iterable. * * @param r input reader * @param includeEol whether to keep eol-characters in the returned strings * @return iterable of lines (as strings) */ public static Iterable<String> getLineIterable( Reader r, boolean includeEol) { if (includeEol) { return new EolPreservingLineReaderIterable(r); } else { return new LineReaderIterable( (r instanceof BufferedReader)? (BufferedReader) r:new BufferedReader(r) ); } } public static Iterable<String> getLineIterable( Reader r, int bufferSize, boolean includeEol) { if (includeEol) { return new EolPreservingLineReaderIterable(r, bufferSize); } else { return new LineReaderIterable( (r instanceof BufferedReader)? (BufferedReader) r:new BufferedReader(r, bufferSize) ); } } /** * Line iterator that uses BufferedReader.readLine() * EOL-characters are automatically discarded and not included in the strings returns */ private static final class LineReaderIterable implements Iterable<String> { private final BufferedReader reader; private LineReaderIterable( BufferedReader reader ) { this.reader = reader; } @Override public Iterator<String> iterator() { return new Iterator<String>() { private String next = getNext(); private String getNext() { try { return reader.readLine(); } catch (IOException ex) { throw new RuntimeIOException(ex); } } @Override public boolean hasNext() { return this.next != null; } @Override public String next() { String nextLine = this.next; if (nextLine == null) { throw new NoSuchElementException(); } next = getNext(); return nextLine; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } } /** * Line iterator that preserves the eol-character exactly as read from reader. * Line endings are: \r\n,\n,\r * Lines returns by this iterator will include the eol-characters **/ private static final class EolPreservingLineReaderIterable implements Iterable<String> { private final Reader reader; private final int bufferSize; private EolPreservingLineReaderIterable( Reader reader ) { this(reader, SLURP_BUFFER_SIZE); } private EolPreservingLineReaderIterable( Reader reader, int bufferSize ) { this.reader = reader; this.bufferSize = bufferSize; } @Override public Iterator<String> iterator() { return new Iterator<String>() { private String next; private boolean done = false; private final StringBuilder sb = new StringBuilder(80); private final char[] charBuffer = new char[bufferSize]; private int charBufferPos = -1; private int charsInBuffer = 0; boolean lastWasLF = false; private String getNext() { try { while (true) { if (charBufferPos < 0) { charsInBuffer = reader.read(charBuffer); if (charsInBuffer < 0) { // No more!!! if (sb.length() > 0) { String line = sb.toString(); // resets the buffer sb.setLength(0); return line; } else { return null; } } charBufferPos = 0; } boolean eolReached = copyUntilEol(); if (eolReached) { // eol reached String line = sb.toString(); // resets the buffer sb.setLength(0); return line; } } } catch (IOException ex) { throw new RuntimeIOException(ex); } } private boolean copyUntilEol() { for (int i = charBufferPos; i < charsInBuffer; i++) { if (charBuffer[i] == '\n') { // line end // copy into our string builder sb.append(charBuffer, charBufferPos, i - charBufferPos + 1); // advance character buffer pos charBufferPos = i+1; lastWasLF = false; return true; // end of line reached } else if (lastWasLF) { // not a '\n' here - still need to terminate line (but don't include current character) if (i > charBufferPos) { sb.append(charBuffer, charBufferPos, i - charBufferPos); // advance character buffer pos charBufferPos = i; lastWasLF = false; return true; // end of line reached } } lastWasLF = (charBuffer[i] == '\r'); } sb.append(charBuffer, charBufferPos, charsInBuffer - charBufferPos); // reset character buffer pos charBufferPos = -1; return false; } @Override public boolean hasNext() { if (done) return false; if (next == null) { next = getNext(); } if (next == null) { done = true; } return !done; } @Override public String next() { if (!hasNext()) { throw new NoSuchElementException(); } String res = next; next = null; return res; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } // end iterator() } // end static class EolPreservingLineReaderIterable /** * Provides an implementation of closing a file for use in a finally block so * you can correctly close a file without even more exception handling stuff. * From a suggestion in a talk by Josh Bloch. Calling close() will flush(). * * @param c The IO resource to close (e.g., a Stream/Reader) */ public static void closeIgnoringExceptions(Closeable c) { if (c != null) { try { c.close(); } catch (IOException ioe) { // ignore } } } /** * Iterate over all the files in the directory, recursively. * * @param dir The root directory. * @return All files within the directory. */ public static Iterable<File> iterFilesRecursive(final File dir) { return iterFilesRecursive(dir, (Pattern) null); } /** * Iterate over all the files in the directory, recursively. * * @param dir The root directory. * @param ext A string that must be at the end of all files (e.g. ".txt") * @return All files within the directory ending in the given extension. */ public static Iterable<File> iterFilesRecursive(final File dir, final String ext) { return iterFilesRecursive(dir, Pattern.compile(Pattern.quote(ext) + "$")); } /** * Iterate over all the files in the directory, recursively. * * @param dir The root directory. * @param pattern A regular expression that the file path must match. This uses * Matcher.find(), so use ^ and $ to specify endpoints. * @return All files within the directory. */ public static Iterable<File> iterFilesRecursive(final File dir, final Pattern pattern) { return new Iterable<File>() { public Iterator<File> iterator() { return new AbstractIterator<File>() { private final Queue<File> files = new LinkedList<>(Collections .singleton(dir)); private File file = this.findNext(); @Override public boolean hasNext() { return this.file != null; } @Override public File next() { File result = this.file; if (result == null) { throw new NoSuchElementException(); } this.file = this.findNext(); return result; } private File findNext() { File next = null; while (!this.files.isEmpty() && next == null) { next = this.files.remove(); if (next.isDirectory()) { files.addAll(Arrays.asList(next.listFiles())); next = null; } else if (pattern != null) { if (!pattern.matcher(next.getPath()).find()) { next = null; } } } return next; } }; } }; } /** * Returns all the text in the given File as a single String. * If the file's name ends in .gz, it is assumed to be gzipped and is silently uncompressed. */ public static String slurpFile(File file) throws IOException { return slurpFile(file, null); } /** * Returns all the text in the given File as a single String. * If the file's name ends in .gz, it is assumed to be gzipped and is silently uncompressed. * * @param file The file to read from * @param encoding The character encoding to assume. This may be null, and * the platform default character encoding is used. */ public static String slurpFile(File file, String encoding) throws IOException { return IOUtils.slurpReader(IOUtils.encodedInputStreamReader( inputStreamFromFile(file), encoding)); } /** * Returns all the text in the given File as a single String. */ public static String slurpGZippedFile(String filename) throws IOException { Reader r = encodedInputStreamReader(new GZIPInputStream(new FileInputStream( filename)), null); return IOUtils.slurpReader(r); } /** * Returns all the text in the given File as a single String. */ public static String slurpGZippedFile(File file) throws IOException { Reader r = encodedInputStreamReader(new GZIPInputStream(new FileInputStream( file)), null); return IOUtils.slurpReader(r); } /** * Returns all the text in the given file with the given encoding. * The string may be empty, if the file is empty. */ public static String slurpFile(String filename, String encoding) throws IOException { Reader r = readerFromString(filename, encoding); return IOUtils.slurpReader(r); } /** * Returns all the text in the given file with the given * encoding. If the file cannot be read (non-existent, etc.), then * the method throws an unchecked RuntimeIOException. If the caller * is willing to tolerate missing files, they should catch that * exception. */ public static String slurpFileNoExceptions(String filename, String encoding) { try { return slurpFile(filename, encoding); } catch (IOException e) { throw new RuntimeIOException("slurpFile IO problem", e); } } /** * Returns all the text in the given file * * @return The text in the file. */ public static String slurpFile(String filename) throws IOException { return slurpFile(filename, defaultEncoding); } /** * Returns all the text at the given URL. */ public static String slurpURLNoExceptions(URL u, String encoding) { try { return IOUtils.slurpURL(u, encoding); } catch (Exception e) { logger.err(throwableToStackTrace(e)); return null; } } /** * Returns all the text at the given URL. */ public static String slurpURL(URL u, String encoding) throws IOException { String lineSeparator = System.lineSeparator(); URLConnection uc = u.openConnection(); uc.setReadTimeout(30000); InputStream is; try { is = uc.getInputStream(); } catch (SocketTimeoutException e) { logger.error("Socket time out; returning empty string."); logger.err(throwableToStackTrace(e)); return ""; } try (BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding))) { StringBuilder buff = new StringBuilder(SLURP_BUFFER_SIZE); // make biggish for (String temp; (temp = br.readLine()) != null; ) { buff.append(temp); buff.append(lineSeparator); } return buff.toString(); } } public static String getUrlEncoding(URLConnection connection) { String contentType = connection.getContentType(); String[] values = contentType.split(";"); String charset = defaultEncoding; // might or might not be right.... for (String value : values) { value = value.trim(); if (value.toLowerCase(Locale.ENGLISH).startsWith("charset=")) { charset = value.substring("charset=".length()); } } return charset; } /** * Returns all the text at the given URL. */ public static String slurpURL(URL u) throws IOException { URLConnection uc = u.openConnection(); String encoding = getUrlEncoding(uc); InputStream is = uc.getInputStream(); try (BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding))) { StringBuilder buff = new StringBuilder(SLURP_BUFFER_SIZE); // make biggish String lineSeparator = System.lineSeparator(); for (String temp; (temp = br.readLine()) != null; ) { buff.append(temp); buff.append(lineSeparator); } return buff.toString(); } } /** * Returns all the text at the given URL. */ public static String slurpURLNoExceptions(URL u) { try { return slurpURL(u); } catch (Exception e) { logger.err(throwableToStackTrace(e)); return null; } } /** * Returns all the text at the given URL. */ public static String slurpURL(String path) throws Exception { return slurpURL(new URL(path)); } /** * Returns all the text at the given URL. If the file cannot be read * (non-existent, etc.), then and only then the method returns * {@code null}. */ public static String slurpURLNoExceptions(String path) { try { return slurpURL(path); } catch (Exception e) { logger.err(throwableToStackTrace(e)); return null; } } /** * Returns all the text in the given file with the given * encoding. If the file cannot be read (non-existent, etc.), then * the method throws an unchecked RuntimeIOException. If the caller * is willing to tolerate missing files, they should catch that * exception. */ public static String slurpFileNoExceptions(File file) { try { return IOUtils.slurpReader(encodedInputStreamReader(new FileInputStream(file), null)); } catch (IOException e) { throw new RuntimeIOException(e); } } /** * Returns all the text in the given file with the given * encoding. If the file cannot be read (non-existent, etc.), then * the method throws an unchecked RuntimeIOException. If the caller * is willing to tolerate missing files, they should catch that * exception. */ public static String slurpFileNoExceptions(String filename) { try { return slurpFile(filename); } catch (IOException e) { throw new RuntimeIOException(e); } } /** * Returns all the text from the given Reader. * Closes the Reader when done. * * @return The text in the file. */ public static String slurpReader(Reader reader) { StringBuilder buff = new StringBuilder(); try (BufferedReader r = new BufferedReader(reader)) { char[] chars = new char[SLURP_BUFFER_SIZE]; while (true) { int amountRead = r.read(chars, 0, SLURP_BUFFER_SIZE); if (amountRead < 0) { break; } buff.append(chars, 0, amountRead); } } catch (Exception e) { throw new RuntimeIOException("slurpReader IO problem", e); } return buff.toString(); } /** * Read the contents of an input stream, decoding it according to the given character encoding. * @param input The input stream to read from * @return The String representation of that input stream */ public static String slurpInputStream(InputStream input, String encoding) throws IOException { return slurpReader(encodedInputStreamReader(input, encoding)); } /** * Send all bytes from the input stream to the output stream. * * @param input The input bytes. * @param output Where the bytes should be written. */ public static void writeStreamToStream(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[4096]; while (true) { int len = input.read(buffer); if (len == -1) { break; } output.write(buffer, 0, len); } } /** * Read in a CSV formatted file with a header row. * * @param path - path to CSV file * @param quoteChar - character for enclosing strings, defaults to " * @param escapeChar - character for escaping quotes appearing in quoted strings; defaults to " (i.e. "" is used for " inside quotes, consistent with Excel) * @return a list of maps representing the rows of the csv. The maps' keys are the header strings and their values are the row contents */ public static List<Map<String,String>> readCSVWithHeader(String path, char quoteChar, char escapeChar) { String[] labels = null; List<Map<String,String>> rows = Generics.newArrayList(); for (String line : IOUtils.readLines(path)) { // logger.info("Splitting "+line); if (labels == null) { labels = StringUtils.splitOnCharWithQuoting(line,',','"',escapeChar); } else { String[] cells = StringUtils.splitOnCharWithQuoting(line,',',quoteChar,escapeChar); assert(cells.length == labels.length); Map<String,String> cellMap = Generics.newHashMap(); for (int i=0; i<labels.length; i++) cellMap.put(labels[i],cells[i]); rows.add(cellMap); } } return rows; } public static List<Map<String,String>> readCSVWithHeader(String path) { return readCSVWithHeader(path, '"', '"'); } /** * Read a CSV file character by character. Allows for multi-line CSV files (in quotes), but * is less flexible and likely slower than readCSVWithHeader() * @param csvContents The char[] array corresponding to the contents of the file * @param numColumns The number of columns in the file (for verification, primarily) * @return A list of lines in the file */ public static LinkedList<String[]> readCSVStrictly(char[] csvContents, int numColumns){ //--Variables StringBuilder[] buffer = new StringBuilder[numColumns]; buffer[0] = new StringBuilder(); LinkedList<String[]> lines = new LinkedList<>(); //--State boolean inQuotes = false; boolean nextIsEscaped = false; int columnI = 0; //--Read for(int offset=0; offset<csvContents.length; offset++){ if(nextIsEscaped){ buffer[columnI].append(csvContents[offset]); nextIsEscaped = false; } else { switch(csvContents[offset]){ case '"': //(case: quotes) inQuotes = !inQuotes; break; case ',': //(case: field separator) if(inQuotes){ buffer[columnI].append(','); } else { columnI += 1; if(columnI >= numColumns){ throw new IllegalArgumentException("Too many columns: "+columnI+"/"+numColumns+" (offset: " + offset + ")"); } buffer[columnI] = new StringBuilder(); } break; case '\n': //(case: newline) if(inQuotes){ buffer[columnI].append('\n'); } else { //((error checks)) if(columnI != numColumns-1){ throw new IllegalArgumentException("Too few columns: "+columnI+"/"+numColumns+" (offset: " + offset + ")"); } //((create line)) String[] rtn = new String[buffer.length]; for(int i=0; i<buffer.length; i++){ rtn[i] = buffer[i].toString(); } lines.add(rtn); //((update state)) columnI = 0; buffer[columnI] = new StringBuilder(); } break; case '\\': nextIsEscaped = true; break; default: buffer[columnI].append(csvContents[offset]); } } } //--Return return lines; } public static LinkedList<String[]> readCSVStrictly(String filename, int numColumns) throws IOException { return readCSVStrictly(slurpFile(filename).toCharArray(), numColumns); } /** * Get a input file stream (automatically gunzip depending on file extension) * @param filename Name of file to open * @return Input stream that can be used to read from the file * @throws IOException if there are exceptions opening the file */ public static InputStream getFileInputStream(String filename) throws IOException { InputStream in = new FileInputStream(filename); if (filename.endsWith(".gz")) { in = new GZIPInputStream(in); } return in; } /** * Get a output file stream (automatically gzip depending on file extension) * @param filename Name of file to open * @return Output stream that can be used to write to the file * @throws IOException if there are exceptions opening the file */ public static OutputStream getFileOutputStream(String filename) throws IOException { OutputStream out = new FileOutputStream(filename); if (filename.endsWith(".gz")) { out = new GZIPOutputStream(out); } return out; } public static OutputStream getFileOutputStream(String filename, boolean append) throws IOException { OutputStream out = new FileOutputStream(filename, append); if (filename.endsWith(".gz")) { out = new GZIPOutputStream(out); } return out; } /** @deprecated Just call readerFromString(filename) */ @Deprecated public static BufferedReader getBufferedFileReader(String filename) throws IOException { return readerFromString(filename, defaultEncoding); } /** @deprecated Just call readerFromString(filename) */ @Deprecated public static BufferedReader getBufferedReaderFromClasspathOrFileSystem(String filename) throws IOException { return readerFromString(filename, defaultEncoding); } public static PrintWriter getPrintWriter(File textFile) throws IOException { return getPrintWriter(textFile, null); } public static PrintWriter getPrintWriter(File textFile, String encoding) throws IOException { File f = textFile.getAbsoluteFile(); if (encoding == null) { encoding = defaultEncoding; } return new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), encoding)), true); } public static PrintWriter getPrintWriter(String filename) throws IOException { return getPrintWriter(filename, defaultEncoding); } public static PrintWriter getPrintWriterIgnoringExceptions(String filename) { try { return getPrintWriter(filename, defaultEncoding); } catch (IOException ioe) { return null; } } public static PrintWriter getPrintWriterOrDie(String filename) { try { return getPrintWriter(filename, defaultEncoding); } catch (IOException ioe) { throw new RuntimeIOException(ioe); } } public static PrintWriter getPrintWriter(String filename, String encoding) throws IOException { OutputStream out = getFileOutputStream(filename); if (encoding == null) { encoding = defaultEncoding; } return new PrintWriter(new BufferedWriter(new OutputStreamWriter(out, encoding)), true); } private static final Pattern tab = Pattern.compile("\t"); /** * Read column as set * @param infile filename * @param field index of field to read * @return a set of the entries in column field * @throws IOException If I/O error */ public static Set<String> readColumnSet(String infile, int field) throws IOException { BufferedReader br = IOUtils.readerFromString(infile); Set<String> set = Generics.newHashSet(); for (String line; (line = br.readLine()) != null; ) { line = line.trim(); if (line.length() > 0) { if (field < 0) { set.add(line); } else { String[] fields = tab.split(line); if (field < fields.length) { set.add(fields[field]); } } } } br.close(); return set; } public static <C> List<C> readObjectFromColumns(Class objClass, String filename, String[] fieldNames, String delimiter) throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException { Pattern delimiterPattern = Pattern.compile(delimiter); List<C> list = new ArrayList<>(); BufferedReader br = IOUtils.readerFromString(filename); for (String line; (line = br.readLine()) != null; ) { line = line.trim(); if (line.length() > 0) { C item = StringUtils.columnStringToObject(objClass, line, delimiterPattern, fieldNames); list.add(item); } } br.close(); return list; } public static Map<String,String> readMap(String filename) { Map<String,String> map = Generics.newHashMap(); try { BufferedReader br = IOUtils.readerFromString(filename); for (String line; (line = br.readLine()) != null; ) { String[] fields = tab.split(line,2); map.put(fields[0], fields[1]); } br.close(); } catch (IOException ex) { throw new RuntimeIOException(ex); } return map; } /** * Returns the contents of a file as a single string. The string may be * empty, if the file is empty. If there is an IOException, it is caught * and null is returned. */ public static String stringFromFile(String filename) { return stringFromFile(filename, defaultEncoding); } /** * Returns the contents of a file as a single string. The string may be * empty, if the file is empty. If there is an IOException, it is caught * and null is returned. Encoding can also be specified. */ // todo: This is same as slurpFile (!) public static String stringFromFile(String filename, String encoding) { try { StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new EncodingFileReader(filename,encoding)); String line; while ((line = in.readLine()) != null) { sb.append(line); sb.append(eolChar); } in.close(); return sb.toString(); } catch (IOException e) { logger.err(throwableToStackTrace(e)); return null; } } /** * Returns the contents of a file as a list of strings. The list may be * empty, if the file is empty. If there is an IOException, it is caught * and null is returned. */ public static List<String> linesFromFile(String filename) { return linesFromFile(filename, defaultEncoding); } /** * Returns the contents of a file as a list of strings. The list may be * empty, if the file is empty. If there is an IOException, it is caught * and null is returned. Encoding can also be specified */ public static List<String> linesFromFile(String filename,String encoding) { return linesFromFile(filename, encoding, false); } public static List<String> linesFromFile(String filename,String encoding, boolean ignoreHeader) { try { List<String> lines = new ArrayList<>(); BufferedReader in = readerFromString(filename, encoding); String line; int i = 0; while ((line = in.readLine()) != null) { i++; if(ignoreHeader && i == 1) continue; lines.add(line); } in.close(); return lines; } catch (IOException e) { logger.err(throwableToStackTrace(e)); return null; } } /** * A JavaNLP specific convenience routine for obtaining the current * scratch directory for the machine you're currently running on. */ public static File getJNLPLocalScratch() { try { String machineName = InetAddress.getLocalHost().getHostName().split("\\.")[0]; String username = System.getProperty("user.name"); return new File("/"+machineName+"/scr1/"+username); } catch (Exception e) { return new File("./scr/"); // default scratch } } /** * Given a filepath, makes sure a directory exists there. If not, creates and returns it. * Same as ENSURE-DIRECTORY in CL. * * @param tgtDir The directory that you wish to ensure exists * @throws IOException If directory can't be created, is an existing file, or for other reasons */ public static File ensureDir(File tgtDir) throws IOException { if (tgtDir.exists()) { if (tgtDir.isDirectory()) { return tgtDir; } else { throw new IOException("Could not create directory "+tgtDir.getAbsolutePath()+", as a file already exists at that path."); } } else { if ( ! tgtDir.mkdirs()) { throw new IOException("Could not create directory "+tgtDir.getAbsolutePath()); } return tgtDir; } } /** * Given a filepath, delete all files in the directory recursively * @param dir Directory from which to delete files * @return {@code true} if the deletion is successful, {@code false} otherwise */ public static boolean deleteDirRecursively(File dir) { if (dir.isDirectory()) { for (File f : dir.listFiles()) { boolean success = deleteDirRecursively(f); if (!success) return false; } } return dir.delete(); } public static String getExtension(String fileName) { if(!fileName.contains(".")) return null; int idx = fileName.lastIndexOf('.'); return fileName.substring(idx+1); } /** Create a Reader with an explicit encoding around an InputStream. * This static method will treat null as meaning to use the platform default, * unlike the Java library methods that disallow a null encoding. * * @param stream An InputStream * @param encoding A charset encoding * @return A Reader * @throws IOException If any IO problem */ public static Reader encodedInputStreamReader(InputStream stream, String encoding) throws IOException { // InputStreamReader doesn't allow encoding to be null; if (encoding == null) { return new InputStreamReader(stream); } else { return new InputStreamReader(stream, encoding); } } /** Create a Reader with an explicit encoding around an InputStream. * This static method will treat null as meaning to use the platform default, * unlike the Java library methods that disallow a null encoding. * * @param stream An InputStream * @param encoding A charset encoding * @return A Reader * @throws IOException If any IO problem */ public static Writer encodedOutputStreamWriter(OutputStream stream, String encoding) throws IOException { // OutputStreamWriter doesn't allow encoding to be null; if (encoding == null) { return new OutputStreamWriter(stream); } else { return new OutputStreamWriter(stream, encoding); } } /** Create a Reader with an explicit encoding around an InputStream. * This static method will treat null as meaning to use the platform default, * unlike the Java library methods that disallow a null encoding. * * @param stream An InputStream * @param encoding A charset encoding * @param autoFlush Whether to make an autoflushing Writer * @return A Reader * @throws IOException If any IO problem */ public static PrintWriter encodedOutputStreamPrintWriter(OutputStream stream, String encoding, boolean autoFlush) throws IOException { // PrintWriter doesn't allow encoding to be null; or to have charset and flush if (encoding == null) { return new PrintWriter(stream, autoFlush); } else { return new PrintWriter(new OutputStreamWriter(stream, encoding), autoFlush); } } /** * A raw file copy function -- this is not public since no error checks are made as to the * consistency of the file being copied. Use instead: * @see IOUtils#cp(java.io.File, java.io.File, boolean) * @param source The source file. This is guaranteed to exist, and is guaranteed to be a file. * @param target The target file. * @throws IOException Throws an exception if the copy fails. */ private static void copyFile(File source, File target) throws IOException { FileChannel sourceChannel = new FileInputStream( source ).getChannel(); FileChannel targetChannel = new FileOutputStream( target ).getChannel(); // allow for the case that it doesn't all transfer in one go (though it probably does for a file cp) long pos = 0; long toCopy = sourceChannel.size(); while (toCopy > 0) { long bytes = sourceChannel.transferTo(pos, toCopy, targetChannel); pos += bytes; toCopy -= bytes; } sourceChannel.close(); targetChannel.close(); } /** * <p>An implementation of cp, as close to the Unix command as possible. * Both directories and files are valid for either the source or the target; * if the target exists, the semantics of Unix cp are [intended to be] obeyed.</p> * * @param source The source file or directory. * @param target The target to write this file or directory to. * @param recursive If true, recursively copy directory contents * @throws IOException If either the copy fails (standard IO Exception), or the command is invalid * (e.g., copying a directory without the recursive flag) */ public static void cp(File source, File target, boolean recursive) throws IOException { // Error checks if (source.isDirectory() && !recursive) { // cp a b -- a is a directory throw new IOException("cp: omitting directory: " + source); } if (!target.getParentFile().exists()) { // cp a b/c/d/e -- b/c/d doesn't exist throw new IOException("cp: cannot copy to directory: " + recursive + " (parent doesn't exist)"); } if (!target.getParentFile().isDirectory()) { // cp a b/c/d/e -- b/c/d is a regular file throw new IOException("cp: cannot copy to directory: " + recursive + " (parent isn't a directory)"); } // Get true target File trueTarget; if (target.exists() && target.isDirectory()) { trueTarget = new File(target.getPath() + File.separator + source.getName()); } else { trueTarget = target; } // Copy if (source.isFile()) { // Case: copying a file copyFile(source, trueTarget); } else if (source.isDirectory()) { // Case: copying a directory File[] children = source.listFiles(); if (children == null) { throw new IOException("cp: could not list files in source: " + source); } if (target.exists()) { // Case: cp -r a b -- b exists if (!target.isDirectory()) { // cp -r a b -- b is a regular file throw new IOException("cp: cannot copy directory into regular file: " + target); } if (trueTarget.exists() && !trueTarget.isDirectory()) { // cp -r a b -- b/a is not a directory throw new IOException("cp: overwriting a file with a directory: " + trueTarget); } if (!trueTarget.exists() && !trueTarget.mkdir()) { // cp -r a b -- b/a cannot be created throw new IOException("cp: could not create directory: " + trueTarget); } } else { // Case: cp -r a b -- b does not exist assert trueTarget == target; if (!trueTarget.mkdir()) { // cp -r a b -- cannot create b as a directory throw new IOException("cp: could not create target directory: " + trueTarget); } } // Actually do the copy for (File child : children) { File childTarget = new File(trueTarget.getPath() + File.separator + child.getName()); cp(child, childTarget, recursive); } } else { throw new IOException("cp: unknown file type: " + source); } } /** * @see IOUtils#cp(java.io.File, java.io.File, boolean) */ public static void cp(File source, File target) throws IOException { cp(source, target, false); } /** * A Java implementation of the Unix tail functionality. * That is, read the last n lines of the input file f. * @param f The file to read the last n lines from * @param n The number of lines to read from the end of the file. * @param encoding The encoding to read the file in. * @return The read lines, one String per line. * @throws IOException if the file could not be read. */ public static String[] tail(File f, int n, String encoding) throws IOException { if (n == 0) { return new String[0]; } // Variables RandomAccessFile raf = new RandomAccessFile(f, "r"); int linesRead = 0; List<Byte> bytes = new ArrayList<>(); List<String> linesReversed = new ArrayList<>(); // Seek to end of file long length = raf.length() - 1; raf.seek(length); // Read backwards for(long seek = length; seek >= 0; --seek){ // Seek back raf.seek(seek); // Read the next character byte c = raf.readByte(); if(c == '\n'){ // If it's a newline, handle adding the line byte[] str = new byte[bytes.size()]; for (int i = 0; i < str.length; ++i) { str[i] = bytes.get(str.length - i - 1); } linesReversed.add(new String(str, encoding)); bytes = new ArrayList<>(); linesRead += 1; if (linesRead == n){ break; } } else { // Else, register the character for later bytes.add(c); } } // Add any remaining lines if (linesRead < n && bytes.size() > 0) { byte[] str = new byte[bytes.size()]; for (int i = 0; i < str.length; ++i) { str[i] = bytes.get(str.length - i - 1); } linesReversed.add(new String(str, encoding)); } // Create output String[] rtn = new String[linesReversed.size()]; for (int i = 0; i < rtn.length; ++i) { rtn[i] = linesReversed.get(rtn.length - i - 1); } raf.close(); return rtn; } /** @see edu.stanford.nlp.io.IOUtils#tail(java.io.File, int, String) */ public static String[] tail(File f, int n) throws IOException { return tail(f, n, "utf-8"); } /** Bare minimum sanity checks */ private static final Set<String> blockListPathsToRemove = new HashSet<String>(){{ add("/"); add("/u"); add("/u/"); add("/u/nlp"); add("/u/nlp/"); add("/u/nlp/data"); add("/u/nlp/data/"); add("/scr"); add("/scr/"); add("/u/scr/nlp/data"); add("/u/scr/nlp/data/"); }}; /** * Delete this file; or, if it is a directory, delete this directory and all its contents. * This is a somewhat dangerous function to call from code, and so a few safety features have been * implemented (though you should not rely on these!): * * <ul> * <li>Certain directories are prohibited from being removed.</li> * <li>More than 100 files cannot be removed with this function.</li> * <li>More than 10GB cannot be removed with this function.</li> * </ul> * * @param file The file or directory to delete. */ public static void deleteRecursively(File file) { // Sanity checks if (blockListPathsToRemove.contains(file.getPath())) { throw new IllegalArgumentException("You're trying to delete " + file + "! I _really_ don't think you want to do that..."); } int count = 0; long size = 0; for (File f : iterFilesRecursive(file)) { count += 1; size += f.length(); } if (count > 100) { throw new IllegalArgumentException("Deleting more than 100 files; you should do this manually"); } if (size > 10000000000L) { // 10 GB throw new IllegalArgumentException("Deleting more than 10GB; you should do this manually"); } // Do delete if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { deleteRecursively(child); } } } //noinspection ResultOfMethodCallIgnored file.delete(); } /** * Start a simple console. Read lines from stdin, and pass each line to the callback. * Returns on typing "exit" or "quit". * * @param callback The function to run for every line of input. * @throws IOException Thrown from the underlying input stream. */ public static void console(String prompt, Consumer<String> callback) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String line; System.out.print(prompt); while ( (line = reader.readLine()) != null) { switch (line.toLowerCase()) { case "": break; case "exit": case "quit": case "q": return; default: callback.accept(line); break; } System.out.print(prompt); } } /** * Create a prompt, and read a single line of response. * @param prompt An optional prompt to show the user. * @throws IOException Throw from the underlying reader. */ public static String promptUserInput(Optional<String> prompt) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print(prompt.orElse("> ")); return reader.readLine(); } /** @see IOUtils#console(String, Consumer) */ public static void console(Consumer<String> callback) throws IOException { console("> ", callback); } public static String throwableToStackTrace(Throwable t) { StringBuilder sb = new StringBuilder(); sb.append(t).append(eolChar); for (StackTraceElement e : t.getStackTrace()) { sb.append("\t at ").append(e).append(eolChar); } return sb.toString(); } }
stanfordnlp/CoreNLP
src/edu/stanford/nlp/io/IOUtils.java
2,118
package org.thoughtcrime.securesms.util; import android.os.Handler; import android.os.Looper; /** * A class that will throttle the number of runnables executed to be at most once every specified * interval. * * Useful for performing actions in response to rapid user input where you want to take action on * the initial input but prevent follow-up spam. * * This is different from {@link Debouncer} in that it will run the first runnable immediately * instead of waiting for input to die down. * * See http://rxmarbles.com/#throttle */ public class Throttler { private static final int WHAT = 8675309; private final Handler handler; private final long threshold; /** * @param threshold Only one runnable will be executed via {@link #publish(Runnable)} every * {@code threshold} milliseconds. */ public Throttler(long threshold) { this.handler = new Handler(Looper.getMainLooper()); this.threshold = threshold; } public void publish(Runnable runnable) { if (handler.hasMessages(WHAT)) { return; } runnable.run(); handler.sendMessageDelayed(handler.obtainMessage(WHAT), threshold); } public void clear() { handler.removeCallbacksAndMessages(null); } }
signalapp/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/util/Throttler.java
2,119
// 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.bidi; import org.openqa.selenium.WebDriverException; public class BiDiException extends WebDriverException { public BiDiException(Throwable cause) { this(cause.getMessage(), cause); } public BiDiException(String message) { this(message, null); } public BiDiException(String message, Throwable cause) { super(message, cause); addInfo(WebDriverException.DRIVER_INFO, "BiDi Connection"); } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/bidi/BiDiException.java
2,120
/* * Copyright (C) 2013 The Guava 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.common.base; import static com.google.common.base.Strings.lenientFormat; import com.google.common.annotations.GwtCompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static convenience methods that serve the same purpose as Java language <a * href="https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html">assertions</a>, * except that they are always enabled. These methods should be used instead of Java assertions * whenever there is a chance the check may fail "in real life". Example: * * <pre>{@code * Bill bill = remoteService.getLastUnpaidBill(); * * // In case bug 12345 happens again we'd rather just die * Verify.verify(bill.status() == Status.UNPAID, * "Unexpected bill status: %s", bill.status()); * }</pre> * * <h3>Comparison to alternatives</h3> * * <p><b>Note:</b> In some cases the differences explained below can be subtle. When it's unclear * which approach to use, <b>don't worry</b> too much about it; just pick something that seems * reasonable and it will be fine. * * <ul> * <li>If checking whether the <i>caller</i> has violated your method or constructor's contract * (such as by passing an invalid argument), use the utilities of the {@link Preconditions} * class instead. * <li>If checking an <i>impossible</i> condition (which <i>cannot</i> happen unless your own * class or its <i>trusted</i> dependencies is badly broken), this is what ordinary Java * assertions are for. Note that assertions are not enabled by default; they are essentially * considered "compiled comments." * <li>An explicit {@code if/throw} (as illustrated below) is always acceptable; we still * recommend using our {@link VerifyException} exception type. Throwing a plain {@link * RuntimeException} is frowned upon. * <li>Use of {@link java.util.Objects#requireNonNull(Object)} is generally discouraged, since * {@link #verifyNotNull(Object)} and {@link Preconditions#checkNotNull(Object)} perform the * same function with more clarity. * </ul> * * <h3>Warning about performance</h3> * * <p>Remember that parameter values for message construction must all be computed eagerly, and * autoboxing and varargs array creation may happen as well, even when the verification succeeds and * the message ends up unneeded. Performance-sensitive verification checks should continue to use * usual form: * * <pre>{@code * Bill bill = remoteService.getLastUnpaidBill(); * if (bill.status() != Status.UNPAID) { * throw new VerifyException("Unexpected bill status: " + bill.status()); * } * }</pre> * * <h3>Only {@code %s} is supported</h3> * * <p>As with {@link Preconditions}, {@code Verify} uses {@link Strings#lenientFormat} to format * error message template strings. This only supports the {@code "%s"} specifier, not the full range * of {@link java.util.Formatter} specifiers. However, note that if the number of arguments does not * match the number of occurrences of {@code "%s"} in the format string, {@code Verify} will still * behave as expected, and will still include all argument values in the error message; the message * will simply not be formatted exactly as intended. * * <h3>More information</h3> * * See <a href="https://github.com/google/guava/wiki/ConditionalFailuresExplained">Conditional * failures explained</a> in the Guava User Guide for advice on when this class should be used. * * @since 17.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Verify { /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with no * message otherwise. * * @throws VerifyException if {@code expression} is {@code false} * @see Preconditions#checkState Preconditions.checkState() */ public static void verify(boolean expression) { if (!expression) { throw new VerifyException(); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in * square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @throws VerifyException if {@code expression} is {@code false} * @see Preconditions#checkState Preconditions.checkState() */ public static void verify( boolean expression, String errorMessageTemplate, @CheckForNull @Nullable Object... errorMessageArgs) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, errorMessageArgs)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify(boolean expression, String errorMessageTemplate, char p1) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify(boolean expression, String errorMessageTemplate, int p1) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify(boolean expression, String errorMessageTemplate, long p1) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify( boolean expression, String errorMessageTemplate, @CheckForNull Object p1) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify(boolean expression, String errorMessageTemplate, char p1, char p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify(boolean expression, String errorMessageTemplate, int p1, char p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify(boolean expression, String errorMessageTemplate, long p1, char p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, char p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify(boolean expression, String errorMessageTemplate, char p1, int p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify(boolean expression, String errorMessageTemplate, int p1, int p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify(boolean expression, String errorMessageTemplate, long p1, int p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, int p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify(boolean expression, String errorMessageTemplate, char p1, long p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify(boolean expression, String errorMessageTemplate, int p1, long p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify(boolean expression, String errorMessageTemplate, long p1, long p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, long p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify( boolean expression, String errorMessageTemplate, char p1, @CheckForNull Object p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify( boolean expression, String errorMessageTemplate, int p1, @CheckForNull Object p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify( boolean expression, String errorMessageTemplate, long p1, @CheckForNull Object p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2, @CheckForNull Object p3) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2, p3)); } } /** * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a * custom message otherwise. * * <p>See {@link #verify(boolean, String, Object...)} for details. * * @since 23.1 (varargs overload since 17.0) */ public static void verify( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2, @CheckForNull Object p3, @CheckForNull Object p4) { if (!expression) { throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2, p3, p4)); } } /* * For a discussion of the signature of verifyNotNull, see the discussion above * Preconditions.checkNotNull. * * (verifyNotNull has many fewer "problem" callers, so we could try to be stricter. On the other * hand, verifyNotNull arguably has more reason to accept nullable arguments in the first * place....) */ /** * Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a default * message otherwise. * * @return {@code reference}, guaranteed to be non-null, for convenience * @throws VerifyException if {@code reference} is {@code null} * @see Preconditions#checkNotNull Preconditions.checkNotNull() */ @CanIgnoreReturnValue public static <T> T verifyNotNull(@CheckForNull T reference) { return verifyNotNull(reference, "expected a non-null reference"); } /** * Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a custom * message otherwise. * * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in * square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @return {@code reference}, guaranteed to be non-null, for convenience * @throws VerifyException if {@code reference} is {@code null} * @see Preconditions#checkNotNull Preconditions.checkNotNull() */ @CanIgnoreReturnValue public static <T> T verifyNotNull( @CheckForNull T reference, String errorMessageTemplate, @CheckForNull @Nullable Object... errorMessageArgs) { if (reference == null) { throw new VerifyException(lenientFormat(errorMessageTemplate, errorMessageArgs)); } return reference; } // TODO(kevinb): consider <T> T verifySingleton(Iterable<T>) to take over for // Iterables.getOnlyElement() private Verify() {} }
google/guava
guava/src/com/google/common/base/Verify.java
2,121
package com.baeldung.entity; public class BioDieselCar extends Car { }
eugenp/tutorials
mapstruct/src/main/java/com/baeldung/entity/BioDieselCar.java
2,122
package com.baeldung.jdi; public class JDIExampleDebuggee { public static void main(String[] args) { String jpda = "Java Platform Debugger Architecture"; System.out.println("Hi Everyone, Welcome to " + jpda); //add a break point here String jdi = "Java Debug Interface"; //add a break point here and also stepping in here String text = "Today, we'll dive into " + jdi; System.out.println(text); } }
eugenp/tutorials
java-jdi/src/main/java/com/baeldung/jdi/JDIExampleDebuggee.java
2,123
package com.baeldung.jdi; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Map; import com.sun.jdi.AbsentInformationException; import com.sun.jdi.Bootstrap; import com.sun.jdi.ClassType; import com.sun.jdi.IncompatibleThreadStateException; import com.sun.jdi.LocalVariable; import com.sun.jdi.Location; import com.sun.jdi.StackFrame; import com.sun.jdi.VMDisconnectedException; import com.sun.jdi.Value; import com.sun.jdi.VirtualMachine; import com.sun.jdi.connect.Connector; import com.sun.jdi.connect.IllegalConnectorArgumentsException; import com.sun.jdi.connect.LaunchingConnector; import com.sun.jdi.connect.VMStartException; import com.sun.jdi.event.BreakpointEvent; import com.sun.jdi.event.ClassPrepareEvent; import com.sun.jdi.event.Event; import com.sun.jdi.event.EventSet; import com.sun.jdi.event.LocatableEvent; import com.sun.jdi.event.StepEvent; import com.sun.jdi.request.BreakpointRequest; import com.sun.jdi.request.ClassPrepareRequest; import com.sun.jdi.request.StepRequest; public class JDIExampleDebugger { private Class debugClass; private int[] breakPointLines; public Class getDebugClass() { return debugClass; } public void setDebugClass(Class debugClass) { this.debugClass = debugClass; } public int[] getBreakPointLines() { return breakPointLines; } public void setBreakPointLines(int[] breakPointLines) { this.breakPointLines = breakPointLines; } /** * Sets the debug class as the main argument in the connector and launches the VM * @return VirtualMachine * @throws IOException * @throws IllegalConnectorArgumentsException * @throws VMStartException */ public VirtualMachine connectAndLaunchVM() throws IOException, IllegalConnectorArgumentsException, VMStartException { LaunchingConnector launchingConnector = Bootstrap.virtualMachineManager().defaultConnector(); Map<String, Connector.Argument> arguments = launchingConnector.defaultArguments(); arguments.get("main").setValue(debugClass.getName()); VirtualMachine vm = launchingConnector.launch(arguments); return vm; } /** * Creates a request to prepare the debug class, add filter as the debug class and enables it * @param vm */ public void enableClassPrepareRequest(VirtualMachine vm) { ClassPrepareRequest classPrepareRequest = vm.eventRequestManager().createClassPrepareRequest(); classPrepareRequest.addClassFilter(debugClass.getName()); classPrepareRequest.enable(); } /** * Sets the break points at the line numbers mentioned in breakPointLines array * @param vm * @param event * @throws AbsentInformationException */ public void setBreakPoints(VirtualMachine vm, ClassPrepareEvent event) throws AbsentInformationException { ClassType classType = (ClassType) event.referenceType(); for(int lineNumber: breakPointLines) { Location location = classType.locationsOfLine(lineNumber).get(0); BreakpointRequest bpReq = vm.eventRequestManager().createBreakpointRequest(location); bpReq.enable(); } } /** * Displays the visible variables * @param event * @throws IncompatibleThreadStateException * @throws AbsentInformationException */ public void displayVariables(LocatableEvent event) throws IncompatibleThreadStateException, AbsentInformationException { StackFrame stackFrame = event.thread().frame(0); if(stackFrame.location().toString().contains(debugClass.getName())) { Map<LocalVariable, Value> visibleVariables = stackFrame.getValues(stackFrame.visibleVariables()); System.out.println("Variables at " +stackFrame.location().toString() + " > "); for (Map.Entry<LocalVariable, Value> entry : visibleVariables.entrySet()) { System.out.println(entry.getKey().name() + " = " + entry.getValue()); } } } /** * Enables step request for a break point * @param vm * @param event */ public void enableStepRequest(VirtualMachine vm, BreakpointEvent event) { //enable step request for last break point if(event.location().toString().contains(debugClass.getName()+":"+breakPointLines[breakPointLines.length-1])) { StepRequest stepRequest = vm.eventRequestManager().createStepRequest(event.thread(), StepRequest.STEP_LINE, StepRequest.STEP_OVER); stepRequest.enable(); } } public static void main(String[] args) throws Exception { JDIExampleDebugger debuggerInstance = new JDIExampleDebugger(); debuggerInstance.setDebugClass(JDIExampleDebuggee.class); int[] breakPoints = {6, 9}; debuggerInstance.setBreakPointLines(breakPoints); VirtualMachine vm = null; try { vm = debuggerInstance.connectAndLaunchVM(); debuggerInstance.enableClassPrepareRequest(vm); EventSet eventSet = null; while ((eventSet = vm.eventQueue().remove()) != null) { for (Event event : eventSet) { if (event instanceof ClassPrepareEvent) { debuggerInstance.setBreakPoints(vm, (ClassPrepareEvent)event); } if (event instanceof BreakpointEvent) { event.request().disable(); debuggerInstance.displayVariables((BreakpointEvent) event); debuggerInstance.enableStepRequest(vm, (BreakpointEvent)event); } if (event instanceof StepEvent) { debuggerInstance.displayVariables((StepEvent) event); } vm.resume(); } } } catch (VMDisconnectedException e) { System.out.println("Virtual Machine is disconnected."); } catch (Exception e) { e.printStackTrace(); } finally { InputStreamReader reader = new InputStreamReader(vm.process().getInputStream()); OutputStreamWriter writer = new OutputStreamWriter(System.out); char[] buf = new char[512]; reader.read(buf); writer.write(buf); writer.flush(); } } }
eugenp/tutorials
java-jdi/src/main/java/com/baeldung/jdi/JDIExampleDebugger.java
2,124
/* * Copyright 2002-2017 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.jndi; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.lang.Nullable; /** * Convenient superclass for JNDI accessors, providing "jndiTemplate" * and "jndiEnvironment" bean properties. * * @author Juergen Hoeller * @since 1.1 * @see #setJndiTemplate * @see #setJndiEnvironment */ public class JndiAccessor { /** * Logger, available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); private JndiTemplate jndiTemplate = new JndiTemplate(); /** * Set the JNDI template to use for JNDI lookups. * <p>You can also specify JNDI environment settings via "jndiEnvironment". * @see #setJndiEnvironment */ public void setJndiTemplate(@Nullable JndiTemplate jndiTemplate) { this.jndiTemplate = (jndiTemplate != null ? jndiTemplate : new JndiTemplate()); } /** * Return the JNDI template to use for JNDI lookups. */ public JndiTemplate getJndiTemplate() { return this.jndiTemplate; } /** * Set the JNDI environment to use for JNDI lookups. * <p>Creates a JndiTemplate with the given environment settings. * @see #setJndiTemplate */ public void setJndiEnvironment(@Nullable Properties jndiEnvironment) { this.jndiTemplate = new JndiTemplate(jndiEnvironment); } /** * Return the JNDI environment to use for JNDI lookups. */ @Nullable public Properties getJndiEnvironment() { return this.jndiTemplate.getEnvironment(); } }
spring-projects/spring-framework
spring-context/src/main/java/org/springframework/jndi/JndiAccessor.java
2,125
/* * Copyright 2002-2016 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.jndi; import javax.naming.InitialContext; import javax.naming.NamingException; import org.springframework.core.SpringProperties; import org.springframework.lang.Nullable; /** * {@link JndiLocatorSupport} subclass with public lookup methods, * for convenient use as a delegate. * * @author Juergen Hoeller * @since 3.0.1 */ public class JndiLocatorDelegate extends JndiLocatorSupport { /** * System property that instructs Spring to ignore a default JNDI environment, i.e. * to always return {@code false} from {@link #isDefaultJndiEnvironmentAvailable()}. * <p>The default is "false", allowing for regular default JNDI access e.g. in * {@link JndiPropertySource}. Switching this flag to {@code true} is an optimization * for scenarios where nothing is ever to be found for such JNDI fallback searches * to begin with, avoiding the repeated JNDI lookup overhead. * <p>Note that this flag just affects JNDI fallback searches, not explicitly configured * JNDI lookups such as for a {@code DataSource} or some other environment resource. * The flag literally just affects code which attempts JNDI searches based on the * {@code JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()} check: in particular, * {@code StandardServletEnvironment} and {@code StandardPortletEnvironment}. * @since 4.3 * @see #isDefaultJndiEnvironmentAvailable() * @see JndiPropertySource */ public static final String IGNORE_JNDI_PROPERTY_NAME = "spring.jndi.ignore"; private static final boolean shouldIgnoreDefaultJndiEnvironment = SpringProperties.getFlag(IGNORE_JNDI_PROPERTY_NAME); @Override public Object lookup(String jndiName) throws NamingException { return super.lookup(jndiName); } @Override public <T> T lookup(String jndiName, @Nullable Class<T> requiredType) throws NamingException { return super.lookup(jndiName, requiredType); } /** * Configure a {@code JndiLocatorDelegate} with its "resourceRef" property set to * {@code true}, meaning that all names will be prefixed with "java:comp/env/". * @see #setResourceRef */ public static JndiLocatorDelegate createDefaultResourceRefLocator() { JndiLocatorDelegate jndiLocator = new JndiLocatorDelegate(); jndiLocator.setResourceRef(true); return jndiLocator; } /** * Check whether a default JNDI environment, as in a Jakarta EE environment, * is available on this JVM. * @return {@code true} if a default InitialContext can be used, * {@code false} if not */ public static boolean isDefaultJndiEnvironmentAvailable() { if (shouldIgnoreDefaultJndiEnvironment) { return false; } try { new InitialContext().getEnvironment(); return true; } catch (Throwable ex) { return false; } } }
spring-projects/spring-framework
spring-context/src/main/java/org/springframework/jndi/JndiLocatorDelegate.java
2,127
package com.airbnb.lottie.parser; import android.graphics.Path; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableGradientColorValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatablePointValue; import com.airbnb.lottie.model.content.GradientFill; import com.airbnb.lottie.model.content.GradientType; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; import java.util.Collections; class GradientFillParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", "g", "o", "t", "s", "e", "r", "hd" ); private static final JsonReader.Options GRADIENT_NAMES = JsonReader.Options.of( "p", "k" ); private GradientFillParser() { } static GradientFill parse( JsonReader reader, LottieComposition composition) throws IOException { String name = null; AnimatableGradientColorValue color = null; AnimatableIntegerValue opacity = null; GradientType gradientType = null; AnimatablePointValue startPoint = null; AnimatablePointValue endPoint = null; Path.FillType fillType = Path.FillType.WINDING; boolean hidden = false; while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: int points = -1; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(GRADIENT_NAMES)) { case 0: points = reader.nextInt(); break; case 1: color = AnimatableValueParser.parseGradientColor(reader, composition, points); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); break; case 2: opacity = AnimatableValueParser.parseInteger(reader, composition); break; case 3: gradientType = reader.nextInt() == 1 ? GradientType.LINEAR : GradientType.RADIAL; break; case 4: startPoint = AnimatableValueParser.parsePoint(reader, composition); break; case 5: endPoint = AnimatableValueParser.parsePoint(reader, composition); break; case 6: fillType = reader.nextInt() == 1 ? Path.FillType.WINDING : Path.FillType.EVEN_ODD; break; case 7: hidden = reader.nextBoolean(); break; default: reader.skipName(); reader.skipValue(); } } // Telegram sometimes omits opacity. // https://github.com/airbnb/lottie-android/issues/1600 opacity = opacity == null ? new AnimatableIntegerValue(Collections.singletonList(new Keyframe<>(100))) : opacity; return new GradientFill( name, gradientType, fillType, color, opacity, startPoint, endPoint, null, null, hidden); } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/parser/GradientFillParser.java
2,128
package com.airbnb.lottie.model.content; import android.graphics.Path; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.GradientFillContent; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableGradientColorValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatablePointValue; import com.airbnb.lottie.model.layer.BaseLayer; public class GradientFill implements ContentModel { private final GradientType gradientType; private final Path.FillType fillType; private final AnimatableGradientColorValue gradientColor; private final AnimatableIntegerValue opacity; private final AnimatablePointValue startPoint; private final AnimatablePointValue endPoint; private final String name; @Nullable private final AnimatableFloatValue highlightLength; @Nullable private final AnimatableFloatValue highlightAngle; private final boolean hidden; public GradientFill(String name, GradientType gradientType, Path.FillType fillType, AnimatableGradientColorValue gradientColor, AnimatableIntegerValue opacity, AnimatablePointValue startPoint, AnimatablePointValue endPoint, AnimatableFloatValue highlightLength, AnimatableFloatValue highlightAngle, boolean hidden) { this.gradientType = gradientType; this.fillType = fillType; this.gradientColor = gradientColor; this.opacity = opacity; this.startPoint = startPoint; this.endPoint = endPoint; this.name = name; this.highlightLength = highlightLength; this.highlightAngle = highlightAngle; this.hidden = hidden; } public String getName() { return name; } public GradientType getGradientType() { return gradientType; } public Path.FillType getFillType() { return fillType; } public AnimatableGradientColorValue getGradientColor() { return gradientColor; } public AnimatableIntegerValue getOpacity() { return opacity; } public AnimatablePointValue getStartPoint() { return startPoint; } public AnimatablePointValue getEndPoint() { return endPoint; } public boolean isHidden() { return hidden; } @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new GradientFillContent(drawable, composition, layer, this); } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/model/content/GradientFill.java
2,129
package com.airbnb.lottie.parser; import android.graphics.Color; import com.airbnb.lottie.model.content.GradientColor; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.utils.GammaEvaluator; import com.airbnb.lottie.utils.MiscUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class GradientColorParser implements com.airbnb.lottie.parser.ValueParser<GradientColor> { /** * The number of colors if it exists in the json or -1 if it doesn't (legacy bodymovin) */ private int colorPoints; public GradientColorParser(int colorPoints) { this.colorPoints = colorPoints; } /** * Both the color stops and opacity stops are in the same array. * There are {@link #colorPoints} colors sequentially as: * [ * ..., * position, * red, * green, * blue, * ... * ] * <p> * The remainder of the array is the opacity stops sequentially as: * [ * ..., * position, * opacity, * ... * ] */ @Override public GradientColor parse(JsonReader reader, float scale) throws IOException { List<Float> array = new ArrayList<>(); // The array was started by Keyframe because it thought that this may be an array of keyframes // but peek returned a number so it considered it a static array of numbers. boolean isArray = reader.peek() == JsonReader.Token.BEGIN_ARRAY; if (isArray) { reader.beginArray(); } while (reader.hasNext()) { array.add((float) reader.nextDouble()); } if (array.size() == 4 && array.get(0) == 1f) { // If a gradient color only contains one color at position 1, add a second stop with the same // color at position 0. Android's LinearGradient shader requires at least two colors. // https://github.com/airbnb/lottie-android/issues/1967 array.set(0, 0f); array.add(1f); array.add(array.get(1)); array.add(array.get(2)); array.add(array.get(3)); colorPoints = 2; } if (isArray) { reader.endArray(); } if (colorPoints == -1) { colorPoints = array.size() / 4; } float[] positions = new float[colorPoints]; int[] colors = new int[colorPoints]; int r = 0; int g = 0; for (int i = 0; i < colorPoints * 4; i++) { int colorIndex = i / 4; double value = array.get(i); switch (i % 4) { case 0: // Positions should monotonically increase. If they don't, it can cause rendering problems on some phones. // https://github.com/airbnb/lottie-android/issues/1675 if (colorIndex > 0 && positions[colorIndex - 1] >= (float) value) { positions[colorIndex] = (float) value + 0.01f; } else { positions[colorIndex] = (float) value; } break; case 1: r = (int) (value * 255); break; case 2: g = (int) (value * 255); break; case 3: int b = (int) (value * 255); colors[colorIndex] = Color.argb(255, r, g, b); break; } } GradientColor gradientColor = new GradientColor(positions, colors); gradientColor = addOpacityStopsToGradientIfNeeded(gradientColor, array); return gradientColor; } /** * This cheats a little bit. * Opacity stops can be at arbitrary intervals independent of color stops. * This uses the existing color stops and modifies the opacity at each existing color stop * based on what the opacity would be. * <p> * This should be a good approximation is nearly all cases. However, if there are many more * opacity stops than color stops, information will be lost. */ private GradientColor addOpacityStopsToGradientIfNeeded(GradientColor gradientColor, List<Float> array) { int startIndex = colorPoints * 4; if (array.size() <= startIndex) { return gradientColor; } // When there are opacity stops, we create a merged list of color stops and opacity stops. // For a given color stop, we linearly interpolate the opacity for the two opacity stops around it. // For a given opacity stop, we linearly interpolate the color for the two color stops around it. float[] colorStopPositions = gradientColor.getPositions(); int[] colorStopColors = gradientColor.getColors(); int opacityStops = (array.size() - startIndex) / 2; float[] opacityStopPositions = new float[opacityStops]; float[] opacityStopOpacities = new float[opacityStops]; for (int i = startIndex, j = 0; i < array.size(); i++) { if (i % 2 == 0) { opacityStopPositions[j] = array.get(i); } else { opacityStopOpacities[j] = array.get(i); j++; } } // Pre-SKIA (Oreo) devices render artifacts when there is two stops in the same position. // As a result, we have to de-dupe the merge color and opacity stop positions. float[] newPositions = mergeUniqueElements(gradientColor.getPositions(), opacityStopPositions); int newColorPoints = newPositions.length; int[] newColors = new int[newColorPoints]; for (int i = 0; i < newColorPoints; i++) { float position = newPositions[i]; int colorStopIndex = Arrays.binarySearch(colorStopPositions, position); int opacityIndex = Arrays.binarySearch(opacityStopPositions, position); if (colorStopIndex < 0 || opacityIndex > 0) { // This is a stop derived from an opacity stop. if (opacityIndex < 0) { // The formula here is derived from the return value for binarySearch. When an item isn't found, it returns -insertionPoint - 1. opacityIndex = -(opacityIndex + 1); } newColors[i] = getColorInBetweenColorStops(position, opacityStopOpacities[opacityIndex], colorStopPositions, colorStopColors); } else { // This os a step derived from a color stop. newColors[i] = getColorInBetweenOpacityStops(position, colorStopColors[colorStopIndex], opacityStopPositions, opacityStopOpacities); } } return new GradientColor(newPositions, newColors); } int getColorInBetweenColorStops(float position, float opacity, float[] colorStopPositions, int[] colorStopColors) { if (colorStopColors.length < 2 || position == colorStopPositions[0]) { return colorStopColors[0]; } for (int i = 1; i < colorStopPositions.length; i++) { float colorStopPosition = colorStopPositions[i]; if (colorStopPosition < position && i != colorStopPositions.length - 1) { continue; } if (i == colorStopPositions.length - 1 && position >= colorStopPosition) { return Color.argb( (int) (opacity * 255), Color.red(colorStopColors[i]), Color.green(colorStopColors[i]), Color.blue(colorStopColors[i]) ); } // We found the position in which position is between i - 1 and i. float distanceBetweenColors = colorStopPositions[i] - colorStopPositions[i - 1]; float distanceToLowerColor = position - colorStopPositions[i - 1]; float percentage = distanceToLowerColor / distanceBetweenColors; int upperColor = colorStopColors[i]; int lowerColor = colorStopColors[i - 1]; int intermediateColor = GammaEvaluator.evaluate(percentage, lowerColor, upperColor); int a = (int) (opacity * 255); int r = Color.red(intermediateColor); int g = Color.green(intermediateColor); int b = Color.blue(intermediateColor); return Color.argb(a, r, g, b); } throw new IllegalArgumentException("Unreachable code."); } private int getColorInBetweenOpacityStops(float position, int color, float[] opacityStopPositions, float[] opacityStopOpacities) { if (opacityStopOpacities.length < 2 || position <= opacityStopPositions[0]) { int a = (int) (opacityStopOpacities[0] * 255); int r = Color.red(color); int g = Color.green(color); int b = Color.blue(color); return Color.argb(a, r, g, b); } for (int i = 1; i < opacityStopPositions.length; i++) { float opacityStopPosition = opacityStopPositions[i]; if (opacityStopPosition < position && i != opacityStopPositions.length - 1) { continue; } final int a; if (opacityStopPosition <= position) { a = (int) (opacityStopOpacities[i] * 255); } else { // We found the position in which position in between i - 1 and i. float distanceBetweenOpacities = opacityStopPositions[i] - opacityStopPositions[i - 1]; float distanceToLowerOpacity = position - opacityStopPositions[i - 1]; float percentage = distanceToLowerOpacity / distanceBetweenOpacities; a = (int) (MiscUtils.lerp(opacityStopOpacities[i - 1], opacityStopOpacities[i], percentage) * 255); } int r = Color.red(color); int g = Color.green(color); int b = Color.blue(color); return Color.argb(a, r, g, b); } throw new IllegalArgumentException("Unreachable code."); } /** * Takes two sorted float arrays and merges their elements while removing duplicates. */ protected static float[] mergeUniqueElements(float[] arrayA, float[] arrayB) { if (arrayA.length == 0) { return arrayB; } else if (arrayB.length == 0) { return arrayA; } int aIndex = 0; int bIndex = 0; int numDuplicates = 0; // This will be the merged list but may be longer than what is needed if there are duplicates. // If there are, the 0 elements at the end need to be truncated. float[] mergedNotTruncated = new float[arrayA.length + arrayB.length]; for (int i = 0; i < mergedNotTruncated.length; i++) { final float a = aIndex < arrayA.length ? arrayA[aIndex] : Float.NaN; final float b = bIndex < arrayB.length ? arrayB[bIndex] : Float.NaN; if (Float.isNaN(b) || a < b) { mergedNotTruncated[i] = a; aIndex++; } else if (Float.isNaN(a) || b < a) { mergedNotTruncated[i] = b; bIndex++; } else { mergedNotTruncated[i] = a; aIndex++; bIndex++; numDuplicates++; } } if (numDuplicates == 0) { return mergedNotTruncated; } return Arrays.copyOf(mergedNotTruncated, mergedNotTruncated.length - numDuplicates); } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/parser/GradientColorParser.java
2,130
package com.airbnb.lottie.model.content; import com.airbnb.lottie.utils.GammaEvaluator; import com.airbnb.lottie.utils.MiscUtils; import java.util.Arrays; public class GradientColor { private final float[] positions; private final int[] colors; public GradientColor(float[] positions, int[] colors) { this.positions = positions; this.colors = colors; } public float[] getPositions() { return positions; } public int[] getColors() { return colors; } public int getSize() { return colors.length; } public void lerp(GradientColor gc1, GradientColor gc2, float progress) { // Fast return in case start and end is the same // or if progress is at start/end or out of [0,1] bounds if (gc1.equals(gc2)) { copyFrom(gc1); return; } else if (progress <= 0f) { copyFrom(gc1); return; } else if (progress >= 1f) { copyFrom(gc2); return; } if (gc1.colors.length != gc2.colors.length) { throw new IllegalArgumentException("Cannot interpolate between gradients. Lengths vary (" + gc1.colors.length + " vs " + gc2.colors.length + ")"); } for (int i = 0; i < gc1.colors.length; i++) { positions[i] = MiscUtils.lerp(gc1.positions[i], gc2.positions[i], progress); colors[i] = GammaEvaluator.evaluate(progress, gc1.colors[i], gc2.colors[i]); } // Not all keyframes that this GradientColor are used for will have the same length. // AnimatableGradientColorValue.ensureInterpolatableKeyframes may add extra positions // for some keyframes but not others to ensure that it is interpolatable. // If there are extra positions here, just duplicate the last value in the gradient. for (int i = gc1.colors.length; i < positions.length; i++) { positions[i] = positions[gc1.colors.length - 1]; colors[i] = colors[gc1.colors.length - 1]; } } public GradientColor copyWithPositions(float[] positions) { int[] colors = new int[positions.length]; for (int i = 0; i < positions.length; i++) { colors[i] = getColorForPosition(positions[i]); } return new GradientColor(positions, colors); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GradientColor that = (GradientColor) o; return Arrays.equals(positions, that.positions) && Arrays.equals(colors, that.colors); } @Override public int hashCode() { int result = Arrays.hashCode(positions); result = 31 * result + Arrays.hashCode(colors); return result; } private int getColorForPosition(float position) { int existingIndex = Arrays.binarySearch(positions, position); if (existingIndex >= 0) { return colors[existingIndex]; } // binarySearch returns -insertionPoint - 1 if it is not found. int insertionPoint = -(existingIndex + 1); if (insertionPoint == 0) { return colors[0]; } else if (insertionPoint == colors.length - 1) { return colors[colors.length - 1]; } float startPosition = positions[insertionPoint - 1]; float endPosition = positions[insertionPoint]; int startColor = colors[insertionPoint - 1]; int endColor = colors[insertionPoint]; float fraction = (position - startPosition) / (endPosition - startPosition); return GammaEvaluator.evaluate(fraction, startColor, endColor); } private void copyFrom(GradientColor other) { for (int i = 0; i < other.colors.length; i++) { positions[i] = other.positions[i]; colors[i] = other.colors[i]; } } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/model/content/GradientColor.java
2,131
package com.airbnb.lottie.parser; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableGradientColorValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatablePointValue; import com.airbnb.lottie.model.content.GradientStroke; import com.airbnb.lottie.model.content.GradientType; import com.airbnb.lottie.model.content.ShapeStroke; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; class GradientStrokeParser { private GradientStrokeParser() { } private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", "g", "o", "t", "s", "e", "w", "lc", "lj", "ml", "hd", "d" ); private static final JsonReader.Options GRADIENT_NAMES = JsonReader.Options.of( "p", "k" ); private static final JsonReader.Options DASH_PATTERN_NAMES = JsonReader.Options.of( "n", "v" ); static GradientStroke parse( JsonReader reader, LottieComposition composition) throws IOException { String name = null; AnimatableGradientColorValue color = null; AnimatableIntegerValue opacity = null; GradientType gradientType = null; AnimatablePointValue startPoint = null; AnimatablePointValue endPoint = null; AnimatableFloatValue width = null; ShapeStroke.LineCapType capType = null; ShapeStroke.LineJoinType joinType = null; AnimatableFloatValue offset = null; float miterLimit = 0f; boolean hidden = false; List<AnimatableFloatValue> lineDashPattern = new ArrayList<>(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: int points = -1; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(GRADIENT_NAMES)) { case 0: points = reader.nextInt(); break; case 1: color = AnimatableValueParser.parseGradientColor(reader, composition, points); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); break; case 2: opacity = AnimatableValueParser.parseInteger(reader, composition); break; case 3: gradientType = reader.nextInt() == 1 ? GradientType.LINEAR : GradientType.RADIAL; break; case 4: startPoint = AnimatableValueParser.parsePoint(reader, composition); break; case 5: endPoint = AnimatableValueParser.parsePoint(reader, composition); break; case 6: width = AnimatableValueParser.parseFloat(reader, composition); break; case 7: capType = ShapeStroke.LineCapType.values()[reader.nextInt() - 1]; break; case 8: joinType = ShapeStroke.LineJoinType.values()[reader.nextInt() - 1]; break; case 9: miterLimit = (float) reader.nextDouble(); break; case 10: hidden = reader.nextBoolean(); break; case 11: reader.beginArray(); while (reader.hasNext()) { String n = null; AnimatableFloatValue val = null; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(DASH_PATTERN_NAMES)) { case 0: n = reader.nextString(); break; case 1: val = AnimatableValueParser.parseFloat(reader, composition); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); if (n.equals("o")) { offset = val; } else if (n.equals("d") || n.equals("g")) { composition.setHasDashPattern(true); lineDashPattern.add(val); } } reader.endArray(); if (lineDashPattern.size() == 1) { // If there is only 1 value then it is assumed to be equal parts on and off. lineDashPattern.add(lineDashPattern.get(0)); } break; default: reader.skipName(); reader.skipValue(); } } // Telegram sometimes omits opacity. // https://github.com/airbnb/lottie-android/issues/1600 opacity = opacity == null ? new AnimatableIntegerValue(Collections.singletonList(new Keyframe<>(100))) : opacity; return new GradientStroke( name, gradientType, color, opacity, startPoint, endPoint, width, capType, joinType, miterLimit, lineDashPattern, offset, hidden); } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/parser/GradientStrokeParser.java
2,132
package com.airbnb.lottie.model.content; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.GradientStrokeContent; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableGradientColorValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatablePointValue; import com.airbnb.lottie.model.layer.BaseLayer; import java.util.List; public class GradientStroke implements ContentModel { private final String name; private final GradientType gradientType; private final AnimatableGradientColorValue gradientColor; private final AnimatableIntegerValue opacity; private final AnimatablePointValue startPoint; private final AnimatablePointValue endPoint; private final AnimatableFloatValue width; private final ShapeStroke.LineCapType capType; private final ShapeStroke.LineJoinType joinType; private final float miterLimit; private final List<AnimatableFloatValue> lineDashPattern; @Nullable private final AnimatableFloatValue dashOffset; private final boolean hidden; public GradientStroke(String name, GradientType gradientType, AnimatableGradientColorValue gradientColor, AnimatableIntegerValue opacity, AnimatablePointValue startPoint, AnimatablePointValue endPoint, AnimatableFloatValue width, ShapeStroke.LineCapType capType, ShapeStroke.LineJoinType joinType, float miterLimit, List<AnimatableFloatValue> lineDashPattern, @Nullable AnimatableFloatValue dashOffset, boolean hidden) { this.name = name; this.gradientType = gradientType; this.gradientColor = gradientColor; this.opacity = opacity; this.startPoint = startPoint; this.endPoint = endPoint; this.width = width; this.capType = capType; this.joinType = joinType; this.miterLimit = miterLimit; this.lineDashPattern = lineDashPattern; this.dashOffset = dashOffset; this.hidden = hidden; } public String getName() { return name; } public GradientType getGradientType() { return gradientType; } public AnimatableGradientColorValue getGradientColor() { return gradientColor; } public AnimatableIntegerValue getOpacity() { return opacity; } public AnimatablePointValue getStartPoint() { return startPoint; } public AnimatablePointValue getEndPoint() { return endPoint; } public AnimatableFloatValue getWidth() { return width; } public ShapeStroke.LineCapType getCapType() { return capType; } public ShapeStroke.LineJoinType getJoinType() { return joinType; } public List<AnimatableFloatValue> getLineDashPattern() { return lineDashPattern; } @Nullable public AnimatableFloatValue getDashOffset() { return dashOffset; } public float getMiterLimit() { return miterLimit; } public boolean isHidden() { return hidden; } @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new GradientStrokeContent(drawable, layer, this); } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/model/content/GradientStroke.java
2,133
/* * Copyright 2010-2017 JetBrains s.r.o. * * 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.jetbrains.kotlin.resolve; import kotlin.annotations.jvm.Mutable; import kotlin.annotations.jvm.ReadOnly; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.psi.*; import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo; import org.jetbrains.kotlin.resolve.scopes.LexicalScope; import org.jetbrains.kotlin.types.expressions.ExpressionTypingContext; import java.util.Collection; import java.util.Map; public interface BodiesResolveContext { @ReadOnly Collection<KtFile> getFiles(); @Mutable Map<KtClassOrObject, ClassDescriptorWithResolutionScopes> getDeclaredClasses(); @Mutable Map<KtAnonymousInitializer, ClassDescriptorWithResolutionScopes> getAnonymousInitializers(); @Mutable Map<KtSecondaryConstructor, ClassConstructorDescriptor> getSecondaryConstructors(); @Mutable Map<KtScript, ClassDescriptorWithResolutionScopes> getScripts(); @Mutable Map<KtProperty, PropertyDescriptor> getProperties(); @Mutable Map<KtNamedFunction, SimpleFunctionDescriptor> getFunctions(); @Mutable Map<KtTypeAlias, TypeAliasDescriptor> getTypeAliases(); @Mutable Map<KtDestructuringDeclarationEntry, PropertyDescriptor> getDestructuringDeclarationEntries(); @Nullable LexicalScope getDeclaringScope(@NotNull KtDeclaration declaration); @NotNull DataFlowInfo getOuterDataFlowInfo(); @NotNull TopDownAnalysisMode getTopDownAnalysisMode(); @Nullable ExpressionTypingContext getLocalContext(); }
JetBrains/kotlin
compiler/frontend/src/org/jetbrains/kotlin/resolve/BodiesResolveContext.java
2,134
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Red Hat, Inc., Stephen Connolly, Tom Huybrechts * * 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 hudson.model; import static hudson.model.queue.Executables.getParentOf; import static java.util.logging.Level.FINE; import static java.util.logging.Level.FINER; import static java.util.logging.Level.SEVERE; import static java.util.logging.Level.WARNING; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.FilePath; import hudson.Functions; import hudson.Util; import hudson.model.Queue.Executable; import hudson.model.queue.SubTask; import hudson.model.queue.WorkUnit; import hudson.security.ACL; import hudson.security.ACLContext; import hudson.security.AccessControlled; import hudson.util.InterceptingProxy; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Vector; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.servlet.ServletException; import jenkins.model.CauseOfInterruption; import jenkins.model.CauseOfInterruption.UserInterruption; import jenkins.model.InterruptedBuildAction; import jenkins.model.Jenkins; import jenkins.model.queue.AsynchronousExecution; import jenkins.security.QueueItemAuthenticatorConfiguration; import jenkins.security.QueueItemAuthenticatorDescriptor; import net.jcip.annotations.GuardedBy; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.DoNotUse; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import org.kohsuke.stapler.interceptor.RequirePOST; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.Authentication; /** * Thread that executes builds. * Since 1.536, {@link Executor}s start threads on-demand. * <p>Callers should use {@link #isActive()} instead of {@link #isAlive()}. * @author Kohsuke Kawaguchi */ @ExportedBean public class Executor extends Thread implements ModelObject { protected final @NonNull Computer owner; private final Queue queue; private final ReadWriteLock lock = new ReentrantReadWriteLock(); private static final int DEFAULT_ESTIMATED_DURATION = -1; @GuardedBy("lock") private long startTime; /** * Used to track when a job was last executed. */ private final long creationTime = System.currentTimeMillis(); /** * Executor number that identifies it among other executors for the same {@link Computer}. */ private int number; /** * {@link hudson.model.Queue.Executable} being executed right now, or null if the executor is idle. */ @GuardedBy("lock") private Queue.Executable executable; /** * Calculation of estimated duration needs some time, so, it's better to cache it once executable is known */ private long executableEstimatedDuration = DEFAULT_ESTIMATED_DURATION; /** * Used to mark that the execution is continuing asynchronously even though {@link Executor} as {@link Thread} * has finished. */ @GuardedBy("lock") private AsynchronousExecution asynchronousExecution; /** * When {@link Queue} allocates a work for this executor, this field is set * and the executor is {@linkplain Thread#start() started}. */ @GuardedBy("lock") private WorkUnit workUnit; @GuardedBy("lock") private boolean started; /** * When the executor is interrupted, we allow the code that interrupted the thread to override the * result code it prefers. */ @GuardedBy("lock") private Result interruptStatus; /** * Cause of interruption. Access needs to be synchronized. */ @GuardedBy("lock") private final List<CauseOfInterruption> causes = new Vector<>(); public Executor(@NonNull Computer owner, int n) { super("Executor #" + n + " for " + owner.getDisplayName()); this.owner = owner; this.queue = Jenkins.get().getQueue(); this.number = n; } @Override public void interrupt() { if (Thread.currentThread() == this) { // If you catch an InterruptedException the "correct" options are limited to one of two choices: // 1. Propagate the exception; // 2. Restore the Thread.currentThread().interrupted() flag // The JVM locking support assumes such behaviour. // Evil Jenkins overrides the interrupt() method so that when a different thread interrupts this thread // we abort the build. // but that causes JENKINS-28690 style deadlocks when the correctly written code does // // try { // ... some long running thing ... // } catch (InterruptedException e) { // ... some tidy up // // restore interrupted flag // Thread.currentThread().interrupted(); // } // // What about why we do not set the Result.ABORTED on this branch? // That is a good question to ask, the answer is that the only time a thread should be restoring // its own interrupted flag is when that thread has already been interrupted by another thread // as such we should assume that the result has already been applied. If that assumption were // incorrect, then the Run.execute's catch (InterruptedException) block will either set the result // or have been escaped - in which case the result of the run has been sealed anyway so it does not // matter. super.interrupt(); } else { interrupt(Result.ABORTED); } } void interruptForShutdown() { interrupt(Result.ABORTED, true); } /** * Interrupt the execution, * but instead of marking the build as aborted, mark it as specified result. * * @since 1.417 */ public void interrupt(Result result) { interrupt(result, false); } private void interrupt(Result result, boolean forShutdown) { Authentication a = Jenkins.getAuthentication2(); if (a.equals(ACL.SYSTEM2)) interrupt(result, forShutdown, new CauseOfInterruption[0]); else { // worth recording who did it // avoid using User.get() to avoid deadlock. interrupt(result, forShutdown, new UserInterruption(a.getName())); } } /** * Interrupt the execution. Mark the cause and the status accordingly. */ public void interrupt(Result result, CauseOfInterruption... causes) { interrupt(result, false, causes); } private void interrupt(Result result, boolean forShutdown, CauseOfInterruption... causes) { if (LOGGER.isLoggable(FINE)) LOGGER.log(FINE, String.format("%s is interrupted(%s): %s", getDisplayName(), result, Arrays.stream(causes).map(Object::toString).collect(Collectors.joining(","))), new InterruptedException()); lock.writeLock().lock(); try { if (!started) { // not yet started, so simply dispose this owner.removeExecutor(this); return; } interruptStatus = result; for (CauseOfInterruption c : causes) { if (!this.causes.contains(c)) this.causes.add(c); } if (asynchronousExecution != null) { asynchronousExecution.interrupt(forShutdown); } else { super.interrupt(); } } finally { lock.writeLock().unlock(); } } public Result abortResult() { // this method is almost always called as a result of the current thread being interrupted // as a result we need to clean the interrupt flag so that the lock's lock method doesn't // get confused and think it was interrupted while awaiting the lock Thread.interrupted(); // we need to use a write lock as we may be repeatedly interrupted while processing and // we need the same lock as used in void interrupt(Result,boolean,CauseOfInterruption...) // JENKINS-28690 lock.writeLock().lock(); try { Result r = interruptStatus; if (r == null) r = Result.ABORTED; // this is when we programmatically throw InterruptedException instead of calling the interrupt method. return r; } finally { lock.writeLock().unlock(); } } /** * report cause of interruption and record it to the build, if available. * * @since 1.425 */ public void recordCauseOfInterruption(Run<?, ?> build, TaskListener listener) { List<CauseOfInterruption> r; // atomically get&clear causes. lock.writeLock().lock(); try { if (causes.isEmpty()) return; r = new ArrayList<>(causes); causes.clear(); } finally { lock.writeLock().unlock(); } build.addAction(new InterruptedBuildAction(r)); for (CauseOfInterruption c : r) c.print(listener); } /** * There are some cases where an executor is started but the node is removed or goes off-line before we are ready * to start executing the assigned work unit. This method is called to clear the assigned work unit so that * the {@link Queue#maintain()} method can return the item to the buildable state. * * Note: once we create the {@link Executable} we cannot unwind the state and the build will have to end up being * marked as a failure. */ private void resetWorkUnit(String reason) { StringWriter writer = new StringWriter(); try (PrintWriter pw = new PrintWriter(writer)) { pw.printf("%s grabbed %s from queue but %s %s. ", getName(), workUnit, owner.getDisplayName(), reason); if (owner.getTerminatedBy().isEmpty()) { pw.print("No termination trace available."); } else { pw.println("Termination trace follows:"); for (Computer.TerminationRequest request : owner.getTerminatedBy()) { Functions.printStackTrace(request, pw); } } } LOGGER.log(WARNING, writer.toString()); lock.writeLock().lock(); try { if (executable != null) { throw new IllegalStateException("Cannot reset the work unit after the executable has been created"); } workUnit = null; } finally { lock.writeLock().unlock(); } } @Override public void run() { if (!(owner instanceof Jenkins.MasterComputer)) { if (!owner.isOnline()) { resetWorkUnit("went off-line before the task's worker thread started"); owner.removeExecutor(this); queue.scheduleMaintenance(); return; } if (owner.getNode() == null) { resetWorkUnit("was removed before the task's worker thread started"); owner.removeExecutor(this); queue.scheduleMaintenance(); return; } } final WorkUnit workUnit; lock.writeLock().lock(); try { startTime = System.currentTimeMillis(); workUnit = this.workUnit; } finally { lock.writeLock().unlock(); } try (ACLContext ctx = ACL.as2(ACL.SYSTEM2)) { SubTask task; // transition from idle to building. // perform this state change as an atomic operation wrt other queue operations task = Queue.withLock(new Callable<>() { @Override public SubTask call() throws Exception { if (!(owner instanceof Jenkins.MasterComputer)) { if (!owner.isOnline()) { resetWorkUnit("went off-line before the task's worker thread was ready to execute"); return null; } if (owner.getNode() == null) { resetWorkUnit("was removed before the task's worker thread was ready to execute"); return null; } } // after this point we cannot unwind the assignment of the work unit, if the owner // is removed or goes off-line then the build will just have to fail. workUnit.setExecutor(Executor.this); queue.onStartExecuting(Executor.this); if (LOGGER.isLoggable(FINE)) LOGGER.log(FINE, getName() + " grabbed " + workUnit + " from queue"); SubTask task = workUnit.work; Executable executable = task.createExecutable(); if (executable == null) { String displayName = task instanceof Queue.Task ? ((Queue.Task) task).getFullDisplayName() : task.getDisplayName(); LOGGER.log(WARNING, "{0} cannot be run (for example because it is disabled)", displayName); } lock.writeLock().lock(); try { Executor.this.executable = executable; } finally { lock.writeLock().unlock(); } workUnit.setExecutable(executable); return task; } }); Executable executable; lock.readLock().lock(); try { if (this.workUnit == null) { // we called resetWorkUnit, so bail. Outer finally will remove this and schedule queue maintenance return; } executable = this.executable; } finally { lock.readLock().unlock(); } if (LOGGER.isLoggable(FINE)) LOGGER.log(FINE, getName() + " is going to execute " + executable); Throwable problems = null; try { workUnit.context.synchronizeStart(); // this code handles the behavior of null Executables returned // by tasks. In such case Jenkins starts the workUnit in order // to report results to console outputs. if (executable == null) { return; } executableEstimatedDuration = executable.getEstimatedDuration(); if (executable instanceof Actionable) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.log( FINER, "when running {0} from {1} we are copying {2} actions whereas the item currently has {3}", new Object[] { executable, workUnit.context.item, workUnit.context.actions, workUnit.context.item.getAllActions(), }); } for (Action action : workUnit.context.actions) { ((Actionable) executable).addAction(action); } } setName(getName() + " : executing " + executable); Authentication auth = workUnit.context.item.authenticate2(); LOGGER.log(FINE, "{0} is now executing {1} as {2}", new Object[] {getName(), executable, auth}); if (LOGGER.isLoggable(FINE) && auth.equals(ACL.SYSTEM2)) { // i.e., unspecified if (QueueItemAuthenticatorDescriptor.all().isEmpty()) { LOGGER.fine("no QueueItemAuthenticator implementations installed"); } else if (QueueItemAuthenticatorConfiguration.get().getAuthenticators().isEmpty()) { LOGGER.fine("no QueueItemAuthenticator implementations configured"); } else { LOGGER.log(FINE, "some QueueItemAuthenticator implementations configured but neglected to authenticate {0}", executable); } } try (ACLContext context = ACL.as2(auth)) { queue.execute(executable, task); } } catch (AsynchronousExecution x) { lock.writeLock().lock(); try { x.setExecutorWithoutCompleting(this); this.asynchronousExecution = x; } finally { lock.writeLock().unlock(); } x.maybeComplete(); } catch (Throwable e) { problems = e; } finally { boolean needFinish1; lock.readLock().lock(); try { needFinish1 = asynchronousExecution == null; } finally { lock.readLock().unlock(); } if (needFinish1) { finish1(problems); } } } catch (InterruptedException e) { LOGGER.log(FINE, getName() + " interrupted", e); // die peacefully } catch (Exception | Error e) { LOGGER.log(SEVERE, getName() + ": Unexpected executor death", e); } finally { if (asynchronousExecution == null) { finish2(); } } } private void finish1(@CheckForNull Throwable problems) { if (problems != null) { // for some reason the executor died. this is really // a bug in the code, but we don't want the executor to die, // so just leave some info and go on to build other things LOGGER.log(Level.SEVERE, "Executor threw an exception", problems); workUnit.context.abort(problems); } long time = System.currentTimeMillis() - startTime; LOGGER.log(FINE, "{0} completed {1} in {2}ms", new Object[]{getName(), executable, time}); try { workUnit.context.synchronizeEnd(this, executable, problems, time); } catch (InterruptedException e) { workUnit.context.abort(e); } finally { workUnit.setExecutor(null); } } private void finish2() { for (RuntimeException e1 : owner.getTerminatedBy()) { LOGGER.log(Level.FINE, String.format("%s termination trace", getName()), e1); } owner.removeExecutor(this); if (this instanceof OneOffExecutor) { owner.remove((OneOffExecutor) this); } executableEstimatedDuration = DEFAULT_ESTIMATED_DURATION; queue.scheduleMaintenance(); } @Restricted(NoExternalUse.class) public void completedAsynchronous(@CheckForNull Throwable error) { try { finish1(error); } finally { finish2(); } asynchronousExecution = null; } /** * Returns the current build this executor is running. * * @return * null if the executor is idle. */ public @CheckForNull Queue.Executable getCurrentExecutable() { lock.readLock().lock(); try { return executable; } finally { lock.readLock().unlock(); } } /** * Same as {@link #getCurrentExecutable} but checks {@link Item#READ}. */ @Exported(name = "currentExecutable") @Restricted(DoNotUse.class) // for exporting only public Queue.Executable getCurrentExecutableForApi() { Executable candidate = getCurrentExecutable(); return candidate instanceof AccessControlled && ((AccessControlled) candidate).hasPermission(Item.READ) ? candidate : null; } /** * Returns causes of interruption. * * @return Unmodifiable collection of causes of interruption. * @since 1.617 */ public @NonNull Collection<CauseOfInterruption> getCausesOfInterruption() { return Collections.unmodifiableCollection(causes); } /** * Returns the current {@link WorkUnit} (of {@link #getCurrentExecutable() the current executable}) * that this executor is running. * * @return * null if the executor is idle. */ @CheckForNull public WorkUnit getCurrentWorkUnit() { lock.readLock().lock(); try { return workUnit; } finally { lock.readLock().unlock(); } } /** * If {@linkplain #getCurrentExecutable() current executable} is {@link AbstractBuild}, * return the workspace that this executor is using, or null if the build hasn't gotten * to that point yet. */ public FilePath getCurrentWorkspace() { lock.readLock().lock(); try { if (executable == null) { return null; } if (executable instanceof AbstractBuild) { AbstractBuild ab = (AbstractBuild) executable; return ab.getWorkspace(); } return null; } finally { lock.readLock().unlock(); } } /** * Human readable name of the Jenkins executor. For the Java thread name use {@link #getName()}. */ @Override public String getDisplayName() { return "Executor #" + getNumber(); } /** * Gets the executor number that uniquely identifies it among * other {@link Executor}s for the same computer. * * @return * a sequential number starting from 0. */ @Exported public int getNumber() { return number; } /** * Returns true if this {@link Executor} is ready for action. */ @Exported public boolean isIdle() { lock.readLock().lock(); try { return workUnit == null && executable == null; } finally { lock.readLock().unlock(); } } /** * The opposite of {@link #isIdle()} &mdash; the executor is doing some work. */ public boolean isBusy() { lock.readLock().lock(); try { return workUnit != null || executable != null; } finally { lock.readLock().unlock(); } } /** * Check if executor is ready to accept tasks. * This method becomes the critical one since 1.536, which introduces the * on-demand creation of executor threads. Callers should use * this method instead of {@link #isAlive()}, which would be incorrect for * non-started threads or running {@link AsynchronousExecution}. * @return true if the executor is available for tasks (usually true) * @since 1.536 */ public boolean isActive() { lock.readLock().lock(); try { return !started || asynchronousExecution != null || isAlive(); } finally { lock.readLock().unlock(); } } /** * If currently running in asynchronous mode, returns that handle. * @since 1.607 */ public @CheckForNull AsynchronousExecution getAsynchronousExecution() { lock.readLock().lock(); try { return asynchronousExecution; } finally { lock.readLock().unlock(); } } /** * If this executor is running an {@link AsynchronousExecution} and that execution wants to hide the display * cell for the executor (because there is another executor displaying the job progress and we don't want to * confuse the user) then this method will return {@code false} to indicate to {@code executors.jelly} that * the executor cell should be hidden. * * @return {@code true} iff the {@code executorCell.jelly} for this {@link Executor} should be displayed in * {@code executors.jelly}. * @since 1.607 * @see AsynchronousExecution#displayCell() */ public boolean isDisplayCell() { AsynchronousExecution asynchronousExecution = getAsynchronousExecution(); return asynchronousExecution == null || asynchronousExecution.displayCell(); } /** * Returns true if this executor is waiting for a task to execute. */ public boolean isParking() { lock.readLock().lock(); try { return !started; } finally { lock.readLock().unlock(); } } /** * @deprecated no longer used */ @Deprecated public @CheckForNull Throwable getCauseOfDeath() { return null; } /** * Returns the progress of the current build in the number between 0-100. * * @return -1 * if it's impossible to estimate the progress. */ @Exported public int getProgress() { long d = executableEstimatedDuration; if (d <= 0) { return DEFAULT_ESTIMATED_DURATION; } int num = (int) (getElapsedTime() * 100 / d); if (num >= 100) { num = 99; } return num; } /** * Returns true if the current build is likely stuck. * * <p> * This is a heuristics based approach, but if the build is suspiciously taking for a long time, * this method returns true. */ @Exported public boolean isLikelyStuck() { lock.readLock().lock(); try { if (executable == null) { return false; } } finally { lock.readLock().unlock(); } long elapsed = getElapsedTime(); long d = executableEstimatedDuration; if (d >= 0) { // if it's taking 10 times longer than ETA, consider it stuck return d * 10 < elapsed; } else { // if no ETA is available, a build taking longer than a day is considered stuck return TimeUnit.MILLISECONDS.toHours(elapsed) > 24; } } public long getElapsedTime() { lock.readLock().lock(); try { return System.currentTimeMillis() - startTime; } finally { lock.readLock().unlock(); } } /** * Returns the number of milli-seconds the currently executing job spent in the queue * waiting for an available executor. This excludes the quiet period time of the job. * @since 1.440 */ public long getTimeSpentInQueue() { lock.readLock().lock(); try { return startTime - workUnit.context.item.buildableStartMilliseconds; } finally { lock.readLock().unlock(); } } /** * Gets the string that says how long since this build has started. * * @return * string like "3 minutes" "1 day" etc. */ public String getTimestampString() { return Util.getTimeSpanString(getElapsedTime()); } /** * Computes a human-readable text that shows the expected remaining time * until the build completes. */ public String getEstimatedRemainingTime() { long d = executableEstimatedDuration; if (d < 0) { return Messages.Executor_NotAvailable(); } long eta = d - getElapsedTime(); if (eta <= 0) { return Messages.Executor_NotAvailable(); } return Util.getTimeSpanString(eta); } /** * The same as {@link #getEstimatedRemainingTime()} but return * it as a number of milli-seconds. */ public long getEstimatedRemainingTimeMillis() { long d = executableEstimatedDuration; if (d < 0) { return DEFAULT_ESTIMATED_DURATION; } long eta = d - getElapsedTime(); if (eta <= 0) { return DEFAULT_ESTIMATED_DURATION; } return eta; } /** * Can't start executor like you normally start a thread. * * @see #start(WorkUnit) */ @Override public void start() { throw new UnsupportedOperationException(); } /*protected*/ void start(WorkUnit task) { lock.writeLock().lock(); try { this.workUnit = task; super.start(); started = true; } finally { lock.writeLock().unlock(); } } /** * @deprecated as of 1.489 * Use {@link #doStop()} or {@link #doStopBuild(String)}. */ @RequirePOST @Deprecated public void doStop(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { doStop().generateResponse(req, rsp, this); } /** * Stops the current build.<br> * You can use {@link #doStopBuild(String)} instead to ensure what will be * interrupted is actually what you want to interrupt. * * @since 1.489 * @see #doStopBuild(String) */ @RequirePOST public HttpResponse doStop() { return doStopBuild(null); } /** * Stops the current build, if matching the specified external id * (or no id is specified, or the current {@link Executable} is not a {@link Run}). * * @param runExtId * if not null, the externalizable id ({@link Run#getExternalizableId()}) * of the build the user expects to interrupt * @since 2.209 */ @RequirePOST @Restricted(NoExternalUse.class) public HttpResponse doStopBuild(@CheckForNull @QueryParameter(fixEmpty = true) String runExtId) { lock.writeLock().lock(); // need write lock as interrupt will change the field try { if (executable != null) { if (runExtId == null || runExtId.isEmpty() || ! (executable instanceof Run) || (runExtId.equals(((Run<?, ?>) executable).getExternalizableId()))) { final Queue.Task ownerTask = getParentOf(executable).getOwnerTask(); boolean canAbort = ownerTask.hasAbortPermission(); if (canAbort && ownerTask instanceof AccessControlled) { if (!((AccessControlled) ownerTask).hasPermission(Item.READ)) { // pretend the build does not exist return HttpResponses.forwardToPreviousPage(); } } ownerTask.checkAbortPermission(); interrupt(); } } } finally { lock.writeLock().unlock(); } return HttpResponses.forwardToPreviousPage(); } /** * @deprecated now a no-op */ @Deprecated public HttpResponse doYank() { return HttpResponses.redirectViaContextPath("/"); } /** * Checks if the current user has a permission to stop this build. */ public boolean hasStopPermission() { lock.readLock().lock(); try { return executable != null && getParentOf(executable).getOwnerTask().hasAbortPermission(); } catch (RuntimeException ex) { if (!(ex instanceof AccessDeniedException)) { // Prevents UI from exploding in the case of unexpected runtime exceptions LOGGER.log(WARNING, "Unhandled exception", ex); } return false; } finally { lock.readLock().unlock(); } } public @NonNull Computer getOwner() { return owner; } /** * Returns when this executor started or should start being idle. */ public long getIdleStartMilliseconds() { if (isIdle()) return Math.max(creationTime, owner.getConnectTime()); else { return Math.max(startTime + Math.max(0, executableEstimatedDuration), System.currentTimeMillis() + 15000); } } /** * Exposes the executor to the remote API. */ public Api getApi() { return new Api(this); } /** * Creates a proxy object that executes the callee in the context that impersonates * this executor. Useful to export an object to a remote channel. */ public <T> T newImpersonatingProxy(Class<T> type, T core) { return new InterceptingProxy() { @Override protected Object call(Object o, Method m, Object[] args) throws Throwable { final Executor old = IMPERSONATION.get(); IMPERSONATION.set(Executor.this); try { return m.invoke(o, args); } finally { IMPERSONATION.set(old); } } }.wrap(type, core); } /** * Returns the executor of the current thread or null if current thread is not an executor. */ public static @CheckForNull Executor currentExecutor() { Thread t = Thread.currentThread(); if (t instanceof Executor) return (Executor) t; return IMPERSONATION.get(); } /** * Finds the executor currently running a given process. * @param executable a possibly running executable * @return the executor (possibly a {@link OneOffExecutor}) whose {@link Executor#getCurrentExecutable} matches that, * or null if it could not be found (for example because the execution has already completed) * @since 1.607 */ @CheckForNull public static Executor of(Executable executable) { Jenkins jenkins = Jenkins.getInstanceOrNull(); // TODO confirm safe to assume non-null and use getInstance() if (jenkins == null) { return null; } for (Computer computer : jenkins.getComputers()) { for (Executor executor : computer.getAllExecutors()) { if (executor.getCurrentExecutable() == executable) { return executor; } } } return null; } /** * @deprecated call {@link Executable#getEstimatedDuration} directly */ @Deprecated public static long getEstimatedDurationFor(Executable e) { return e == null ? DEFAULT_ESTIMATED_DURATION : e.getEstimatedDuration(); } /** * Mechanism to allow threads (in particular the channel request handling threads) to * run on behalf of {@link Executor}. */ private static final ThreadLocal<Executor> IMPERSONATION = new ThreadLocal<>(); private static final Logger LOGGER = Logger.getLogger(Executor.class.getName()); }
jenkinsci/jenkins
core/src/main/java/hudson/model/Executor.java
2,135
package mindustry.game; import arc.*; import arc.math.*; import arc.struct.Bits; import arc.struct.*; import arc.util.*; import mindustry.*; import mindustry.annotations.Annotations.*; import mindustry.core.*; import mindustry.game.EventType.*; import mindustry.gen.*; import mindustry.io.SaveFileReader.*; import mindustry.io.*; import mindustry.world.meta.*; import java.io.*; import static mindustry.Vars.*; public final class FogControl implements CustomChunk{ private static volatile int ww, wh; private static final int dynamicUpdateInterval = 1000 / 25; //25 FPS private static final Object notifyStatic = new Object(), notifyDynamic = new Object(); /** indexed by team */ private volatile @Nullable FogData[] fog; private final LongSeq staticEvents = new LongSeq(); private final LongSeq dynamicEventQueue = new LongSeq(), unitEventQueue = new LongSeq(); /** access must be synchronized; accessed from both threads */ private final LongSeq dynamicEvents = new LongSeq(100); private @Nullable Thread staticFogThread; private @Nullable Thread dynamicFogThread; private boolean justLoaded = false; private boolean loadedStatic = false; public FogControl(){ Events.on(ResetEvent.class, e -> { stop(); }); Events.on(WorldLoadEvent.class, e -> { stop(); loadedStatic = false; justLoaded = true; ww = world.width(); wh = world.height(); //all old buildings have static light scheduled around them if(state.rules.fog && state.rules.staticFog){ pushStaticBlocks(true); //force draw all static stuff immediately updateStatic(); loadedStatic = true; } }); Events.on(TileChangeEvent.class, event -> { if(state.rules.fog && event.tile.build != null && event.tile.isCenter() && !event.tile.build.team.isOnlyAI() && event.tile.block().flags.contains(BlockFlag.hasFogRadius)){ var data = data(event.tile.team()); if(data != null){ data.dynamicUpdated = true; } if(state.rules.staticFog){ synchronized(staticEvents){ //TODO event per team? pushEvent(FogEvent.get(event.tile.x, event.tile.y, Mathf.round(event.tile.build.fogRadius()), event.tile.build.team.id), false); } } } }); //on tile removed, dynamic fog goes away Events.on(TilePreChangeEvent.class, e -> { if(state.rules.fog && e.tile.build != null && !e.tile.build.team.isOnlyAI() && e.tile.block().flags.contains(BlockFlag.hasFogRadius)){ var data = data(e.tile.team()); if(data != null){ data.dynamicUpdated = true; } } }); //unit dead -> fog updates Events.on(UnitDestroyEvent.class, e -> { if(state.rules.fog && fog[e.unit.team.id] != null){ fog[e.unit.team.id].dynamicUpdated = true; } }); SaveVersion.addCustomChunk("static-fog-data", this); } public @Nullable Bits getDiscovered(Team team){ return fog == null || fog[team.id] == null ? null : fog[team.id].staticData; } public boolean isDiscovered(Team team, int x, int y){ if(!state.rules.staticFog || !state.rules.fog || team == null || team.isAI()) return true; var data = getDiscovered(team); if(data == null) return false; if(x < 0 || y < 0 || x >= ww || y >= wh) return false; return data.get(x + y * ww); } public boolean isVisible(Team team, float x, float y){ return isVisibleTile(team, World.toTile(x), World.toTile(y)); } public boolean isVisibleTile(Team team, int x, int y){ if(!state.rules.fog|| team == null || team.isAI()) return true; var data = data(team); if(data == null) return false; if(x < 0 || y < 0 || x >= ww || y >= wh) return false; return data.read.get(x + y * ww); } public void resetFog(){ fog = null; } @Nullable FogData data(Team team){ return fog == null || fog[team.id] == null ? null : fog[team.id]; } void stop(){ fog = null; //I don't care whether the fog thread crashes here, it's about to die anyway staticEvents.clear(); if(staticFogThread != null){ staticFogThread.interrupt(); staticFogThread = null; } dynamicEvents.clear(); if(dynamicFogThread != null){ dynamicFogThread.interrupt(); dynamicFogThread = null; } } /** @param initial whether this is the initial update; if true, does not update renderer */ void pushStaticBlocks(boolean initial){ if(fog == null) fog = new FogData[256]; synchronized(staticEvents){ for(var build : Groups.build){ if(build.block.flags.contains(BlockFlag.hasFogRadius)){ if(fog[build.team.id] == null){ fog[build.team.id] = new FogData(); } pushEvent(FogEvent.get(build.tile.x, build.tile.y, Mathf.round(build.fogRadius()), build.team.id), initial); } } } } /** @param skipRender whether the event is passed to the fog renderer */ void pushEvent(long event, boolean skipRender){ if(!state.rules.staticFog) return; staticEvents.add(event); if(!skipRender && !headless && FogEvent.team(event) == Vars.player.team().id){ renderer.fog.handleEvent(event); } } public void forceUpdate(Team team, Building build){ if(state.rules.fog && fog[team.id] != null){ fog[team.id].dynamicUpdated = true; if(state.rules.staticFog){ synchronized(staticEvents){ pushEvent(FogEvent.get(build.tile.x, build.tile.y, Mathf.round(build.fogRadius()), build.team.id), false); } } } } public void update(){ if(fog == null){ fog = new FogData[256]; } //force update static if(state.rules.staticFog && !loadedStatic){ pushStaticBlocks(false); updateStatic(); loadedStatic = true; } if(staticFogThread == null){ staticFogThread = new StaticFogThread(); staticFogThread.setPriority(Thread.NORM_PRIORITY - 1); staticFogThread.setDaemon(true); staticFogThread.start(); } if(dynamicFogThread == null){ dynamicFogThread = new DynamicFogThread(); dynamicFogThread.setPriority(Thread.NORM_PRIORITY - 1); dynamicFogThread.setDaemon(true); dynamicFogThread.start(); } //clear to prepare for queuing fog radius from units and buildings dynamicEventQueue.clear(); for(var team : state.teams.present){ //AI teams do not have fog if(!team.team.isOnlyAI()){ //separate for each team unitEventQueue.clear(); FogData data = fog[team.team.id]; if(data == null){ data = fog[team.team.id] = new FogData(); } synchronized(staticEvents){ //TODO slow? for(var unit : team.units){ int tx = unit.tileX(), ty = unit.tileY(), pos = tx + ty * ww; if(unit.type.fogRadius <= 0f) continue; long event = FogEvent.get(tx, ty, (int)unit.type.fogRadius, team.team.id); //always update the dynamic events, but only *flush* the results when necessary? unitEventQueue.add(event); if(unit.lastFogPos != pos){ pushEvent(event, false); unit.lastFogPos = pos; data.dynamicUpdated = true; } } } //if it's time for an update, flush *everything* onto the update queue if(data.dynamicUpdated && Time.timeSinceMillis(data.lastDynamicMs) > dynamicUpdateInterval){ data.dynamicUpdated = false; data.lastDynamicMs = Time.millis(); //add building updates for(var build : indexer.getFlagged(team.team, BlockFlag.hasFogRadius)){ dynamicEventQueue.add(FogEvent.get(build.tile.x, build.tile.y, Mathf.round(build.fogRadius()), build.team.id)); } //add unit updates dynamicEventQueue.addAll(unitEventQueue); } } } if(dynamicEventQueue.size > 0){ //flush unit events over when something happens synchronized(dynamicEvents){ dynamicEvents.clear(); dynamicEvents.addAll(dynamicEventQueue); } dynamicEventQueue.clear(); //force update so visibility doesn't have a pop-in if(justLoaded){ updateDynamic(new Bits(256)); justLoaded = false; } //notify that it's time for rendering //TODO this WILL block until it is done rendering, which is inherently problematic. synchronized(notifyDynamic){ notifyDynamic.notify(); } } //wake up, it's time to draw some circles if(state.rules.staticFog && staticEvents.size > 0 && staticFogThread != null){ synchronized(notifyStatic){ notifyStatic.notify(); } } } class StaticFogThread extends Thread{ StaticFogThread(){ super("StaticFogThread"); } @Override public void run(){ while(true){ try{ synchronized(notifyStatic){ try{ //wait until an event happens notifyStatic.wait(); }catch(InterruptedException e){ //end thread return; } } updateStatic(); //ignore, don't want to crash this thread }catch(Exception e){} } } } void updateStatic(){ //I really don't like synchronizing here, but there should be *some* performance benefit at least synchronized(staticEvents){ int size = staticEvents.size; for(int i = 0; i < size; i++){ long event = staticEvents.items[i]; int x = FogEvent.x(event), y = FogEvent.y(event), rad = FogEvent.radius(event), team = FogEvent.team(event); var data = fog[team]; if(data != null){ circle(data.staticData, x, y, rad); } } staticEvents.clear(); } } class DynamicFogThread extends Thread{ final Bits cleared = new Bits(); DynamicFogThread(){ super("DynamicFogThread"); } @Override public void run(){ while(true){ try{ synchronized(notifyDynamic){ try{ //wait until an event happens notifyDynamic.wait(); }catch(InterruptedException e){ //end thread return; } } updateDynamic(cleared); //ignore, don't want to crash this thread }catch(Exception e){ //log for debugging e.printStackTrace(); } } } } void updateDynamic(Bits cleared){ cleared.clear(); //ugly sync synchronized(dynamicEvents){ int size = dynamicEvents.size; //draw step for(int i = 0; i < size; i++){ long event = dynamicEvents.items[i]; int x = FogEvent.x(event), y = FogEvent.y(event), rad = FogEvent.radius(event), team = FogEvent.team(event); if(rad <= 0) continue; var data = fog[team]; if(data != null){ //clear the buffer, since it is being re-drawn if(!cleared.get(team)){ cleared.set(team); data.write.clear(); } //radius is always +1 to keep up with visuals circle(data.write, x, y, rad + 1); } } dynamicEvents.clear(); } //swap step, no need for synchronization or anything for(int i = 0; i < 256; i++){ if(cleared.get(i)){ var data = fog[i]; //swap buffers, flushing the data that was just drawn Bits temp = data.read; data.read = data.write; data.write = temp; } } } @Override public void write(DataOutput stream) throws IOException{ int used = 0; for(int i = 0; i < 256; i++){ if(fog[i] != null) used ++; } stream.writeByte(used); stream.writeShort(world.width()); stream.writeShort(world.height()); for(int i = 0; i < 256; i++){ if(fog[i] != null){ stream.writeByte(i); Bits data = fog[i].staticData; int size = ww * wh; int pos = 0; while(pos < size){ int consecutives = 0; boolean cur = data.get(pos); while(consecutives < 127 && pos < size){ if(cur != data.get(pos)){ break; } consecutives ++; pos ++; } int mask = (cur ? 0b1000_0000 : 0); stream.write(mask | (consecutives)); } } } } @Override public void read(DataInput stream) throws IOException{ if(fog == null) fog = new FogData[256]; int teams = stream.readUnsignedByte(); int w = stream.readShort(), h = stream.readShort(); int len = w * h; ww = w; wh = h; for(int ti = 0; ti < teams; ti++){ int team = stream.readUnsignedByte(); fog[team] = new FogData(); int pos = 0; Bits bools = fog[team].staticData; while(pos < len){ int data = stream.readByte() & 0xff; boolean sign = (data & 0b1000_0000) != 0; int consec = data & 0b0111_1111; if(sign){ bools.set(pos, pos + consec); pos += consec; }else{ pos += consec; } } } } @Override public boolean shouldWrite(){ return state.rules.fog && state.rules.staticFog && fog != null; } static void circle(Bits arr, int x, int y, int radius){ int f = 1 - radius; int ddFx = 1, ddFy = -2 * radius; int px = 0, py = radius; hline(arr, x, x, y + radius); hline(arr, x, x, y - radius); hline(arr, x - radius, x + radius, y); while(px < py){ if(f >= 0){ py--; ddFy += 2; f += ddFy; } px++; ddFx += 2; f += ddFx; hline(arr, x - px, x + px, y + py); hline(arr, x - px, x + px, y - py); hline(arr, x - py, x + py, y + px); hline(arr, x - py, x + py, y - px); } } static void hline(Bits arr, int x1, int x2, int y){ if(y < 0 || y >= wh) return; int tmp; if(x1 > x2){ tmp = x1; x1 = x2; x2 = tmp; } if(x1 >= ww) return; if(x2 < 0) return; if(x1 < 0) x1 = 0; if(x2 >= ww) x2 = ww - 1; x2++; int off = y * ww; arr.set(off + x1, off + x2); } static class FogData{ /** dynamic double-buffered data for dynamic (live) coverage */ volatile Bits read, write; /** static map exploration fog*/ final Bits staticData; /** last dynamic update timestamp. */ long lastDynamicMs = 0; /** if true, a dynamic fog update must be scheduled. */ boolean dynamicUpdated = true; FogData(){ int len = ww * wh; read = new Bits(len); write = new Bits(len); staticData = new Bits(len); } } @Struct class FogEventStruct{ @StructField(16) int x; @StructField(16) int y; @StructField(16) int radius; @StructField(8) int team; } }
Anuken/Mindustry
core/src/mindustry/game/FogControl.java
2,137
package org.telegram.ui; import android.app.Dialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.core.graphics.ColorUtils; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.R; import org.telegram.messenger.Utilities; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.FillLastLinearLayoutManager; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.Premium.PremiumGradient; import org.telegram.ui.Components.Premium.StarParticlesView; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.SimpleThemeDescription; import java.util.ArrayList; public abstract class GradientHeaderActivity extends BaseFragment { private final PremiumGradient.PremiumGradientTools gradientTools = new PremiumGradient.PremiumGradientTools( Theme.key_premiumGradientBackground1, Theme.key_premiumGradientBackground2, Theme.key_premiumGradientBackground3, Theme.key_premiumGradientBackground4) { @Override protected int getThemeColorByKey(int key) { return Theme.getDefaultColor(key); } }; private final PremiumGradient.PremiumGradientTools darkGradientTools = new PremiumGradient.PremiumGradientTools( Theme.key_premiumGradientBackground1, Theme.key_premiumGradientBackground2, Theme.key_premiumGradientBackground3, Theme.key_premiumGradientBackground4) { @Override protected int getThemeColorByKey(int key) { return Theme.getDefaultColor(key); } }; protected RecyclerListView listView; private Drawable shadowDrawable; private StarParticlesView particlesView; private boolean isDialogVisible; private boolean inc; private float progress; private int currentYOffset; private FrameLayout contentView; private float totalProgress; private final Bitmap gradientTextureBitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); private final Canvas gradientCanvas = new Canvas(gradientTextureBitmap); private float progressToFull; public BackgroundView backgroundView; protected FillLastLinearLayoutManager layoutManager; private boolean isLandscapeMode; private int statusBarHeight; private int firstViewHeight; private final Paint headerBgPaint = new Paint(); { darkGradientTools.darkColors = true; } abstract protected RecyclerView.Adapter<?> createAdapter(); protected void configureHeader(CharSequence title, CharSequence subTitle, View aboveTitleView, View underSubTitleView) { backgroundView.setData(title, subTitle, aboveTitleView, underSubTitleView); } protected View getHeader(Context context) { return new View(context) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (isLandscapeMode) { firstViewHeight = statusBarHeight + actionBar.getMeasuredHeight() - AndroidUtilities.dp(16); } else { int h = AndroidUtilities.dp(140) + statusBarHeight; if (backgroundView.getMeasuredHeight() + AndroidUtilities.dp(24) > h) { h = backgroundView.getMeasuredHeight() + AndroidUtilities.dp(24); } firstViewHeight = h; } super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(firstViewHeight, MeasureSpec.EXACTLY)); } }; } @Override public boolean isSwipeBackEnabled(MotionEvent event) { return true; } @Override public View createView(Context context) { hasOwnBackground = true; Rect padding = new Rect(); shadowDrawable = ContextCompat.getDrawable(context, R.drawable.sheet_shadow_round).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); shadowDrawable.getPadding(padding); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { statusBarHeight = AndroidUtilities.isTablet() ? 0 : AndroidUtilities.statusBarHeight; } contentView = new FrameLayout(context) { int lastSize; boolean topInterceptedTouch; boolean bottomInterceptedTouch; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { isLandscapeMode = MeasureSpec.getSize(widthMeasureSpec) > MeasureSpec.getSize(heightMeasureSpec); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { statusBarHeight = AndroidUtilities.isTablet() ? 0 : AndroidUtilities.statusBarHeight; } backgroundView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); particlesView.getLayoutParams().height = backgroundView.getMeasuredHeight(); layoutManager.setAdditionalHeight(actionBar.getMeasuredHeight()); layoutManager.setMinimumLastViewHeight(0); super.onMeasure(widthMeasureSpec, heightMeasureSpec); int size = getMeasuredHeight() + getMeasuredWidth() << 16; if (lastSize != size) { updateBackgroundImage(); } } @Override public boolean dispatchTouchEvent(MotionEvent ev) { float topX = backgroundView.getX() + backgroundView.aboveTitleLayout.getX(); float topY = backgroundView.getY() + backgroundView.aboveTitleLayout.getY(); boolean isClickableTop = backgroundView.aboveTitleLayout.isClickable(); AndroidUtilities.rectTmp.set(topX, topY, topX + backgroundView.aboveTitleLayout.getMeasuredWidth(), topY + backgroundView.aboveTitleLayout.getMeasuredHeight()); if ((AndroidUtilities.rectTmp.contains(ev.getX(), ev.getY()) || topInterceptedTouch) && !listView.scrollingByUser && isClickableTop && progressToFull < 1) { ev.offsetLocation(-topX, -topY); if (ev.getAction() == MotionEvent.ACTION_DOWN || ev.getAction() == MotionEvent.ACTION_MOVE) { topInterceptedTouch = true; } else if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) { topInterceptedTouch = false; } backgroundView.aboveTitleLayout.dispatchTouchEvent(ev); return true; } float bottomX = backgroundView.getX() + backgroundView.belowSubTitleLayout.getX(); float bottomY = backgroundView.getY() + backgroundView.belowSubTitleLayout.getY(); AndroidUtilities.rectTmp.set(bottomX, bottomY, bottomX + backgroundView.belowSubTitleLayout.getMeasuredWidth(), bottomY + backgroundView.belowSubTitleLayout.getMeasuredHeight()); if ((AndroidUtilities.rectTmp.contains(ev.getX(), ev.getY()) || bottomInterceptedTouch) && !listView.scrollingByUser && progressToFull < 1) { ev.offsetLocation(-bottomX, -bottomY); if (ev.getAction() == MotionEvent.ACTION_DOWN) { bottomInterceptedTouch = true; } else if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) { bottomInterceptedTouch = false; } backgroundView.belowSubTitleLayout.dispatchTouchEvent(ev); if (bottomInterceptedTouch) { return true; } } return super.dispatchTouchEvent(ev); } @Override protected void dispatchDraw(Canvas canvas) { if (!isDialogVisible) { if (inc) { progress += 16f / 1000f; if (progress > 3) { inc = false; } } else { progress -= 16f / 1000f; if (progress < 1) { inc = true; } } } View firstView = null; if (listView.getLayoutManager() != null) { firstView = listView.getLayoutManager().findViewByPosition(0); } currentYOffset = firstView == null ? 0 : firstView.getBottom(); int h = actionBar.getBottom() + AndroidUtilities.dp(16); totalProgress = (1f - (currentYOffset - h) / (float) (firstViewHeight - h)); totalProgress = Utilities.clamp(totalProgress, 1f, 0f); int maxTop = actionBar.getBottom() + AndroidUtilities.dp(16); if (currentYOffset < maxTop) { currentYOffset = maxTop; } float oldProgress = progressToFull; progressToFull = 0; if (currentYOffset < maxTop + AndroidUtilities.dp(30)) { progressToFull = (maxTop + AndroidUtilities.dp(30) - currentYOffset) / (float) AndroidUtilities.dp(30); } if (isLandscapeMode) { progressToFull = 1f; totalProgress = 1f; } if (oldProgress != progressToFull) { listView.invalidate(); } float fromTranslation = currentYOffset - (actionBar.getMeasuredHeight() + backgroundView.getMeasuredHeight() - statusBarHeight) + AndroidUtilities.dp(16); float toTranslation = ((actionBar.getMeasuredHeight() - statusBarHeight - backgroundView.titleView.getMeasuredHeight()) / 2f) + statusBarHeight - backgroundView.getTop() - backgroundView.titleView.getTop(); float translationsY = Math.max(toTranslation, fromTranslation); float iconTranslationsY = -translationsY / 4f + AndroidUtilities.dp(16); backgroundView.setTranslationY(translationsY); backgroundView.aboveTitleLayout.setTranslationY(iconTranslationsY + AndroidUtilities.dp(16)); float s = 0.6f + (1f - totalProgress) * 0.4f; float alpha = 1f - (totalProgress > 0.5f ? (totalProgress - 0.5f) / 0.5f : 0f); backgroundView.aboveTitleLayout.setScaleX(s); backgroundView.aboveTitleLayout.setScaleY(s); backgroundView.aboveTitleLayout.setAlpha(alpha); backgroundView.belowSubTitleLayout.setAlpha(alpha); backgroundView.subtitleView.setAlpha(alpha); particlesView.setAlpha(1f - totalProgress); particlesView.setTranslationY(backgroundView.getY() + backgroundView.aboveTitleLayout.getY() - AndroidUtilities.dp(30)); float toX = AndroidUtilities.dp(72) - backgroundView.titleView.getLeft(); float f = totalProgress > 0.3f ? (totalProgress - 0.3f) / 0.7f : 0f; backgroundView.titleView.setTranslationX(toX * (1f - CubicBezierInterpolator.EASE_OUT_QUINT.getInterpolation(1 - f))); if (!isDialogVisible) { invalidate(); } gradientTools.gradientMatrix(0, 0, getMeasuredWidth(), getMeasuredHeight(), -getMeasuredWidth() * 0.1f * progress, 0); canvas.drawRect(0, 0, getMeasuredWidth(), currentYOffset + AndroidUtilities.dp(20), gradientTools.paint); int titleColor = ColorUtils.blendARGB(getThemedColor(Theme.key_dialogTextBlack), getThemedColor(Theme.key_premiumGradientBackgroundOverlay), alpha); actionBar.getBackButton().setColorFilter(titleColor); backgroundView.titleView.setTextColor(titleColor); headerBgPaint.setAlpha((int) (255 * (1f - alpha))); setLightStatusBar(Theme.blendOver(Theme.getColor(Theme.key_premiumGradientBackground4, resourceProvider), headerBgPaint.getColor())); canvas.drawRect(0, 0, getMeasuredWidth(), currentYOffset + AndroidUtilities.dp(20), headerBgPaint); super.dispatchDraw(canvas); parentLayout.drawHeaderShadow(canvas, alpha <= 0.01f ? 255 : 0, actionBar.getMeasuredHeight()); } private Boolean lightStatusBar; private void setLightStatusBar(int color) { boolean colorLight = AndroidUtilities.computePerceivedBrightness(color) >= .721f; if (lightStatusBar == null || lightStatusBar != colorLight) { AndroidUtilities.setLightStatusBar(fragmentView, lightStatusBar = colorLight); } } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { if (child == listView) { canvas.save(); canvas.clipRect(0, actionBar.getBottom(), getMeasuredWidth(), getMeasuredHeight()); super.drawChild(canvas, child, drawingTime); canvas.restore(); return true; } return super.drawChild(canvas, child, drawingTime); } }; contentView.setFitsSystemWindows(true); listView = new RecyclerListView(context) { @Override public void onDraw(Canvas canvas) { shadowDrawable.setBounds((int) (-padding.left - AndroidUtilities.dp(16) * progressToFull), currentYOffset - padding.top - AndroidUtilities.dp(16), (int) (getMeasuredWidth() + padding.right + AndroidUtilities.dp(16) * progressToFull), getMeasuredHeight()); shadowDrawable.draw(canvas); super.onDraw(canvas); } }; listView.setLayoutManager(layoutManager = new FillLastLinearLayoutManager(context, AndroidUtilities.dp(68) + statusBarHeight - AndroidUtilities.dp(16), listView)); layoutManager.setFixedLastItemHeight(); listView.setAdapter(createAdapter()); listView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE) { int maxTop = actionBar.getBottom() + AndroidUtilities.dp(16); if (totalProgress > 0.5f) { listView.smoothScrollBy(0, currentYOffset - maxTop); } else { View firstView = null; if (listView.getLayoutManager() != null) { firstView = listView.getLayoutManager().findViewByPosition(0); } if (firstView != null && firstView.getTop() < 0) { listView.smoothScrollBy(0, firstView.getTop()); } } } } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); contentView.invalidate(); } }); backgroundView = new BackgroundView(context) { @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return true; } }; particlesView = new StarParticlesView(context) { @Override protected void configure() { drawable = new Drawable(50) { @Override protected int getPathColor() { return ColorUtils.setAlphaComponent(Theme.getDefaultColor(colorKey), 200); } }; drawable.type = 100; drawable.roundEffect = false; drawable.useRotate = false; drawable.useBlur = true; drawable.checkBounds = true; drawable.isCircle = false; drawable.size1 = 4; drawable.k1 = drawable.k2 = drawable.k3 = 0.98f; drawable.init(); } @Override protected int getStarsRectWidth() { return getMeasuredWidth(); } }; contentView.addView(particlesView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); contentView.addView(backgroundView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); contentView.addView(listView); fragmentView = contentView; actionBar.setBackground(null); actionBar.setCastShadows(false); actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } } }); actionBar.setForceSkipTouches(true); updateColors(); return fragmentView; } public Paint setDarkGradientLocation(float x, float y) { darkGradientTools.gradientMatrix(0, 0, contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), -x - (contentView.getMeasuredWidth() * 0.1f * progress), -y); return darkGradientTools.paint; } @Override public boolean isActionBarCrossfadeEnabled() { return false; } private void updateBackgroundImage() { if (contentView.getMeasuredWidth() == 0 || contentView.getMeasuredHeight() == 0 || backgroundView == null) { return; } gradientTools.gradientMatrix(0, 0, contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), 0, 0); gradientCanvas.save(); gradientCanvas.scale(100f / contentView.getMeasuredWidth(), 100f / contentView.getMeasuredHeight()); gradientCanvas.drawRect(0, 0, contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), gradientTools.paint); gradientCanvas.restore(); } @Override public Dialog showDialog(Dialog dialog) { Dialog d = super.showDialog(dialog); updateDialogVisibility(d != null); return d; } @Override protected void onDialogDismiss(Dialog dialog) { super.onDialogDismiss(dialog); updateDialogVisibility(false); } protected void updateDialogVisibility(boolean isVisible) { if (isVisible != isDialogVisible) { isDialogVisible = isVisible; particlesView.setPaused(isVisible); contentView.invalidate(); } } private void updateColors() { if (backgroundView == null || actionBar == null) { return; } headerBgPaint.setColor(getThemedColor(Theme.key_dialogBackground)); actionBar.setItemsColor(Theme.getColor(Theme.key_premiumGradientBackgroundOverlay), false); actionBar.setItemsBackgroundColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_premiumGradientBackgroundOverlay), 60), false); particlesView.drawable.updateColors(); if (backgroundView != null) { backgroundView.titleView.setTextColor(Theme.getColor(Theme.key_premiumGradientBackgroundOverlay)); backgroundView.subtitleView.setTextColor(Theme.getColor(Theme.key_premiumGradientBackgroundOverlay)); } updateBackgroundImage(); } @Override public ArrayList<ThemeDescription> getThemeDescriptions() { return SimpleThemeDescription.createThemeDescriptions(this::updateColors, Theme.key_premiumGradient1, Theme.key_premiumGradient2, Theme.key_premiumGradient3, Theme.key_premiumGradient4, Theme.key_premiumGradientBackground1, Theme.key_premiumGradientBackground2, Theme.key_premiumGradientBackground3, Theme.key_premiumGradientBackground4, Theme.key_premiumGradientBackgroundOverlay, Theme.key_premiumStarGradient1, Theme.key_premiumStarGradient2, Theme.key_premiumStartSmallStarsColor, Theme.key_premiumStartSmallStarsColor2 ); } @Override public boolean isLightStatusBar() { return false; } @Override public void onResume() { super.onResume(); particlesView.setPaused(false); } @Override public void onPause() { super.onPause(); if (particlesView != null) { particlesView.setPaused(true); } } protected static class BackgroundView extends LinearLayout { private final TextView titleView; private final TextView subtitleView; private final FrameLayout aboveTitleLayout; private final FrameLayout belowSubTitleLayout; public BackgroundView(Context context) { super(context); setOrientation(VERTICAL); aboveTitleLayout = new FrameLayout(context); addView(aboveTitleLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL)); aboveTitleLayout.setClipChildren(false); setClipChildren(false); titleView = new TextView(context); titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 22); titleView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); titleView.setGravity(Gravity.CENTER_HORIZONTAL); addView(titleView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, 0, Gravity.CENTER_HORIZONTAL, 16, 20, 16, 0)); subtitleView = new TextView(context); subtitleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); subtitleView.setLineSpacing(AndroidUtilities.dp(2), 1f); subtitleView.setGravity(Gravity.CENTER_HORIZONTAL); addView(subtitleView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 24, 7, 24, 0)); belowSubTitleLayout = new FrameLayout(context); addView(belowSubTitleLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL)); belowSubTitleLayout.setClipChildren(false); } public void setData(CharSequence title, CharSequence subTitle, View aboveTitleView, View underSubTitleView) { titleView.setText(title); subtitleView.setText(subTitle); if (aboveTitleView != null) { aboveTitleLayout.removeAllViews(); aboveTitleLayout.addView(aboveTitleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL)); } if (underSubTitleView != null) { belowSubTitleLayout.removeAllViews(); belowSubTitleLayout.addView(underSubTitleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL)); } requestLayout(); } } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/GradientHeaderActivity.java
2,138
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for (int i=0; i<=n; i++){ String s = sc.nextLine(); // System.out.println(s); String[] xynum = s.split(" "); // System.out.println(xynum[0]); int x, y; try{ x = Integer.parseInt(xynum[0]); }catch(NumberFormatException ex){ // handle your exception continue; } try{ y = Integer.valueOf(xynum[1]); }catch(NumberFormatException ex){ // handle your exception continue; } // System.out.println((Helper(xynum[2].substring(0,2),x))); for (int j=1; j<xynum[2].length(); j++){ if (Helper(xynum[2].substring(0,j),x) == Helper(xynum[2].substring(j,xynum[2].length()),y)){ System.out.println(Helper(xynum[2].substring(0,j),x)); } } // System.out.println(Helper("111", 2)); // System.out.println(s); // System.out.println(res); } } private static int Helper(String s, int k) { int res = 0; for (int i=s.length()-1;i>=0;i--){ char chr = s.charAt(i); int tmp; if (chr == 'A') { tmp = 10; }else if(chr == 'B') { tmp = 11; }else if(chr == 'C') { tmp = 12; }else if(chr == 'D') { tmp = 13; }else if(chr == 'E') { tmp = 14; }else if(chr == 'F') { tmp = 15; } else{ tmp = Integer.parseInt(Character.toString(chr)); } // System.out.println("tmp"+tmp); res += tmp * Math.pow(k, s.length()-1-i); // System.out.println("res"+res); } return res; } } /* 1 ABCDE */
apachecn/Interview
src/其他/wangyihuyudierti.java
2,139
/* * Copyright 2010-2015 JetBrains s.r.o. * * 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.jetbrains.kotlin.codegen; import org.jetbrains.annotations.TestOnly; public class ClassBuilderMode { public final boolean generateBodies; public final boolean generateMetadata; public final boolean generateSourceRetentionAnnotations; public final boolean generateMultiFileFacadePartClasses; public final boolean mightBeIncorrectCode; private ClassBuilderMode( boolean generateBodies, boolean generateMetadata, boolean generateSourceRetentionAnnotations, boolean generateMultiFileFacadePartClasses, boolean mightBeIncorrectCode ) { this.generateBodies = generateBodies; this.generateMetadata = generateMetadata; this.generateSourceRetentionAnnotations = generateSourceRetentionAnnotations; this.generateMultiFileFacadePartClasses = generateMultiFileFacadePartClasses; this.mightBeIncorrectCode = mightBeIncorrectCode; } /** * Full function bodies */ public final static ClassBuilderMode FULL = new ClassBuilderMode( /* bodies = */ true, /* metadata = */ true, /* sourceRetention = */ false, /* generateMultiFileFacadePartClasses = */ true, /* mightBeIncorrectCode = */ false); /** * Generating light classes: Only function signatures */ public final static ClassBuilderMode LIGHT_CLASSES = new ClassBuilderMode( /* bodies = */ false, /* metadata = */ false, /* sourceRetention = */ true, /* generateMultiFileFacadePartClasses = */ false, /* mightBeIncorrectCode = */ true); /** * Function signatures + metadata (to support incremental compilation with kapt) */ public final static ClassBuilderMode KAPT3 = new ClassBuilderMode( /* bodies = */ false, /* metadata = */ true, /* sourceRetention = */ true, /* generateMultiFileFacadePartClasses = */ true, /* mightBeIncorrectCode = */ true); private final static ClassBuilderMode LIGHT_ANALYSIS_FOR_TESTS = new ClassBuilderMode( /* bodies = */ false, /* metadata = */ true, /* sourceRetention = */ false, /* generateMultiFileFacadePartClasses = */ true, /* mightBeIncorrectCode = */ true); @TestOnly public static ClassBuilderMode getLightAnalysisForTests() { return LIGHT_ANALYSIS_FOR_TESTS; } }
JetBrains/kotlin
compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBuilderMode.java
2,140
/* * 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.react.bridge.queue; import android.os.Looper; import android.os.Process; import android.os.SystemClock; import android.util.Pair; import com.facebook.common.logging.FLog; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.bridge.AssertionException; import com.facebook.react.bridge.SoftAssertions; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.common.ReactConstants; import com.facebook.react.common.futures.SimpleSettableFuture; import java.util.concurrent.Callable; import java.util.concurrent.Future; /** Encapsulates a Thread that has a {@link Looper} running on it that can accept Runnables. */ @DoNotStrip public class MessageQueueThreadImpl implements MessageQueueThread { private final String mName; private final Looper mLooper; private final MessageQueueThreadHandler mHandler; private final String mAssertionErrorMessage; private MessageQueueThreadPerfStats mPerfStats; private volatile boolean mIsFinished = false; private MessageQueueThreadImpl( String name, Looper looper, QueueThreadExceptionHandler exceptionHandler) { this(name, looper, exceptionHandler, null); } private MessageQueueThreadImpl( String name, Looper looper, QueueThreadExceptionHandler exceptionHandler, MessageQueueThreadPerfStats stats) { mName = name; mLooper = looper; mHandler = new MessageQueueThreadHandler(looper, exceptionHandler); mPerfStats = stats; mAssertionErrorMessage = "Expected to be called from the '" + getName() + "' thread!"; } /** * Runs the given Runnable on this Thread. It will be submitted to the end of the event queue even * if it is being submitted from the same queue Thread. */ @DoNotStrip @Override public boolean runOnQueue(Runnable runnable) { if (mIsFinished) { FLog.w( ReactConstants.TAG, "Tried to enqueue runnable on already finished thread: '" + getName() + "... dropping Runnable."); return false; } mHandler.post(runnable); return true; } @DoNotStrip @Override public <T> Future<T> callOnQueue(final Callable<T> callable) { final SimpleSettableFuture<T> future = new SimpleSettableFuture<>(); runOnQueue( new Runnable() { @Override public void run() { try { future.set(callable.call()); } catch (Exception e) { future.setException(e); } } }); return future; } /** * @return whether the current Thread is also the Thread associated with this MessageQueueThread. */ @DoNotStrip @Override public boolean isOnThread() { return mLooper.getThread() == Thread.currentThread(); } /** * Asserts {@link #isOnThread()}, throwing a {@link AssertionException} (NOT an {@link * AssertionError}) if the assertion fails. */ @DoNotStrip @Override public void assertIsOnThread() { SoftAssertions.assertCondition(isOnThread(), mAssertionErrorMessage); } /** * Asserts {@link #isOnThread()}, throwing a {@link AssertionException} (NOT an {@link * AssertionError}) if the assertion fails. */ @DoNotStrip @Override public void assertIsOnThread(String message) { SoftAssertions.assertCondition( isOnThread(), new StringBuilder().append(mAssertionErrorMessage).append(" ").append(message).toString()); } /** * Quits this queue's Looper. If that Looper was running on a different Thread than the current * Thread, also waits for the last message being processed to finish and the Thread to die. */ @DoNotStrip @Override public void quitSynchronous() { mIsFinished = true; mLooper.quit(); if (mLooper.getThread() != Thread.currentThread()) { try { mLooper.getThread().join(); } catch (InterruptedException e) { throw new RuntimeException("Got interrupted waiting to join thread " + mName); } } } @DoNotStrip @Override public MessageQueueThreadPerfStats getPerfStats() { return mPerfStats; } @DoNotStrip @Override public void resetPerfStats() { assignToPerfStats(mPerfStats, -1, -1); runOnQueue( new Runnable() { @Override public void run() { long wallTime = SystemClock.uptimeMillis(); long cpuTime = SystemClock.currentThreadTimeMillis(); assignToPerfStats(mPerfStats, wallTime, cpuTime); } }); } @DoNotStrip @Override public boolean isIdle() { return mLooper.getQueue().isIdle(); } private static void assignToPerfStats(MessageQueueThreadPerfStats stats, long wall, long cpu) { stats.wallTime = wall; stats.cpuTime = cpu; } public Looper getLooper() { return mLooper; } public String getName() { return mName; } public static MessageQueueThreadImpl create( MessageQueueThreadSpec spec, QueueThreadExceptionHandler exceptionHandler) { switch (spec.getThreadType()) { case MAIN_UI: return createForMainThread(spec.getName(), exceptionHandler); case NEW_BACKGROUND: return startNewBackgroundThread(spec.getName(), spec.getStackSize(), exceptionHandler); default: throw new RuntimeException("Unknown thread type: " + spec.getThreadType()); } } /** * @return a MessageQueueThreadImpl corresponding to Android's main UI thread. */ private static MessageQueueThreadImpl createForMainThread( String name, QueueThreadExceptionHandler exceptionHandler) { final MessageQueueThreadImpl mqt = new MessageQueueThreadImpl(name, Looper.getMainLooper(), exceptionHandler); if (UiThreadUtil.isOnUiThread()) { Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY); } else { UiThreadUtil.runOnUiThread( new Runnable() { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY); } }); } return mqt; } /** * Creates and starts a new MessageQueueThreadImpl encapsulating a new Thread with a new Looper * running on it. Give it a name for easier debugging and optionally a suggested stack size. When * this method exits, the new MessageQueueThreadImpl is ready to receive events. */ private static MessageQueueThreadImpl startNewBackgroundThread( final String name, long stackSize, QueueThreadExceptionHandler exceptionHandler) { final SimpleSettableFuture<Pair<Looper, MessageQueueThreadPerfStats>> dataFuture = new SimpleSettableFuture<>(); long startTimeMillis; Thread bgThread = new Thread( null, new Runnable() { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY); Looper.prepare(); MessageQueueThreadPerfStats stats = new MessageQueueThreadPerfStats(); long wallTime = SystemClock.uptimeMillis(); long cpuTime = SystemClock.currentThreadTimeMillis(); assignToPerfStats(stats, wallTime, cpuTime); dataFuture.set(new Pair<>(Looper.myLooper(), stats)); Looper.loop(); } }, "mqt_" + name, stackSize); bgThread.start(); Pair<Looper, MessageQueueThreadPerfStats> pair = dataFuture.getOrThrow(); return new MessageQueueThreadImpl(name, pair.first, exceptionHandler, pair.second); } }
facebook/react-native
packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadImpl.java
2,141
/* * Copyright (C) 2009-2018 The Project Lombok Authors. * * 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 lombok.eclipse; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import static lombok.eclipse.EcjAugments.ASTNode_handled; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import lombok.Lombok; import lombok.core.AnnotationValues; import lombok.core.AnnotationValues.AnnotationValueDecodeFail; import lombok.core.configuration.ConfigurationKeysLoader; import lombok.core.HandlerPriority; import lombok.core.SpiLoadUtil; import lombok.core.TypeLibrary; import lombok.core.TypeResolver; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; /** * This class tracks 'handlers' and knows how to invoke them for any given AST node. * * This class can find the handlers (via SPI discovery) and will set up the given AST node, such as * building an AnnotationValues instance. */ public class HandlerLibrary { /** * Creates a new HandlerLibrary. Errors will be reported to the Eclipse Error log. * You probably want to use {@link #load()} instead. */ public HandlerLibrary() { ConfigurationKeysLoader.LoaderLoader.loadAllConfigurationKeys(); } private TypeLibrary typeLibrary = new TypeLibrary(); private static class VisitorContainer { private final EclipseASTVisitor visitor; private final long priority; private final boolean deferUntilPostDiet; VisitorContainer(EclipseASTVisitor visitor) { this.visitor = visitor; this.deferUntilPostDiet = visitor.getClass().isAnnotationPresent(DeferUntilPostDiet.class); HandlerPriority hp = visitor.getClass().getAnnotation(HandlerPriority.class); this.priority = hp == null ? 0L : (((long)hp.value()) << 32) + hp.subValue(); } public boolean deferUntilPostDiet() { return deferUntilPostDiet; } public long getPriority() { return priority; } } private static class AnnotationHandlerContainer<T extends Annotation> { private final EclipseAnnotationHandler<T> handler; private final Class<T> annotationClass; private final long priority; private final boolean deferUntilPostDiet; AnnotationHandlerContainer(EclipseAnnotationHandler<T> handler, Class<T> annotationClass) { this.handler = handler; this.annotationClass = annotationClass; this.deferUntilPostDiet = handler.getClass().isAnnotationPresent(DeferUntilPostDiet.class); HandlerPriority hp = handler.getClass().getAnnotation(HandlerPriority.class); this.priority = hp == null ? 0L : (((long)hp.value()) << 32) + hp.subValue(); } public void handle(org.eclipse.jdt.internal.compiler.ast.Annotation annotation, final EclipseNode annotationNode) { AnnotationValues<T> annValues = createAnnotation(annotationClass, annotationNode); handler.handle(annValues, annotation, annotationNode); } public void preHandle(org.eclipse.jdt.internal.compiler.ast.Annotation annotation, final EclipseNode annotationNode) { AnnotationValues<T> annValues = createAnnotation(annotationClass, annotationNode); handler.preHandle(annValues, annotation, annotationNode); } public boolean deferUntilPostDiet() { return deferUntilPostDiet; } public long getPriority() { return priority; } } private Map<String, AnnotationHandlerContainer<?>> annotationHandlers = new HashMap<String, AnnotationHandlerContainer<?>>(); private Collection<VisitorContainer> visitorHandlers = new ArrayList<VisitorContainer>(); /** * Creates a new HandlerLibrary. Errors will be reported to the Eclipse Error log. * then uses SPI discovery to load all annotation and visitor based handlers so that future calls * to the handle methods will defer to these handlers. */ public static HandlerLibrary load() { HandlerLibrary lib = new HandlerLibrary(); loadAnnotationHandlers(lib); loadVisitorHandlers(lib); lib.calculatePriorities(); return lib; } private SortedSet<Long> priorities; public SortedSet<Long> getPriorities() { return priorities; } private void calculatePriorities() { SortedSet<Long> set = new TreeSet<Long>(); for (AnnotationHandlerContainer<?> container : annotationHandlers.values()) set.add(container.getPriority()); for (VisitorContainer container : visitorHandlers) set.add(container.getPriority()); this.priorities = Collections.unmodifiableSortedSet(set); } /** Uses SPI Discovery to find implementations of {@link EclipseAnnotationHandler}. */ @SuppressWarnings({"rawtypes", "unchecked"}) private static void loadAnnotationHandlers(HandlerLibrary lib) { try { for (EclipseAnnotationHandler<?> handler : SpiLoadUtil.findServices(EclipseAnnotationHandler.class, EclipseAnnotationHandler.class.getClassLoader())) { try { Class<? extends Annotation> annotationClass = handler.getAnnotationHandledByThisHandler(); AnnotationHandlerContainer<?> container = new AnnotationHandlerContainer(handler, annotationClass); String annotationClassName = container.annotationClass.getName().replace("$", "."); if (lib.annotationHandlers.put(annotationClassName, container) != null) { error(null, "Duplicate handlers for annotation type: " + annotationClassName, null); } lib.typeLibrary.addType(container.annotationClass.getName()); } catch (Throwable t) { error(null, "Can't load Lombok annotation handler for Eclipse: ", t); } } } catch (IOException e) { throw Lombok.sneakyThrow(e); } } /** Uses SPI Discovery to find implementations of {@link EclipseASTVisitor}. */ private static void loadVisitorHandlers(HandlerLibrary lib) { try { for (EclipseASTVisitor visitor : SpiLoadUtil.findServices(EclipseASTVisitor.class, EclipseASTVisitor.class.getClassLoader())) { lib.visitorHandlers.add(new VisitorContainer(visitor)); } } catch (Throwable t) { throw Lombok.sneakyThrow(t); } } private boolean checkAndSetHandled(ASTNode node) { return !ASTNode_handled.getAndSet(node, true); } private boolean needsHandling(ASTNode node) { return !ASTNode_handled.get(node); } /** * Handles the provided annotation node by first finding a qualifying instance of * {@link EclipseAnnotationHandler} and if one exists, calling it with a freshly cooked up * instance of {@link AnnotationValues}. * * Note that depending on the printASTOnly flag, the {@link lombok.core.PrintAST} annotation * will either be silently skipped, or everything that isn't {@code PrintAST} will be skipped. * * The HandlerLibrary will attempt to guess if the given annotation node represents a lombok annotation. * For example, if {@code lombok.*} is in the import list, then this method will guess that * {@code Getter} refers to {@code lombok.Getter}, presuming that {@link lombok.eclipse.handlers.HandleGetter} * has been loaded. * * @param ast The Compilation Unit that contains the Annotation AST Node. * @param annotationNode The Lombok AST Node representing the Annotation AST Node. * @param annotation 'node.get()' - convenience parameter. * @param priority current prioritiy * @return the priority we want to run - MAX_VALUE means never */ public long handleAnnotation(CompilationUnitDeclaration ast, EclipseNode annotationNode, org.eclipse.jdt.internal.compiler.ast.Annotation annotation, long priority) { TypeResolver resolver = new TypeResolver(annotationNode.getImportList()); TypeReference rawType = annotation.type; if (rawType == null) return Long.MAX_VALUE; String fqn = resolver.typeRefToFullyQualifiedName(annotationNode, typeLibrary, toQualifiedName(annotation.type.getTypeName())); if (fqn == null) return Long.MAX_VALUE; AnnotationHandlerContainer<?> container = annotationHandlers.get(fqn); if (container == null) return Long.MAX_VALUE; if (priority < container.getPriority()) return container.getPriority(); // we want to run at this priority if (priority > container.getPriority()) return Long.MAX_VALUE; // it's over- we do not want to run again if (!annotationNode.isCompleteParse() && container.deferUntilPostDiet()) { if (needsHandling(annotation)) container.preHandle(annotation, annotationNode); return Long.MAX_VALUE; } try { if (checkAndSetHandled(annotation)) container.handle(annotation, annotationNode); } catch (AnnotationValueDecodeFail fail) { fail.owner.setError(fail.getMessage(), fail.idx); } catch (Throwable t) { error(ast, String.format("Lombok annotation handler %s failed", container.handler.getClass()), t); } return Long.MAX_VALUE; } /** * Will call all registered {@link EclipseASTVisitor} instances. */ public long callASTVisitors(EclipseAST ast, long priority, boolean isCompleteParse) { long nearestPriority = Long.MAX_VALUE; for (VisitorContainer container : visitorHandlers) { if (priority < container.getPriority()) nearestPriority = Math.min(container.getPriority(), nearestPriority); if (!isCompleteParse && container.deferUntilPostDiet()) continue; if (priority != container.getPriority()) continue; try { ast.traverse(container.visitor); } catch (Throwable t) { error((CompilationUnitDeclaration) ast.top().get(), String.format("Lombok visitor handler %s failed", container.visitor.getClass()), t); } } return nearestPriority; } }
projectlombok/lombok
src/core/lombok/eclipse/HandlerLibrary.java
2,142
package com.blankj.subutil.util; import androidx.collection.SimpleArrayMap; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 16/11/16 * desc : 拼音相关工具类 * </pre> */ public final class PinyinUtils { private PinyinUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * 汉字转拼音 * * @param ccs 汉字字符串(Chinese characters) * @return 拼音 */ public static String ccs2Pinyin(final CharSequence ccs) { return ccs2Pinyin(ccs, ""); } /** * 汉字转拼音 * * @param ccs 汉字字符串(Chinese characters) * @param split 汉字拼音之间的分隔符 * @return 拼音 */ public static String ccs2Pinyin(final CharSequence ccs, final CharSequence split) { if (ccs == null || ccs.length() == 0) return null; StringBuilder sb = new StringBuilder(); for (int i = 0, len = ccs.length(); i < len; i++) { char ch = ccs.charAt(i); if (ch >= 0x4E00 && ch <= 0x9FA5) { int sp = (ch - 0x4E00) * 6; sb.append(pinyinTable.substring(sp, sp + 6).trim()); } else { sb.append(ch); } sb.append(split); } return sb.toString(); } /** * 获取第一个汉字首字母 * * @param ccs 汉字字符串(Chinese characters) * @return 拼音 */ public static String getPinyinFirstLetter(final CharSequence ccs) { if (ccs == null || ccs.length() == 0) return null; return ccs2Pinyin(String.valueOf(ccs.charAt(0))).substring(0, 1); } /** * 获取所有汉字的首字母 * * @param ccs 汉字字符串(Chinese characters) * @return 所有汉字的首字母 */ public static String getPinyinFirstLetters(final CharSequence ccs) { return getPinyinFirstLetters(ccs, ""); } /** * 获取所有汉字的首字母 * * @param ccs 汉字字符串(Chinese characters) * @param split 首字母之间的分隔符 * @return 所有汉字的首字母 */ public static String getPinyinFirstLetters(final CharSequence ccs, final CharSequence split) { if (ccs == null || ccs.length() == 0) return null; int len = ccs.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append(ccs2Pinyin(String.valueOf(ccs.charAt(i))).substring(0, 1)).append(split); } return sb.toString(); } /** * 根据名字获取姓氏的拼音 * * @param name 名字 * @return 姓氏的拼音 */ public static String getSurnamePinyin(final CharSequence name) { if (name == null || name.length() == 0) return null; if (name.length() >= 2) { CharSequence str = name.subSequence(0, 2); if (str.equals("澹台")) return "tantai"; else if (str.equals("尉迟")) return "yuchi"; else if (str.equals("万俟")) return "moqi"; else if (str.equals("单于")) return "chanyu"; } char ch = name.charAt(0); if (SURNAMES.containsKey(ch)) { return SURNAMES.get(ch); } if (ch >= 0x4E00 && ch <= 0x9FA5) { int sp = (ch - 0x4E00) * 6; return pinyinTable.substring(sp, sp + 6).trim(); } else { return String.valueOf(ch); } } /** * 根据名字获取姓氏的首字母 * * @param name 名字 * @return 姓氏的首字母 */ public static String getSurnameFirstLetter(final CharSequence name) { String surname = getSurnamePinyin(name); if (surname == null || surname.length() == 0) return null; return String.valueOf(surname.charAt(0)); } // 多音字姓氏映射表 private static final SimpleArrayMap<Character, String> SURNAMES; /** * 获取拼音对照表,对比过pinyin4j和其他方式,这样查表设计的好处就是读取快 * <p>当该类加载后会一直占有123KB的内存</p> * <p>如果你想存进文件,然后读取操作的话也是可以,但速度肯定没有这样空间换时间快,毕竟现在设备内存都很大</p> * <p>如需更多用法可以用pinyin4j开源库</p> */ private static final String pinyinTable; static { SURNAMES = new SimpleArrayMap<>(35); SURNAMES.put('乐', "yue"); SURNAMES.put('乘', "sheng"); SURNAMES.put('乜', "nie"); SURNAMES.put('仇', "qiu"); SURNAMES.put('会', "gui"); SURNAMES.put('便', "pian"); SURNAMES.put('区', "ou"); SURNAMES.put('单', "shan"); SURNAMES.put('参', "shen"); SURNAMES.put('句', "gou"); SURNAMES.put('召', "shao"); SURNAMES.put('员', "yun"); SURNAMES.put('宓', "fu"); SURNAMES.put('弗', "fei"); SURNAMES.put('折', "she"); SURNAMES.put('曾', "zeng"); SURNAMES.put('朴', "piao"); SURNAMES.put('查', "zha"); SURNAMES.put('洗', "xian"); SURNAMES.put('盖', "ge"); SURNAMES.put('祭', "zhai"); SURNAMES.put('种', "chong"); SURNAMES.put('秘', "bi"); SURNAMES.put('繁', "po"); SURNAMES.put('缪', "miao"); SURNAMES.put('能', "nai"); SURNAMES.put('蕃', "pi"); SURNAMES.put('覃', "qin"); SURNAMES.put('解', "xie"); SURNAMES.put('谌', "shan"); SURNAMES.put('适', "kuo"); SURNAMES.put('都', "du"); SURNAMES.put('阿', "e"); SURNAMES.put('难', "ning"); SURNAMES.put('黑', "he"); //noinspection StringBufferReplaceableByString pinyinTable = new StringBuilder(125412) .append("yi ding kao qi shang xia none wan zhang san shang xia ji bu yu mian gai chou chou zhuan qie pi shi shi qiu bing ye cong dong si cheng diu qiu liang diu you liang yan bing sang shu jiu ge ya qiang zhong ji jie feng guan chuan chan lin zhuo zhu none wan dan wei zhu jing li ju pie fu yi yi nai none jiu jiu tuo me yi none zhi wu zha hu fa le zhong ping pang qiao hu guai cheng cheng yi yin none mie jiu qi ye xi xiang gai diu none none shu none shi ji nang jia none shi none none mai luan none ru xi yan fu sha na gan none none none none qian zhi gui gan luan lin yi jue le none yu zheng shi shi er chu yu kui yu yun hu qi wu jing si sui gen gen ya xie ya qi ya ji tou wang kang ta jiao hai yi chan heng mu none xiang jing ting liang heng jing ye qin bo you xie dan lian duo wei ren ren ji none wang yi shen ren le ding ze jin pu chou ba zhang jin jie bing reng cong fo san lun none cang zi shi ta zhang fu xian xian cha hong tong ren qian gan ge di dai ling yi chao chang sa shang yi mu men ren jia chao yang qian zhong pi wan wu jian jia yao feng cang ren wang fen di fang zhong qi pei yu diao dun wen yi xin kang yi ji ai wu ji fu fa xiu jin bei chen fu tang zhong you huo hui yu cui yun san wei chuan che ya xian shang chang lun cang xun xin wei zhu chi xuan nao bo gu ni ni xie ban xu ling zhou shen qu si beng si jia pi yi si ai zheng dian han mai dan zhu bu qu bi shao ci wei di zhu zuo you yang ti zhan he bi tuo she yu yi fo zuo gou ning tong ni xuan ju yong wa qian none ka none pei huai he lao xiang ge yang bai fa ming jia nai bing ji heng huo gui quan tiao jiao ci yi shi xing shen tuo kan zhi gai lai yi chi kua guang li yin shi mi zhu xu you an lu mou er lun dong cha chi xun gong zhou yi ru jian xia jia zai lu: none jiao zhen ce qiao kuai chai ning nong jin wu hou jiong cheng zhen cuo chou qin lu: ju shu ting shen tuo bo nan hao bian tui yu xi cu e qiu xu kuang ku wu jun yi fu lang zu qiao li yong hun jing xian san pai su fu xi li mian ping bao yu si xia xin xiu yu ti che chou none yan liang li lai si jian xiu fu he ju xiao pai jian biao ti fei feng ya an bei yu xin bi chi chang zhi bing zan yao cui lia wan lai cang zong ge guan bei tian shu shu men dao tan jue chui xing peng tang hou yi qi ti gan jing jie xu chang jie fang zhi kong juan zong ju qian ni lun zhuo wo luo song leng hun dong zi ben wu ju nai cai jian zhai ye zhi sha qing none ying cheng qian yan nuan zhong chun jia jie wei yu bing ruo ti wei pian yan feng tang wo e xie che sheng kan di zuo cha ting bei ye huang yao zhan qiu yan you jian xu zha chai fu bi zhi zong mian ji yi xie xun si duan ce zhen ou tou tou bei za lou jie wei fen chang kui sou chi su xia fu yuan rong li ru yun gou ma bang dian tang hao jie xi shan qian jue cang chu san bei xiao yong yao ta suo wang fa bing jia dai zai tang none bin chu nuo zan lei cui yong zao zong peng song ao chuan yu zhai zu shang qian") .append("g qiang chi sha han zhang qing yan di xi lou bei piao jin lian lu man qian xian qiu ying dong zhuan xiang shan qiao jiong tui zun pu xi lao chang guang liao qi deng chan wei zhang fan hui chuan tie dan jiao jiu seng fen xian jue e jiao jian tong lin bo gu xian su xian jiang min ye jin jia qiao pi feng zhou ai sai yi jun nong shan yi dang jing xuan kuai jian chu dan jiao sha zai none bin an ru tai chou chai lan ni jin qian meng wu neng qiong ni chang lie lei lu: kuang bao du biao zan zhi si you hao qin chen li teng wei long chu chan rang shu hui li luo zan nuo tang yan lei nang er wu yun zan yuan xiong chong zhao xiong xian guang dui ke dui mian tu chang er dui er jin tu si yan yan shi shi dang qian dou fen mao xin dou bai jing li kuang ru wang nei quan liang yu ba gong liu xi none lan gong tian guan xing bing qi ju dian zi none yang jian shou ji yi ji chan jiong mao ran nei yuan mao gang ran ce jiong ce zai gua jiong mao zhou mao gou xu mian mi rong yin xie kan jun nong yi mi shi guan meng zhong zui yuan ming kou none fu xie mi bing dong tai gang feng bing hu chong jue hu kuang ye leng pan fu min dong xian lie xia jian jing shu mei shang qi gu zhun song jing liang qing diao ling dong gan jian yin cou ai li cang ming zhun cui si duo jin lin lin ning xi du ji fan fan fan feng ju chu none feng none none fu feng ping feng kai huang kai gan deng ping qu xiong kuai tu ao chu ji dang han han zao dao diao dao ren ren chuangfen qie yi ji kan qian cun chu wen ji dan xing hua wan jue li yue lie liu ze gang chuangfu chu qu ju shan min ling zhong pan bie jie jie bao li shan bie chan jing gua gen dao chuangkui ku duo er zhi shua quan cha ci ke jie gui ci gui kai duo ji ti jing lou luo ze yuan cuo xue ke la qian cha chuan gua jian cuo li ti fei pou chan qi chuangzi gang wan bo ji duo qing yan zhuo jian ji bo yan ju huo sheng jian duo duan wu gua fu sheng jian ge zha kai chuangjuan chan tuan lu li fou shan piao kou jiao gua qiao jue hua zha zhuo lian ju pi liu gui jiao gui jian jian tang huo ji jian yi jian zhi chan cuan mo li zhu li ya quan ban gong jia wu mai lie jing keng xie zhi dong zhu nu jie qu shao yi zhu mo li jing lao lao juan kou yang wa xiao mou kuang jie lie he shi ke jing hao bo min chi lang yong yong mian ke xun juan qing lu bu meng lai le kai mian dong xu xu kan wu yi xun weng sheng lao mu lu piao shi ji qin qiang jiao quan xiang yi qiao fan juan tong ju dan xie mai xun xun lu: li che rang quan bao shao yun jiu bao gou wu yun none none gai gai bao cong none xiong peng ju tao ge pu an pao fu gong da jiu qiong bi hua bei nao chi fang jiu yi za jiang kang jiang kuang hu xia qu fan gui qie cang kuang fei hu yu gui kui hui dan kui lian lian suan du jiu qu xi pi qu yi an yan bian ni qu shi xin qian nian sa zu sheng wu hui ban shi xi wan hua xie wan bei zu zhuo xie dan mai nan dan ji bo shuai bu kuang bian bu zhan ka lu you lu xi gua wo xie jie jie wei ang qiong zhi mao yin we") .append("i shao ji que luan shi juan xie xu jin que wu ji e qing xi none chang han e ting li zhe an li ya ya yan she zhi zha pang none ke ya zhi ce pang ti li she hou ting zui cuo fei yuan ce yuan xiang yan li jue sha dian chu jiu qin ao gui yan si li chang lan li yan yan yuan si si lin qiu qu qu none lei du xian zhuan san can can san can ai dai you cha ji you shuangfan shou guai ba fa ruo shi shu zhui qu shou bian xu jia pan sou ji yu sou die rui cong kou gu ju ling gua tao kou zhi jiao zhao ba ding ke tai chi shi you qiu po ye hao si tan chi le diao ji none hong mie yu mang chi ge xuan yao zi he ji diao cun tong ming hou li tu xiang zha he ye lu: a ma ou xue yi jun chou lin tun yin fei bi qin qin jie pou fou ba dun fen e han ting hang shun qi hu zhi yin wu wu chao na chuo xi chui dou wen hou ou wu gao ya jun lu: e ge mei dai qi cheng wu gao fu jiao hong chi sheng na tun m yi dai ou li bei yuan guo none qiang wu e shi quan pen wen ni mou ling ran you di zhou shi zhou zhan ling yi qi ping zi gua ci wei xu he nao xia pei yi xiao shen hu ming da qu ju gan za tuo duo pou pao bie fu bi he za he hai jiu yong fu da zhou wa ka gu ka zuo bu long dong ning zha si xian huo qi er e guang zha xi yi lie zi mie mi zhi yao ji zhou ge shuai zan xiao ke hui kua huai tao xian e xuan xiu guo yan lao yi ai pin shen tong hong xiong duo wa ha zai you di pai xiang ai gen kuang ya da xiao bi hui none hua none kuai duo none ji nong mou yo hao yuan long pou mang ge e chi shao li na zu he ku xiao xian lao bei zhe zha liang ba mi le sui fou bu han heng geng shuo ge you yan gu gu bai han suo chun yi ai jia tu xian guan li xi tang zuo miu che wu zao ya dou qi di qin ma none gong dou none lao liang suo zao huan none gou ji zuo wo feng yin hu qi shou wei shua chang er li qiang an jie yo nian yu tian lai sha xi tuo hu ai zhou nou ken zhuo zhuo shang di heng lin a xiao xiang tun wu wen cui jie hu qi qi tao dan dan wan zi bi cui chuo he ya qi zhe fei liang xian pi sha la ze qing gua pa zhe se zhuan nie guo luo yan di quan tan bo ding lang xiao none tang chi ti an jiu dan ka yong wei nan shan yu zhe la jie hou han die zhou chai kuai re yu yin zan yao wo mian hu yun chuan hui huan huan xi he ji kui zhong wei sha xu huang du nie xuan liang yu sang chi qiao yan dan pen shi li yo zha wei miao ying pen none kui xi yu jie lou ku cao huo ti yao he a xiu qiang se yong su hong xie ai suo ma cha hai ke da sang chen ru sou gong ji pang wu qian shi ge zi jie luo weng wa si chi hao suo jia hai suo qin nie he none sai ng ge na dia ai none tong bi ao ao lian cui zhe mo sou sou tan di qi jiao chong jiao kai tan san cao jia none xiao piao lou ga gu xiao hu hui guo ou xian ze chang xu po de ma ma hu lei du ga tang ye beng ying none jiao mi xiao hua ") .append("mai ran zuo peng lao xiao ji zhu chao kui zui xiao si hao fu liao qiao xi xu chan dan hei xun wu zun pan chi kui can zan cu dan yu tun cheng jiao ye xi qi hao lian xu deng hui yin pu jue qin xun nie lu si yan ying da zhan o zhou jin nong hui hui qi e zao yi shi jiao yuan ai yong xue kuai yu pen dao ga xin dun dang none sai pi pi yin zui ning di han ta huo ru hao xia yan duo pi chou ji jin hao ti chang none none ca ti lu hui bao you nie yin hu mo huang zhe li liu none nang xiao mo yan li lu long mo dan chen pin pi xiang huo mo xi duo ku yan chan ying rang dian la ta xiao jiao chuo huan huo zhuan nie xiao ca li chan chai li yi luo nang zan su xi none jian za zhu lan nie nang none none wei hui yin qiu si nin jian hui xin yin nan tuan tuan dun kang yuan jiong pian yun cong hu hui yuan e guo kun cong wei tu wei lun guo jun ri ling gu guo tai guo tu you guo yin hun pu yu han yuan lun quan yu qing guo chui wei yuan quan ku pu yuan yuan e tu tu tu tuan lu:e hui yi yuan luan luan tu ya tu ting sheng yan lu none ya zai wei ge yu wu gui pi yi di qian qian zhen zhuo dang qia none none kuang chang qi nie mo ji jia zhi zhi ban xun tou qin fen jun keng dun fang fen ben tan kan huai zuo keng bi xing di jing ji kuai di jing jian tan li ba wu fen zhui po pan tang kun qu tan zhi tuo gan ping dian wa ni tai pi jiong yang fo ao liu qiu mu ke gou xue ba chi che ling zhu fu hu zhi chui la long long lu ao none pao none xing tong ji ke lu ci chi lei gai yin hou dui zhao fu guang yao duo duo gui cha yang yin fa gou yuan die xie ken shang shou e none dian hong ya kua da none dang kai none nao an xing xian huan bang pei ba yi yin han xu chui cen geng ai peng fang que yong jun jia di mai lang xuan cheng shan jin zhe lie lie pu cheng none bu shi xun guo jiong ye nian di yu bu wu juan sui pi cheng wan ju lun zheng kong zhong dong dai tan an cai shu beng kan zhi duo yi zhi yi pei ji zhun qi sao ju ni ku ke tang kun ni jian dui jin gang yu e peng gu tu leng none ya qian none an chen duo nao tu cheng yin hun bi lian guo die zhuan hou bao bao yu di mao jie ruan e geng kan zong yu huang e yao yan bao ji mei chang du tuo an feng zhong jie zhen heng gang chuan jian none lei gang huang leng duan wan xuan ji ji kuai ying ta cheng yong kai su su shi mi ta weng cheng tu tang qiao zhong li peng bang sai zang dui tian wu cheng xun ge zhen ai gong yan kan tian yuan wen xie liu none lang chang peng beng chen lu lu ou qian mei mo zhuan shuangshu lou chi man biao jing ce shu di zhang kan yong dian chen zhi ji guo qiang jin di shang mu cui yan ta zeng qi qiang liang none zhui qiao zeng xu shan shan ba pu kuai dong fan que mo dun dun zun zui sheng duo duo tan deng mu fen huang tan da ye chu none ao qiang ji qiao ken yi pi bi dian jiang ye yong xue tan lan ju huai dang rang qian xuan lan mi he kai ya dao hao ruan none lei kuang lu yan tan wei huai long long rui li ") .append(" lin rang chan xun yan lei ba none shi ren none zhuangzhuangsheng yi mai qiao zhu zhuanghu hu kun yi hu xu kun shou mang zun shou yi zhi gu chu xiang feng bei none bian sui qun ling fu zuo xia xiong none nao xia kui xi wai yuan mao su duo duo ye qing none gou gou qi meng meng yin huo chen da ze tian tai fu guai yao yang hang gao shi ben tai tou yan bi yi kua jia duo none kuang yun jia ba en lian huan di yan pao juan qi nai feng xie fen dian none kui zou huan qi kai she ben yi jiang tao zhuangben xi huang fei diao sui beng dian ao she weng pan ao wu ao jiang lian duo yun jiang shi fen huo bei lian che nu: nu ding nai qian jian ta jiu nan cha hao xian fan ji shuo ru fei wang hong zhuangfu ma dan ren fu jing yan xie wen zhong pa du ji keng zhong yao jin yun miao pei chi yue zhuangniu yan na xin fen bi yu tuo feng yuan fang wu yu gui du ba ni zhou zhou zhao da nai yuan tou xuan zhi e mei mo qi bi shen qie e he xu fa zheng ni ban mu fu ling zi zi shi ran shan yang qian jie gu si xing wei zi ju shan pin ren yao tong jiang shu ji gai shang kuo juan jiao gou lao jian jian yi nian zhi ji ji xian heng guang jun kua yan ming lie pei yan you yan cha xian yin chi gui quan zi song wei hong wa lou ya rao jiao luan ping xian shao li cheng xie mang none suo mu wei ke lai chuo ding niang keng nan yu na pei sui juan shen zhi han di zhuange pin tui xian mian wu yan wu xi yan yu si yu wa li xian ju qu chui qi xian zhui dong chang lu ai e e lou mian cong pou ju po cai ling wan biao xiao shu qi hui fu wo rui tan fei none jie tian ni quan jing hun jing qian dian xing hu wan lai bi yin chou chuo fu jing lun yan lan kun yin ya none li dian xian none hua ying chan shen ting yang yao wu nan chuo jia tou xu yu wei ti rou mei dan ruan qin none wu qian chun mao fu jie duan xi zhong mei huang mian an ying xuan none wei mei yuan zhen qiu ti xie tuo lian mao ran si pian wei wa jiu hu ao none bao xu tou gui zou yao pi xi yuan ying rong ru chi liu mei pan ao ma gou kui qin jia sao zhen yuan cha yong ming ying ji su niao xian tao pang lang niao bao ai pi pin yi piao yu lei xuan man yi zhang kang yong ni li di gui yan jin zhuan chang ce han nen lao mo zhe hu hu ao nen qiang none bi gu wu qiao tuo zhan mao xian xian mo liao lian hua gui deng zhi xu none hua xi hui rao xi yan chan jiao mei fan fan xian yi wei chan fan shi bi shan sui qiang lian huan none niao dong yi can ai niang ning ma tiao chou jin ci yu pin none xu nai yan tai ying can niao none ying mian none ma shen xing ni du liu yuan lan yan shuangling jiao niang lan xian ying shuangshuai quan mi li luan yan zhu lan zi jie jue jue kong yun zi zi cun sun fu bei zi xiao xin meng si tai bao ji gu nu xue none chan hai luan sun nao mie cong jian shu chan ya zi ni fu zi li xue bo ru nai nie nie ying luan mian ning rong ta gui zhai qiong yu shou an tu song wan rou yao hong yi jing zhun mi guai dang hong zong guan zhou ding wa") .append("n yi bao shi shi chong shen ke xuan shi you huan yi tiao shi xian gong cheng qun gong xiao zai zha bao hai yan xiao jia shen chen rong huang mi kou kuan bin su cai zan ji yuan ji yin mi kou qing he zhen jian fu ning bing huan mei qin han yu shi ning jin ning zhi yu bao kuan ning qin mo cha ju gua qin hu wu liao shi ning zhai shen wei xie kuan hui liao jun huan yi yi bao qin chong bao feng cun dui si xun dao lu: dui shou po feng zhuan fu she ke jiang jiang zhuan wei zun xun shu dui dao xiao ji shao er er er ga jian shu chen shang shang yuan ga chang liao xian xian none wang wang you liao liao yao mang wang wang wang ga yao duo kui zhong jiu gan gu gan gan gan gan shi yin chi kao ni jin wei niao ju pi ceng xi bi ju jie tian qu ti jie wu diao shi shi ping ji xie chen xi ni zhan xi none man e lou ping ti fei shu xie tu lu: lu: xi ceng lu: ju xie ju jue liao jue shu xi che tun ni shan wa xian li e none none long yi qi ren wu han shen yu chu sui qi none yue ban yao ang ya wu jie e ji qian fen wan qi cen qian qi cha jie qu gang xian ao lan dao ba zhai zuo yang ju gang ke gou xue bo li tiao qu yan fu xiu jia ling tuo pei you dai kuang yue qu hu po min an tiao ling chi none dong none kui xiu mao tong xue yi none he ke luo e fu xun die lu lang er gai quan tong yi mu shi an wei hu zhi mi li ji tong kui you none xia li yao jiao zheng luan jiao e e yu ye bu qiao qun feng feng nao li you xian hong dao shen cheng tu geng jun hao xia yin wu lang kan lao lai xian que kong chong chong ta none hua ju lai qi min kun kun zu gu cui ya ya gang lun lun leng jue duo cheng guo yin dong han zheng wei yao pi yan song jie beng zu jue dong zhan gu yin zi ze huang yu wei yang feng qiu dun ti yi zhi shi zai yao e zhu kan lu: yan mei gan ji ji huan ting sheng mei qian wu yu zong lan jie yan yan wei zong cha sui rong ke qin yu qi lou tu dui xi weng cang dang rong jie ai liu wu song qiao zi wei beng dian cuo qian yong nie cuo ji none none song zong jiang liao none chan di cen ding tu lou zhang zhan zhan ao cao qu qiang zui zui dao dao xi yu bo long xiang ceng bo qin jiao yan lao zhan lin liao liao jin deng duo zun jiao gui yao qiao yao jue zhan yi xue nao ye ye yi e xian ji xie ke sui di ao zui none yi rong dao ling za yu yue yin none jie li sui long long dian ying xi ju chan ying kui yan wei nao quan chao cuan luan dian dian nie yan yan yan nao yan chuan gui chuan zhou huang jing xun chao chao lie gong zuo qiao ju gong none wu none none cha qiu qiu ji yi si ba zhi zhao xiang yi jin xun juan none xun jin fu za bi shi bu ding shuai fan nie shi fen pa zhi xi hu dan wei zhang tang dai ma pei pa tie fu lian zhi zhou bo zhi di mo yi yi ping qia juan ru shuai dai zhen shui qiao zhen shi qun xi bang dai gui chou ping zhang sha wan dai wei chang sha qi ze guo mao du hou zhen xu mi wei wo fu yi bang ping none gong pan huang dao mi jia teng hui zhong sen ") .append("man mu biao guo ze mu bang zhang jiong chan fu zhi hu fan chuangbi bi none mi qiao dan fen meng bang chou mie chu jie xian lan gan ping nian jian bing bing xing gan yao huan you you ji guang pi ting ze guang zhuangmo qing bi qin dun chuanggui ya bai jie xu lu wu none ku ying di pao dian ya miao geng ci fu tong pang fei xiang yi zhi tiao zhi xiu du zuo xiao tu gui ku pang ting you bu bing cheng lai bi ji an shu kang yong tuo song shu qing yu yu miao sou ce xiang fei jiu he hui liu sha lian lang sou jian pou qing jiu jiu qin ao kuo lou yin liao dai lu yi chu chan tu si xin miao chang wu fei guang none guai bi qiang xie lin lin liao lu none ying xian ting yong li ting yin xun yan ting di po jian hui nai hui gong nian kai bian yi qi nong fen ju yan yi zang bi yi yi er san shi er shi shi gong diao yin hu fu hong wu tui chi qiang ba shen di zhang jue tao fu di mi xian hu chao nu jing zhen yi mi quan wan shao ruo xuan jing diao zhang jiang qiang beng dan qiang bi bi she dan jian gou none fa bi kou none bie xiao dan kuang qiang hong mi kuo wan jue ji ji gui dang lu lu tuan hui zhi hui hui yi yi yi yi huo huo shan xing zhang tong yan yan yu chi cai biao diao bin peng yong piao zhang ying chi chi zhuo tuo ji pang zhong yi wang che bi di ling fu wang zheng cu wang jing dai xi xun hen yang huai lu: hou wang cheng zhi xu jing tu cong none lai cong de pai xi none qi chang zhi cong zhou lai yu xie jie jian chi jia bian huang fu xun wei pang yao wei xi zheng piao chi de zheng zhi bie de chong che jiao wei jiao hui mei long xiang bao qu xin xin bi yi le ren dao ding gai ji ren ren chan tan te te gan qi dai cun zhi wang mang xi fan ying tian min min zhong chong wu ji wu xi ye you wan zong zhong kuai yu bian zhi chi cui chen tai tun qian nian hun xiong niu wang xian xin kang hu kai fen huai tai song wu ou chang chuangju yi bao chao min pi zuo zen yang kou ban nu nao zheng pa bu tie hu hu ju da lian si zhou di dai yi tu you fu ji peng xing yuan ni guai fu xi bi you qie xuan zong bing huang xu chu pi xi xi tan none zong dui none none yi chi nen xun shi xi lao heng kuang mou zhi xie lian tiao huang die hao kong gui heng xi xiao shu sai hu qiu yang hui hui chi jia yi xiong guai lin hui zi xu chi xiang nu: hen en ke dong tian gong quan xi qia yue peng ken de hui e none tong yan kai ce nao yun mang yong yong juan mang kun qiao yue yu yu jie xi zhe lin ti han hao qie ti bu yi qian hui xi bei man yi heng song quan cheng kui wu wu you li liang huan cong yi yue li nin nao e que xuan qian wu min cong fei bei de cui chang men li ji guan guan xing dao qi kong tian lun xi kan kun ni qing chou dun guo chan jing wan yuan jin ji lin yu huo he quan yan ti ti nie wang chuo hu hun xi chang xin wei hui e rui zong jian yong dian ju can cheng de bei qie can dan guan duo nao yun xiang zhui die huang chun qiong re xing ce bian hun zong ti qiao chou bei xuan wei ge qian wei yu yu bi xuan huan") .append(" min bi yi mian yong kai dang yin e chen mou qia ke yu ai qie yan nuo gan yun zong sai leng fen none kui kui que gong yun su su qi yao song huang none gu ju chuangta xie kai zheng yong cao sun shen bo kai yuan xie hun yong yang li sao tao yin ci xu qian tai huang yun shen ming none she cong piao mo mu guo chi can can can cui min ni zhang tong ao shuangman guan que zao jiu hui kai lian ou song jin yin lu: shang wei tuan man qian zhe yong qing kang di zhi lu: juan qi qi yu ping liao zong you chuangzhi tong cheng qi qu peng bei bie chun jiao zeng chi lian ping kui hui qiao cheng yin yin xi xi dan tan duo dui dui su jue ce xiao fan fen lao lao chong han qi xian min jing liao wu can jue chou xian tan sheng pi yi chu xian nao dan tan jing song han jiao wei huan dong qin qin qu cao ken xie ying ao mao yi lin se jun huai men lan ai lin yan gua xia chi yu yin dai meng ai meng dui qi mo lan men chou zhi nuo nuo yan yang bo zhi xing kuang you fu liu mie cheng none chan meng lan huai xuan rang chan ji ju huan she yi lian nan mi tang jue gang gang zhuangge yue wu jian xu shu rong xi cheng wo jie ge jian qiang huo qiang zhan dong qi jia die cai jia ji shi kan ji kui gai deng zhan chuangge jian jie yu jian yan lu xi zhan xi xi chuo dai qu hu hu hu e shi li mao hu li fang suo bian dian jiong shang yi yi shan hu fei yan shou shou cai zha qiu le pu ba da reng fu none zai tuo zhang diao kang yu ku han shen cha chi gu kou wu tuo qian zhi cha kuo men sao yang niu ban che rao xi qian ban jia yu fu ao xi pi zhi zi e dun zhao cheng ji yan kuang bian chao ju wen hu yue jue ba qin zhen zheng yun wan na yi shu zhua pou tou dou kang zhe pou fu pao ba ao ze tuan kou lun qiang none hu bao bing zhi peng tan pu pi tai yao zhen zha yang bao he ni yi di chi pi za mo mo chen ya chou qu min chu jia fu zha zhu dan chai mu nian la fu pao ban pai lin na guai qian ju tuo ba tuo tuo ao ju zhuo pan zhao bai bai di ni ju kuo long jian qia yong lan ning bo ze qian hen kuo shi jie zheng nin gong gong quan shuan tun zan kao chi xie ce hui pin zhuai shi na bo chi gua zhi kuo duo duo zhi qie an nong zhen ge jiao kua dong ru tiao lie zha lu: die wa jue none ju zhi luan ya wo ta xie nao dang jiao zheng ji hui xian none ai tuo nuo cuo bo geng ti zhen cheng suo suo keng mei long ju peng jian yi ting shan nuo wan xie cha feng jiao wu jun jiu tong kun huo tu zhuo pou lu: ba han shao nie juan she shu ye jue bu huan bu jun yi zhai lu: sou tuo lao sun bang jian huan dao none wan qin peng she lie min men fu bai ju dao wo ai juan yue zong chen chui jie tu ben na nian nuo zu wo xi xian cheng dian sao lun qing gang duo shou diao pou di zhang gun ji tao qia qi pai shu qian ling ye ya jue zheng liang gua yi huo shan ding lu:e cai tan che bing jie ti kong tui yan cuo zou ju tian qian ken bai shou jie lu guai none none zhi dan none chan sao guan peng yuan nuo jian zheng jiu jian yu ya") .append("n kui nan hong rou pi wei sai zou xuan miao ti nie cha shi zong zhen yi shun heng bian yang huan yan zan an xu ya wo ke chuai ji ti la la cheng kai jiu jiu tu jie hui geng chong shuo she xie yuan qian ye cha zha bei yao none none lan wen qin chan ge lou zong geng jiao gou qin yong que chou chuai zhan sun sun bo chu rong bang cuo sao ke yao dao zhi nu xie jian sou qiu gao xian shuo sang jin mie e chui nuo shan ta jie tang pan ban da li tao hu zhi wa xia qian wen qiang chen zhen e xie nuo quan cha zha ge wu en she gong she shu bai yao bin sou tan sha chan suo liao chong chuangguo bing feng shuai di qi none zhai lian cheng chi guan lu luo lou zong gai hu zha chuangtang hua cui nai mo jiang gui ying zhi ao zhi chi man shan kou shu suo tuan zhao mo mo zhe chan keng biao jiang yin gou qian liao ji ying jue pie pie lao dun xian ruan kui zan yi xian cheng cheng sa nao heng si han huang da zun nian lin zheng hui zhuangjiao ji cao dan dan che bo che jue xiao liao ben fu qiao bo cuo zhuo zhuan tuo pu qin dun nian none xie lu jiao cuan ta han qiao zhua jian gan yong lei kuo lu shan zhuo ze pu chuo ji dang se cao qing jing huan jie qin kuai dan xie ge pi bo ao ju ye none none sou mi ji tai zhuo dao xing lan ca ju ye ru ye ye ni huo ji bin ning ge zhi jie kuo mo jian xie lie tan bai sou lu lu:e rao zhi pan yang lei sa shu zan nian xian jun huo lu:e la han ying lu long qian qian zan qian lan san ying mei rang chan none cuan xie she luo jun mi li zan luan tan zuan li dian wa dang jiao jue lan li nang zhi gui gui qi xin po po shou kao you gai gai gong gan ban fang zheng bo dian kou min wu gu ge ce xiao mi chu ge di xu jiao min chen jiu shen duo yu chi ao bai xu jiao duo lian nie bi chang dian duo yi gan san ke yan dun qi dou xiao duo jiao jing yang xia hun shu ai qiao ai zheng di zhen fu shu liao qu xiong xi jiao none qiao zhuo yi lian bi li xue xiao wen xue qi qi zhai bin jue zhai lang fei ban ban lan yu lan wei dou sheng liao jia hu xie jia yu zhen jiao wo tiao dou jin chi yin fu qiang zhan qu zhuo zhan duan zhuo si xin zhuo zhuo qin lin zhuo chu duan zhu fang xie hang wu shi pei you none pang qi zhan mao lu: pei pi liu fu fang xuan jing jing ni zu zhao yi liu shao jian none yi qi zhi fan piao fan zhan guai sui yu wu ji ji ji huo ri dan jiu zhi zao xie tiao xun xu ga la gan han tai di xu chan shi kuang yang shi wang min min tun chun wu yun bei ang ze ban jie kun sheng hu fang hao gui chang xuan ming hun fen qin hu yi xi xin yan ze fang tan shen ju yang zan bing xing ying xuan pei zhen ling chun hao mei zuo mo bian xu hun zhao zong shi shi yu fei die mao ni chang wen dong ai bing ang zhou long xian kuang tiao chao shi huang huang xuan kui xu jiao jin zhi jin shang tong hong yan gai xiang shai xiao ye yun hui han han jun wan xian kun zhou xi sheng sheng bu zhe zhe wu han hui hao chen wan tian zhuo zui zhou pu jing xi shan yi xi qing qi jing gui zhen yi zhi an wan lin ") .append("liang chang wang xiao zan none xuan geng yi xia yun hui fu min kui he ying du wei shu qing mao nan jian nuan an yang chun yao suo pu ming jiao kai gao weng chang qi hao yan li ai ji gui men zan xie hao mu mo cong ni zhang hui bao han xuan chuan liao xian dan jing pie lin tun xi yi ji kuang dai ye ye li tan tong xiao fei qin zhao hao yi xiang xing sen jiao bao jing none ai ye ru shu meng xun yao pu li chen kuang die none yan huo lu xi rong long nang luo luan shai tang yan chu yue yue qu ye geng zhuai hu he shu cao cao sheng man ceng ceng ti zui can xu hui yin qie fen pi yue you ruan peng ban fu ling fei qu none nu: tiao shuo zhen lang lang juan ming huang wang tun chao ji qi ying zong wang tong lang none meng long mu deng wei mo ben zha zhu shu none zhu ren ba po duo duo dao li qiu ji jiu bi xiu ting ci sha none za quan qian yu gan wu cha shan xun fan wu zi li xing cai cun ren shao zhe di zhang mang chi yi gu gong du yi qi shu gang tiao none none none lai shan mang yang ma miao si yuan hang fei bei jie dong gao yao xian chu chun pa shu hua xin chou zhu chou song ban song ji yue yun gou ji mao pi bi wang ang fang fen yi fu nan xi hu ya dou xun zhen yao lin rui e mei zhao guo zhi zong yun none dou shu zao none li lu jian cheng song qiang feng nan xiao xian ku ping tai xi zhi guai xiao jia jia gou bao mo yi ye sang shi nie bi tuo yi ling bing ni la he ban fan zhong dai ci yang fu bo mou gan qi ran rou mao zhao song zhe xia you shen ju tuo zuo nan ning yong di zhi zha cha dan gu none jiu ao fu jian bo duo ke nai zhu bi liu chai zha si zhu pei shi guai cha yao cheng jiu shi zhi liu mei none rong zha none biao zhan zhi long dong lu none li lan yong shu xun shuan qi zhen qi li chi xiang zhen li su gua kan bing ren xiao bo ren bing zi chou yi ci xu zhu jian zui er er yu fa gong kao lao zhan li none yang he gen zhi chi ge zai luan fa jie heng gui tao guang wei kuang ru an an juan yi zhuo ku zhi qiong tong sang sang huan jie jiu xue duo zhui yu zan none ying none none zhan ya rao zhen dang qi qiao hua gui jiang zhuangxun suo suo zhen bei ting kuo jing bo ben fu rui tong jue xi lang liu feng qi wen jun gan cu liang qiu ting you mei bang long peng zhuangdi xuan tu zao ao gu bi di han zi zhi ren bei geng jian huan wan nuo jia tiao ji xiao lu: kuan shao cen fen song meng wu li li dou cen ying suo ju ti xie kun zhuo shu chan fan wei jing li bing none none tao zhi lai lian jian zhuo ling li qi bing lun cong qian mian qi qi cai gun chan de fei pai bang pou hun zong cheng zao ji li peng yu yu gu hun dong tang gang wang di xi fan cheng zhan qi yuan yan yu quan yi sen ren chui leng qi zhuo fu ke lai zou zou zhao guan fen fen chen qiong nie wan guo lu hao jie yi chou ju ju cheng zuo liang qiang zhi zhui ya ju bei jiao zhuo zi bin peng ding chu shan none none jian gui xi du qian none kui none luo zhi none none none none peng shan none tuo sen duo ye fu wei wei duan jia zong") .append(" jian yi shen xi yan yan chuan zhan chun yu he zha wo bian bi yao huo xu ruo yang la yan ben hun kui jie kui si feng xie tuo ji jian mu mao chu hu hu lian leng ting nan yu you mei song xuan xuan ying zhen pian die ji jie ye chu shun yu cou wei mei di ji jie kai qiu ying rou heng lou le none gui pin none gai tan lan yun yu chen lu: ju none none none xie jia yi zhan fu nuo mi lang rong gu jian ju ta yao zhen bang sha yuan zi ming su jia yao jie huang gan fei zha qian ma sun yuan xie rong shi zhi cui yun ting liu rong tang que zhai si sheng ta ke xi gu qi kao gao sun pan tao ge xun dian nou ji shuo gou chui qiang cha qian huai mei xu gang gao zhuo tuo qiao yang dian jia jian zui none long bin zhu none xi qi lian hui yong qian guo gai gai tuan hua qi sen cui beng you hu jiang hu huan kui yi yi gao kang gui gui cao man jin di zhuangle lang chen cong li xiu qing shuangfan tong guan ji suo lei lu liang mi lou chao su ke chu tang biao lu jiu shu zha shu zhang men mo niao yang tiao peng zhu sha xi quan heng jian cong none none qiang none ying er xin zhi qiao zui cong pu shu hua kui zhen zun yue zhan xi xun dian fa gan mo wu qiao rao lin liu qiao xian run fan zhan tuo lao yun shun tui cheng tang meng ju cheng su jue jue tan hui ji nuo xiang tuo ning rui zhu tong zeng fen qiong ran heng cen gu liu lao gao chu none none none none ji dou none lu none none yuan ta shu jiang tan lin nong yin xi sui shan zui xuan cheng gan ju zui yi qin pu yan lei feng hui dang ji sui bo bi ding chu zhua gui ji jia jia qing zhe jian qiang dao yi biao song she lin li cha meng yin tao tai mian qi none bin huo ji qian mi ning yi gao jian yin er qing yan qi mi zhao gui chun ji kui po deng chu none mian you zhi guang qian lei lei sa lu none cuan lu: mie hui ou lu: zhi gao du yuan li fei zhu sou lian none chu none zhu lu yan li zhu chen jie e su huai nie yu long lai none xian none ju xiao ling ying jian yin you ying xiang nong bo chan lan ju shuangshe wei cong quan qu none none yu luo li zan luan dang jue none lan lan zhu lei li ba nang yu ling none qian ci huan xin yu yu qian ou xu chao chu qi kai yi jue xi xu xia yu kuai lang kuan shuo xi e yi qi hu chi qin kuan kan kuan kan chuan sha none yin xin xie yu qian xiao yi ge wu tan jin ou hu ti huan xu pen xi xiao hu she none lian chu yi kan yu chuo huan zhi zheng ci bu wu qi bu bu wai ju qian chi se chi se zhong sui sui li cuo yu li gui dai dai si jian zhe mo mo yao mo cu yang tian sheng dai shang xu xun shu can jue piao qia qiu su qing yun lian yi fou zhi ye can hun dan ji ye none yun wen chou bin ti jin shang yin diao cu hui cuan yi dan du jiang lian bin du jian jian shu ou duan zhu yin qing yi sha ke ke yao xun dian hui hui gu que ji yi ou hui duan yi xiao wu guan mu mei mei ai zuo du yu bi bi bi pi pi bi chan mao none none pi none jia zhan sai mu tuo xun er rong xian ju mu hao qiu dou none ta") .append("n pei ju duo cui bi san none mao sui shu yu tuo he jian ta san lu: mu li tong rong chang pu lu zhan sao zhan meng lu qu die shi di min jue mang qi pie nai qi dao xian chuan fen ri nei none fu shen dong qing qi yin xi hai yang an ya ke qing ya dong dan lu: qing yang yun yun shui shui zheng bing yong dang shui le ni tun fan gui ting zhi qiu bin ze mian cuan hui diao han cha zhuo chuan wan fan dai xi tuo mang qiu qi shan pai han qian wu wu xun si ru gong jiang chi wu none none tang zhi chi qian mi gu wang qing jing rui jun hong tai quan ji bian bian gan wen zhong fang xiong jue hu none qi fen xu xu qin yi wo yun yuan hang yan shen chen dan you dun hu huo qi mu rou mei ta mian wu chong tian bi sha zhi pei pan zhui za gou liu mei ze feng ou li lun cang feng wei hu mo mei shu ju zan tuo tuo duo he li mi yi fu fei you tian zhi zhao gu zhan yan si kuang jiong ju xie qiu yi jia zhong quan bo hui mi ben zhuo chu le you gu hong gan fa mao si hu ping ci fan zhi su ning cheng ling pao bo qi si ni ju yue zhu sheng lei xuan xue fu pan min tai yang ji yong guan beng xue long lu dan luo xie po ze jing yin zhou jie yi hui hui zui cheng yin wei hou jian yang lie si ji er xing fu sa zi zhi yin wu xi kao zhu jiang luo none an dong yi mou lei yi mi quan jin po wei xiao xie hong xu su kuang tao qie ju er zhou ru ping xun xiong zhi guang huan ming huo wa qia pai wu qu liu yi jia jing qian jiang jiao zhen shi zhuo ce none hui ji liu chan hun hu nong xun jin lie qiu wei zhe jun han bang mang zhuo you xi bo dou huan hong yi pu ying lan hao lang han li geng fu wu li chun feng yi yu tong lao hai jin jia chong weng mei sui cheng pei xian shen tu kun pin nie han jing xiao she nian tu yong xiao xian ting e su tun juan cen ti li shui si lei shui tao du lao lai lian wei wo yun huan di none run jian zhang se fu guan xing shou shuan ya chuo zhang ye kong wan han tuo dong he wo ju gan liang hun ta zhuo dian qie de juan zi xi xiao qi gu guo han lin tang zhou peng hao chang shu qi fang chi lu nao ju tao cong lei zhi peng fei song tian pi dan yu ni yu lu gan mi jing ling lun yin cui qu huai yu nian shen piao chun hu yuan lai hun qing yan qian tian miao zhi yin mi ben yuan wen re fei qing yuan ke ji she yuan se lu zi du none jian mian pi xi yu yuan shen shen rou huan zhu jian nuan yu qiu ting qu du feng zha bo wo wo di wei wen ru xie ce wei ge gang yan hong xuan mi ke mao ying yan you hong miao xing mei zai hun nai kui shi e pai mei lian qi qi mei tian cou wei can tuan mian xu mo xu ji pen jian jian hu feng xiang yi yin zhan shi jie zhen huang tan yu bi min shi tu sheng yong ju zhong none qiu jiao none yin tang long huo yuan nan ban you quan chui liang chan yan chun nie zi wan shi man ying la kui none jian xu lou gui gai none none po jin gui tang yuan suo yuan lian yao meng zhun sheng ke tai ta wa liu gou sao ming zha shi yi lun ma pu wei li ") .append("cai wu xi wen qiang ce shi su yi zhen sou yun xiu yin rong hun su su ni ta shi ru wei pan chu chu pang weng cang mie he dian hao huang xi zi di zhi ying fu jie hua ge zi tao teng sui bi jiao hui gun yin gao long zhi yan she man ying chun lu: lan luan xiao bin tan yu xiu hu bi biao zhi jiang kou shen shang di mi ao lu hu hu you chan fan yong gun man qing yu piao ji ya jiao qi xi ji lu lu: long jin guo cong lou zhi gai qiang li yan cao jiao cong chun tuan ou teng ye xi mi tang mo shang han lian lan wa li qian feng xuan yi man zi mang kang luo peng shu zhang zhang chong xu huan kuo jian yan chuangliao cui ti yang jiang cong ying hong xiu shu guan ying xiao none none xu lian zhi wei pi yu jiao po xiang hui jie wu pa ji pan wei xiao qian qian xi lu xi sun dun huang min run su liao zhen zhong yi di wan dan tan chao xun kui none shao tu zhu sa hei bi shan chan chan shu tong pu lin wei se se cheng jiong cheng hua jiao lao che gan cun heng si shu peng han yun liu hong fu hao he xian jian shan xi ao lu lan none yu lin min zao dang huan ze xie yu li shi xue ling man zi yong kuai can lian dian ye ao huan lian chan man dan dan yi sui pi ju ta qin ji zhuo lian nong guo jin fen se ji sui hui chu ta song ding se zhu lai bin lian mi shi shu mi ning ying ying meng jin qi bi ji hao ru zui wo tao yin yin dui ci huo jing lan jun ai pu zhuo wei bin gu qian xing bin kuo fei none bin jian dui luo luo lu: li you yang lu si jie ying du wang hui xie pan shen biao chan mie liu jian pu se cheng gu bin huo xian lu qin han ying rong li jing xiao ying sui wei xie huai hao zhu long lai dui fan hu lai none none ying mi ji lian jian ying fen lin yi jian yue chan dai rang jian lan fan shuangyuan zhuo feng she lei lan cong qu yong qian fa guan que yan hao none sa zan luan yan li mi dan tan dang jiao chan none hao ba zhu lan lan nang wan luan quan xian yan gan yan yu huo biao mie guang deng hui xiao xiao none hong ling zao zhuan jiu zha xie chi zhuo zai zai can yang qi zhong fen niu gui wen po yi lu chui pi kai pan yan kai pang mu chao liao gui kang dun guang xin zhi guang xin wei qiang bian da xia zheng zhu ke zhao fu ba duo duo ling zhuo xuan ju tan pao jiong pao tai tai bing yang tong han zhu zha dian wei shi lian chi ping none hu shuo lan ting jiao xu xing quan lie huan yang xiao xiu xian yin wu zhou yao shi wei tong tong zai kai hong luo xia zhu xuan zheng po yan hui guang zhe hui kao none fan shao ye hui none tang jin re none xi fu jiong che pu jing zhuo ting wan hai peng lang shan hu feng chi rong hu none shu lang xun xun jue xiao xi yan han zhuangqu di xie qi wu none none han yan huan men ju dao bei fen lin kun hun chun xi cui wu hong ju fu yue jiao cong feng ping qiong cui xi qiong xin zhuo yan yan yi jue yu gang ran pi yan none sheng chang shao none none none none chen he kui zhong duan ya hui feng lian xuan xing huang jiao jian bi ying zhu wei tuan tian xi nuan nuan chan yan jiong jiong yu mei sha wu ye ") .append(" xin qiong rou mei huan xu zhao wei fan qiu sui yang lie zhu none gao gua bao hu yun xia none none bian wei tui tang chao shan yun bo huang xie xi wu xi yun he he xi yun xiong nai kao none yao xun ming lian ying wen rong none none qiang liu xi bi biao cong lu jian shu yi lou feng sui yi teng jue zong yun hu yi zhi ao wei liao han ou re jiong man none shang cuan zeng jian xi xi xi yi xiao chi huang chan ye qian ran yan xian qiao zun deng dun shen jiao fen si liao yu lin tong shao fen fan yan xun lan mei tang yi jing men none none ying yu yi xue lan tai zao can sui xi que cong lian hui zhu xie ling wei yi xie zhao hui none none lan ru xian kao xun jin chou dao yao he lan biao rong li mo bao ruo di lu: ao xun kuang shuo none li lu jue liao yan xi xie long yan none rang yue lan cong jue tong guan none che mi tang lan zhu lan ling cuan yu zhua lan pa zheng pao zhao yuan ai wei none jue jue fu ye ba die ye yao zu shuanger pan chuan ke zang zang qiang die qiang pian ban pan shao jian pai du yong tou tou bian die bang bo bang you none du ya cheng niu cheng pin jiu mou ta mu lao ren mang fang mao mu ren wu yan fa bei si jian gu you gu sheng mu di qian quan quan zi te xi mang keng qian wu gu xi li li pou ji gang zhi ben quan run du ju jia jian feng pian ke ju kao chu xi bei luo jie ma san wei li dun tong se jiang xi li du lie pi piao bao xi chou wei kui chou quan quan ba fan qiu bo chai chuo an jie zhuangguang ma you kang bo hou ya han huan zhuangyun kuang niu di qing zhong yun bei pi ju ni sheng pao xia tuo hu ling fei pi ni sheng you gou yue ju dan bo gu xian ning huan hen jiao he zhao ji huan shan ta rong shou tong lao du xia shi kuai zheng yu sun yu bi mang xi juan li xia yin suan lang bei zhi yan sha li zhi xian jing han fei yao ba qi ni biao yin li lie jian qiang kun yan guo zong mi chang yi zhi zheng ya meng cai cu she lie none luo hu zong hu wei feng wo yuan xing zhu mao wei yuan xian tuan ya nao xie jia hou bian you you mei cha yao sun bo ming hua yuan sou ma yuan dai yu shi hao none yi zhen chuanghao man jing jiang mo zhang chan ao ao hao cui ben jue bi bi huang bu lin yu tong yao liao shuo xiao shou none xi ge juan du hui kuai xian xie ta xian xun ning bian huo nou meng lie nao guang shou lu ta xian mi rang huan nao luo xian qi qu xuan miao zi lu: lu yu su wang qiu ga ding le ba ji hong di chuan gan jiu yu qi yu yang ma hong wu fu min jie ya bin bian beng yue jue yun jue wan jian mei dan pi wei huan xian qiang ling dai yi an ping dian fu xuan xi bo ci gou jia shao po ci ke ran sheng shen yi zu jia min shan liu bi zhen zhen jue fa long jin jiao jian li guang xian zhou gong yan xiu yang xu luo su zhu qin ken xun bao er xiang yao xia heng gui chong xu ban pei none dang ying hun wen e cheng ti wu wu cheng jun mei bei ting xian chuo han xuan yan qiu quan lang li xiu fu liu ya xi ling li jin lian suo suo none wan dian bing zhan cui min yu") .append(" ju chen lai wen sheng wei dian chu zhuo pei cheng hu qi e kun chang qi beng wan lu cong guan yan diao bei lin qin pi pa qiang zhuo qin fa none qiong du jie hun yu mao mei chun xuan ti xing dai rou min zhen wei ruan huan xie chuan jian zhuan yang lian quan xia duan yuan ye nao hu ying yu huang rui se liu none rong suo yao wen wu jin jin ying ma tao liu tang li lang gui tian qiang cuo jue zhao yao ai bin tu chang kun zhuan cong jin yi cui cong qi li ying suo qiu xuan ao lian man zhang yin none ying wei lu wu deng none zeng xun qu dang lin liao qiong su huang gui pu jing fan jin liu ji none jing ai bi can qu zao dang jiao gun tan hui huan se sui tian none yu jin fu bin shu wen zui lan xi ji xuan ruan huo gai lei du li zhi rou li zan qiong zhe gui sui la long lu li zan lan ying mi xiang xi guan dao zan huan gua bao die pao hu zhi piao ban rang li wa none jiang qian ban pen fang dan weng ou none none none hu ling yi ping ci none juan chang chi none dang meng bu chui ping bian zhou zhen none ci ying qi xian lou di ou meng zhuan beng lin zeng wu pi dan weng ying yan gan dai shen tian tian han chang sheng qing shen chan chan rui sheng su shen yong shuai lu fu yong beng none ning tian you jia shen zha dian fu nan dian ping ding hua ting quan zai meng bi qi liu xun liu chang mu yun fan fu geng tian jie jie quan wei fu tian mu none pan jiang wa da nan liu ben zhen chu mu mu ce none gai bi da zhi lu:e qi lu:e pan none fan hua yu yu mu jun yi liu she die chou hua dang chuo ji wan jiang cheng chang tun lei ji cha liu die tuan lin jiang jiang chou bo die die pi nie dan shu shu zhi yi chuangnai ding bi jie liao gong ge jiu zhou xia shan xu nu:e li yang chen you ba jie jue xi xia cui bi yi li zong chuangfeng zhu pao pi gan ke ci xie qi dan zhen fa zhi teng ju ji fei ju dian jia xuan zha bing nie zheng yong jing quan chong tong yi jie wei hui duo yang chi zhi hen ya mei dou jing xiao tong tu mang pi xiao suan pu li zhi cuo duo wu sha lao shou huan xian yi peng zhang guan tan fei ma lin chi ji tian an chi bi bi min gu dui e wei yu cui ya zhu xi dan shen zhong ji yu hou feng la yang shen tu yu gua wen huan ku jia yin yi lou sao jue chi xi guan yi wen ji chuangban lei liu chai shou nu:e dian da bie tan zhang biao shen cu luo yi zong chou zhang zhai sou suo que diao lou lou mo jin yin ying huang fu liao long qiao liu lao xian fei dan yin he ai ban xian guan guai nong yu wei yi yong pi lei li shu dan lin dian lin lai bie ji chi yang xuan jie zheng none li huo lai ji dian xian ying yin qu yong tan dian luo luan luan bo none gui po fa deng fa bai bai qie bi zao zao mao de pa jie huang gui ci ling gao mo ji jiao peng gao ai e hao han bi wan chou qian xi ai jiong hao huang hao ze cui hao xiao ye po hao jiao ai xing huang li piao he jiao pi gan pao zhou jun qiu cun que zha gu jun jun zhou zha gu zhan du min qi ying yu bei zhao zhong pen he ying he yi bo wan he ang zhan yan jian ") .append("he yu kui fan gai dao pan fu qiu sheng dao lu zhan meng lu jin xu jian pan guan an lu xu zhou dang an gu li mu ding gan xu mang mang zhi qi wan tian xiang dun xin xi pan feng dun min ming sheng shi yun mian pan fang miao dan mei mao kan xian kou shi yang zheng yao shen huo da zhen kuang ju shen yi sheng mei mo zhu zhen zhen mian di yuan die yi zi zi chao zha xuan bing mi long sui tong mi die yi er ming xuan chi kuang juan mou zhen tiao yang yan mo zhong mai zhe zheng mei suo shao han huan di cheng cuo juan e wan xian xi kun lai jian shan tian hun wan ling shi qiong lie ya jing zheng li lai sui juan shui sui du pi pi mu hun ni lu gao jie cai zhou yu hun ma xia xing hui gun none chun jian mei du hou xuan ti kui gao rui mao xu fa wen miao chou kui mi weng kou dang chen ke sou xia qiong mao ming man shui ze zhang yi diao kou mo shun cong lou chi man piao cheng ji meng huan run pie xi qiao pu zhu deng shen shun liao che xian kan ye xu tong wu lin kui jian ye ai hui zhan jian gu zhao ju wei chou ji ning xun yao huo meng mian bin mian li guang jue xuan mian huo lu meng long guan man xi chu tang kan zhu mao jin lin yu shuo ce jue shi yi shen zhi hou shen ying ju zhou jiao cuo duan ai jiao zeng huo bai shi ding qi ji zi gan wu tuo ku qiang xi fan kuang dang ma sha dan jue li fu min nuo hua kang zhi qi kan jie fen e ya pi zhe yan sui zhuan che dun pan yan none feng fa mo zha qu yu ke tuo tuo di zhai zhen e fu mu zhu la bian nu ping peng ling pao le po bo po shen za ai li long tong none li kuang chu keng quan zhu kuang gui e nao jia lu wei ai luo ken xing yan dong peng xi none hong shuo xia qiao none wei qiao none keng xiao que chan lang hong yu xiao xia mang long none che che wo liu ying mang que yan cuo kun yu none none lu chen jian none song zhuo keng peng yan zhui kong ceng qi zong qing lin jun bo ding min diao jian he liu ai sui que ling bei yin dui wu qi lun wan dian gang bei qi chen ruan yan die ding zhou tuo jie ying bian ke bi wei shuo zhen duan xia dang ti nao peng jian di tan cha none qi none feng xuan que que ma gong nian su e ci liu si tang bang hua pi wei sang lei cuo tian xia xi lian pan wei yun dui zhe ke la none qing gun zhuan chan qi ao peng lu lu kan qiang chen yin lei biao qi mo qi cui zong qing chuo none ji shan lao qu zeng deng jian xi lin ding dian huang pan za qiao di li jian jiao xi zhang qiao dun jian yu zhui he huo zhai lei ke chu ji que dang wo jiang pi pi yu pin qi ai ke jian yu ruan meng pao zi bo none mie ca xian kuang lei lei zhi li li fan que pao ying li long long mo bo shuangguan lan zan yan shi shi li reng she yue si qi ta ma xie yao xian zhi qi zhi beng shu chong none yi shi you zhi tiao fu fu mi zu zhi suan mei zuo qu hu zhu shen sui ci chai mi lu: yu xiang wu tiao piao zhu gui xia zhi ji gao zhen gao shui jin zhen gai kun di dao huo tao qi gu guan zui ling lu bing jin dao zhi lu shan bei zhe hui you xi ") .append(" yin zi huo zhen fu yuan wu xian yang ti yi mei si di none zhuo zhen yong ji gao tang chi ma ta none xuan qi yu xi ji si chan xuan hui sui li nong ni dao li rang yue ti zan lei rou yu yu li xie qin he tu xiu si ren tu zi cha gan yi xian bing nian qiu qiu zhong fen hao yun ke miao zhi jing bi zhi yu mi ku ban pi ni li you zu pi ba ling mo cheng nian qin yang zuo zhi zhi shu ju zi tai ji cheng tong zhi huo he yin zi zhi jie ren du yi zhu hui nong fu xi kao lang fu ze shui lu: kun gan jing ti cheng tu shao shui ya lun lu gu zuo ren zhun bang bai ji zhi zhi kun leng peng ke bing chou zui yu su none none yi xi bian ji fu bi nuo jie zhong zong xu cheng dao wen lian zi yu ji xu zhen zhi dao jia ji gao gao gu rong sui none ji kang mu shan men zhi ji lu su ji ying wen qiu se none yi huang qie ji sui xiao pu jiao zhuo tong none lu: sui nong se hui rang nuo yu none ji tui wen cheng huo gong lu: biao none rang jue li zan xue wa jiu qiong xi qiong kong yu sen jing yao chuan zhun tu lao qie zhai yao bian bao yao bing yu zhu jiao qiao diao wu gui yao zhi chuan yao tiao jiao chuangjiong xiao cheng kou cuan wo dan ku ke zhui xu su none kui dou none yin wo wa ya yu ju qiong yao yao tiao liao yu tian diao ju liao xi wu kui chuangju none kuan long cheng cui piao zao cuan qiao qiong dou zao zao qie li chu shi fu qian chu hong qi qian gong shi shu miao ju zhan zhu ling long bing jing jing zhang yi si jun hong tong song jing diao yi shu jing qu jie ping duan shao zhuan ceng deng cun huai jing kan jing zhu zhu le peng yu chi gan mang zhu none du ji xiao ba suan ji zhen zhao sun ya zhui yuan hu gang xiao cen pi bi jian yi dong shan sheng xia di zhu na chi gu li qie min bao tiao si fu ce ben fa da zi di ling ze nu fu gou fan jia ge fan shi mao po none jian qiong long none bian luo gui qu chi yin yao xian bi qiong gua deng jiao jin quan sun ru fa kuang zhu tong ji da hang ce zhong kou lai bi shai dang zheng ce fu yun tu pa li lang ju guan jian han tong xia zhi cheng suan shi zhu zuo xiao shao ting jia yan gao kuai gan chou kuang gang yun none qian xiao jian pu lai zou bi bi bi ge chi guai yu jian zhao gu chi zheng qing sha zhou lu bo ji lin suan jun fu zha gu kong qian qian jun chui guan yuan ce ju bo ze qie tuo luo dan xiao ruo jian none bian sun xiang xian ping zhen sheng hu shi zhu yue chun fu wu dong shuo ji jie huang xing mei fan chuan zhuan pian feng zhu hong qie hou qiu miao qian none kui none lou yun he tang yue chou gao fei ruo zheng gou nie qian xiao cuan gong pang du li bi zhuo chu shai chi zhu qiang long lan jian bu li hui bi di cong yan peng sen cuan pai piao dou yu mie zhuan ze xi guo yi hu chan kou cu ping zao ji gui su lou zha lu nian suo cuan none suo le duan liang xiao bo mi shai dang liao dan dian fu jian min kui dai qiao deng huang sun lao zan xiao lu shi zan none pai qi pai gan ju du lu yan bo dang sai ke gou qian lian bu zhou lai none la") .append("n kui yu yue hao zhen tai ti mi chou ji none qi teng zhuan zhou fan sou zhou qian kuo teng lu lu jian tuo ying yu lai long none lian lan qian yue zhong qu lian bian duan zuan li shai luo ying yue zhuo xu mi di fan shen zhe shen nu: xie lei xian zi ni cun zhang qian none bi ban wu sha kang rou fen bi cui yin li chi tai none ba li gan ju po mo cu zhan zhou li su tiao li xi su hong tong zi ce yue zhou lin zhuangbai none fen mian qu none liang xian fu liang can jing li yue lu ju qi cui bai chang lin zong jing guo none san san tang bian rou mian hou xu zong hu jian zan ci li xie fu nuo bei gu xiu gao tang qiu none cao zhuangtang mi san fen zao kang jiang mo san san nuo chi liang jiang kuai bo huan shu zong jian nuo tuan nie li zuo di nie tiao lan mi mi jiu xi gong zheng jiu you ji cha zhou xun yue hong yu he wan ren wen wen qiu na zi tou niu fou jie shu chun pi yin sha hong zhi ji fen yun ren dan jin su fang suo cui jiu zha ba jin fu zhi qi zi chou hong zha lei xi fu xie shen bei zhu qu ling zhu shao gan yang fu tuo zhen dai chu shi zhong xian zu jiong ban ju pa shu zui kuang jing ren heng xie jie zhu chou gua bai jue kuang hu ci geng geng tao xie ku jiao quan gai luo xuan beng xian fu gei tong rong tiao yin lei xie quan xu hai die tong si jiang xiang hui jue zhi jian juan chi mian zhen lu: cheng qiu shu bang tong xiao wan qin geng xiu ti xiu xie hong xi fu ting sui dui kun fu jing hu zhi yan jiong feng ji xu none zong lin duo li lu: liang chou quan shao qi qi zhun qi wan qian xian shou wei qi tao wan gang wang beng zhui cai guo cui lun liu qi zhan bei chuo ling mian qi jie tan zong gun zou yi zi xing liang jin fei rui min yu zong fan lu: xu none shang none xu xiang jian ke xian ruan mian ji duan zhong di min miao yuan xie bao si qiu bian huan geng zong mian wei fu wei yu gou miao jie lian zong bian yun yin ti gua zhi yun cheng chan dai jia yuan zong xu sheng none geng none ying jin yi zhui ni bang gu pan zhou jian cuo quan shuangyun xia shuai xi rong tao fu yun zhen gao ru hu zai teng xian su zhen zong tao huang cai bi feng cu li suo yin xi zong lei zhuan qian man zhi lu: mo piao lian mi xuan zong ji shan sui fan shuai beng yi sao mou zhou qiang hun xian xi none xiu ran xuan hui qiao zeng zuo zhi shan san lin yu fan liao chuo zun jian rao chan rui xiu hui hua zuan xi qiang none da sheng hui xi se jian jiang huan qiao cong jie jiao bo chan yi nao sui yi shai xu ji bin qian jian pu xun zuan qi peng li mo lei xie zuan kuang you xu lei xian chan none lu chan ying cai xiang xian zui zuan luo xi dao lan lei lian mi jiu yu hong zhou xian he yue ji wan kuang ji ren wei yun hong chun pi sha gang na ren zong lun fen zhi wen fang zhu zhen niu shu xian gan xie fu lian zu shen xi zhi zhong zhou ban fu chu shao yi jing dai bang rong jie ku rao die hang hui ji xuan jiang luo jue jiao tong geng xiao juan xiu xi sui tao ji ti ji xu ling yin xu qi fei chuo shang gun sheng wei mian shou beng chou tao liu quan ") .append("zong zhan wan lu: zhui zi ke xiang jian mian lan ti miao ji yun hui si duo duan bian xian gou zhui huan di lu: bian min yuan jin fu ru zhen feng cui gao chan li yi jian bin piao man lei ying suo mou sao xie liao shan zeng jiang qian qiao huan jiao zuan fou xie gang fou que fou que bo ping hou none gang ying ying qing xia guan zun tan none qing weng ying lei tan lu guan wang gang wang wang han none luo fu mi fa gu zhu ju mao gu min gang ba gua ti juan fu lin yan zhao zui gua zhuo yu zhi an fa lan shu si pi ma liu ba fa li chao wei bi ji zeng tong liu ji juan mi zhao luo pi ji ji luan yang mie qiang ta mei yang you you fen ba gao yang gu qiang zang gao ling yi zhu di xiu qiang yi xian rong qun qun qian huan suo xian yi yang qiang xian yu geng jie tang yuan xi fan shan fen shan lian lei geng nou qiang chan yu gong yi chong weng fen hong chi chi cui fu xia pen yi la yi pi ling liu zhi qu xi xie xiang xi xi qi qiao hui hui shu se hong jiang zhai cui fei tao sha chi zhu jian xuan shi pian zong wan hui hou he he han ao piao yi lian qu none lin pen qiao ao fan yi hui xuan dao yao lao none kao mao zhe qi gou gou gou die die er shua ruan er nai zhuan lei ting zi geng chao hao yun pa pi chi si qu jia ju huo chu lao lun ji tang ou lou nou jiang pang ze lou ji lao huo you mo huai er zhe ding ye da song qin yun chi dan dan hong geng zhi none nie dan zhen che ling zheng you wa liao long zhi ning tiao er ya die guo none lian hao sheng lie pin jing ju bi di guo wen xu ping cong none none ting yu cong kui lian kui cong lian weng kui lian lian cong ao sheng song ting kui nie zhi dan ning none ji ting ting long yu yu zhao si su yi su si zhao zhao rou yi lei ji qiu ken cao ge di huan huang yi ren xiao ru zhou yuan du gang rong gan cha wo chang gu zhi qin fu fei ban pei pang jian fang zhun you na ang ken ran gong yu wen yao jin pi qian xi xi fei ken jing tai shen zhong zhang xie shen wei zhou die dan fei ba bo qu tian bei gua tai zi ku zhi ni ping zi fu pang zhen xian zuo pei jia sheng zhi bao mu qu hu ke yi yin xu yang long dong ka lu jing nu yan pang kua yi guang hai ge dong zhi jiao xiong xiong er an xing pian neng zi none cheng tiao zhi cui mei xie cui xie mo mai ji xie none kuai sa zang qi nao mi nong luan wan bo wen wan qiu jiao jing you heng cuo lie shan ting mei chun shen xie none juan cu xiu xin tuo pao cheng nei fu dou tuo niao nao pi gu luo li lian zhang cui jie liang shui pi biao lun pian guo juan chui dan tian nei jing jie la ye a ren shen chuo fu fu ju fei qiang wan dong pi guo zong ding wu mei ruan zhuan zhi cou gua ou di an xing nao shu shuan nan yun zhong rou e sai tu yao jian wei jiao yu jia duan bi chang fu xian ni mian wa teng tui bang qian lu: wa shou tang su zhui ge yi bo liao ji pi xie gao lu: bin none chang lu guo pang chuai biao jiang fu tang mo xi zhuan lu: jiao ying lu: zhi xue chun lin tong peng ni chuai liao cui gui xiao teng fan zhi jiao shan hu ") .append(" cui run xin sui fen ying shan gua dan kuai nong tun lian bei yong jue chu yi juan la lian sao tun gu qi cui bin xun nao huo zang xian biao xing kuan la yan lu hu za luo qu zang luan ni za chen qian wo guang zang lin guang zi jiao nie chou ji gao chou mian nie zhi zhi ge jian die zhi xiu tai zhen jiu xian yu cha yao yu chong xi xi jiu yu yu xing ju jiu xin she she she jiu shi tan shu shi tian dan pu pu guan hua tian chuan shun xia wu zhou dao chuan shan yi none pa tai fan ban chuan hang fang ban bi lu zhong jian cang ling zhu ze duo bo xian ge chuan jia lu hong pang xi none fu zao feng li shao yu lang ting none wei bo meng nian ju huang shou zong bian mao die none bang cha yi sou cang cao lou dai none yao chong none dang qiang lu yi jie jian huo meng qi lu lu chan shuanggen liang jian jian se yan fu ping yan yan cao cao yi le ting jiao ai nai tiao jiao jie peng wan yi chai mian mi gan qian yu yu shao xiong du xia qi mang zi hui sui zhi xiang bi fu tun wei wu zhi qi shan wen qian ren fou kou jie lu zhu ji qin qi yan fen ba rui xin ji hua hua fang wu jue gou zhi yun qin ao chu mao ya fei reng hang cong yin you bian yi none wei li pi e xian chang cang zhu su yi yuan ran ling tai tiao di miao qing li rao ke mu pei bao gou min yi yi ju pie ruo ku zhu ni bo bing shan qiu yao xian ben hong ying zha dong ju die nie gan hu ping mei fu sheng gu bi wei fu zhuo mao fan qie mao mao ba zi mo zi di chi gou jing long none niao none xue ying qiong ge ming li rong yin gen qian chai chen yu xiu zi lie wu duo kui ce jian ci gou guang mang cha jiao jiao fu yu zhu zi jiang hui yin cha fa rong ru chong mang tong zhong none zhu xun huan kua quan gai da jing xing chuan cao jing er an shou chi ren jian ti huang ping li jin lao rong zhuangda jia rao bi ce qiao hui ji dang none rong hun ying luo ying qian jin sun yin mai hong zhou yao du wei chu dou fu ren yin he bi bu yun di tu sui sui cheng chen wu bie xi geng li pu zhu mo li zhuangji duo qiu sha suo chen feng ju mei meng xing jing che xin jun yan ting you cuo guan han you cuo jia wang you niu shao xian lang fu e mo wen jie nan mu kan lai lian shi wo tu xian huo you ying ying none chun mang mang ci yu jing di qu dong jian zou gu la lu ju wei jun nie kun he pu zai gao guo fu lun chang chou song chui zhan men cai ba li tu bo han bao qin juan xi qin di jie pu dang jin zhao tai geng hua gu ling fei jin an wang beng zhou yan zu jian lin tan shu tian dao hu ji he cui tao chun bei chang huan fei lai qi meng ping wei dan sha huan yan yi tiao qi wan ce nai none tuo jiu tie luo none none meng none none ding ying ying ying xiao sa qiu ke xiang wan yu yu fu lian xuan xuan nan ze wo chun xiao yu pian mao an e luo ying huo gua jiang wan zuo zuo ju bao rou xi xie an qu jian fu lu: lu: pen feng hong hong hou yan tu zhu zi xiang shen ge qia jing mi huang shen pu ge dong zhou qian wei bo wei pa ji hu zang ji") .append("a duan yao jun cong quan wei xian kui ting hun xi shi qi lan zong yao yuan mei yun shu di zhuan guan none qiong chan kai kui none jiang lou wei pai none sou yin shi chun shi yun zhen lang nu meng he que suan yuan li ju xi bang chu xu tu liu huo zhen qian zu po cuo yuan chu yu kuai pan pu pu na shuo xi fen yun zheng jian ji ruo cang en mi hao sun zhen ming none xu liu xi gu lang rong weng gai cuo shi tang luo ru suo xian bei yao gui bi zong gun none xiu ce none lan none ji li can lang yu none ying mo diao xiu wu tong zhu peng an lian cong xi ping qiu jin chun jie wei tui cao yu yi ji liao bi lu xu bu zhang luo qiang man yan leng ji biao gun han di su lu she shang di mie xun man bo di cuo zhe sen xuan yu hu ao mi lou cu zhong cai po jiang mi cong niao hui jun yin jian nian shu yin kui chen hu sha kou qian ma cang ze qiang dou lian lin kou ai bi li wei ji qian sheng fan meng ou chan dian xun jiao rui rui lei yu qiao chu hua jian mai yun bao you qu lu rao hui e ti fei jue zui fa ru fen kui shun rui ya xu fu jue dang wu tong si xiao xi yong wen shao qi jian yun sun ling yu xia weng ji hong si deng lei xuan yun yu xi hao bo hao ai wei hui wei ji ci xiang luan mie yi leng jiang can shen qiang lian ke yuan da ti tang xue bi zhan sun lian fan ding xiao gu xie shu jian kao hong sa xin xun yao bai sou shu xun dui pin wei neng chou mai ru piao tai qi zao chen zhen er ni ying gao cong xiao qi fa jian xu kui jie bian di mi lan jin zang miao qiong qie xian none ou xian su lu: yi xu xie li yi la lei jiao di zhi pi teng yao mo huan biao fan sou tan tui qiong qiao wei liu hui shu gao yun none li zhu zhu ai lin zao xuan chen lai huo tuo wu rui rui qi heng lu su tui mang yun pin yu xun ji jiong xuan mo none su jiong none nie bo rang yi xian yu ju lian lian yin qiang ying long tou wei yue ling qu yao fan mi lan kui lan ji dang none lei lei tong feng zhi wei kui zhan huai li ji mi lei huai luo ji nao lu jian none none lei quan xiao yi luan men bie hu hu lu nu:e lu: zhi xiao qian chu hu xu cuo fu xu xu lu hu yu hao jiao ju guo bao yan zhan zhan kui ban xi shu chong qiu diao ji qiu ding shi none di zhe she yu gan zi hong hui meng ge sui xia chai shi yi ma xiang fang e pa chi qian wen wen rui bang pi yue yue jun qi ran yin qi can yuan jue hui qian qi zhong ya hao mu wang fen fen hang gong zao fu ran jie fu chi dou bao xian ni te qiu you zha ping chi you he han ju li fu ran zha gou pi bo xian zhu diao bie bing gu ran qu she tie ling gu dan gu ying li cheng qu mou ge ci hui hui mang fu yang wa lie zhu yi xian kuo jiao li yi ping ji ha she yi wang mo qiong qie gui gong zhi man none zhe jia nao si qi xing lie qiu shao yong jia tui che bai e han shu xuan feng shen zhen fu xian zhe wu fu li lang bi chu yuan you jie dan yan ting dian tui hui wo zhi song fei ju mi qi qi yu jun la meng qiang si xi ") .append("lun li die tiao tao kun gan han yu bang fei pi wei dun yi yuan su quan qian rui ni qing wei liang guo wan dong e ban zhuo wang can yang ying guo chan none la ke ji xie ting mai xu mian yu jie shi xuan huang yan bian rou wei fu yuan mei wei fu ruan xie you you mao xia ying shi chong tang zhu zong ti fu yuan kui meng la du hu qiu die li gua yun ju nan lou chun rong ying jiang tun lang pang si xi xi xi yuan weng lian sou ban rong rong ji wu xiu han qin yi bi hua tang yi du nai he hu xi ma ming yi wen ying teng yu cang none none man none shang shi cao chi di ao lu wei zhi tang chen piao qu pi yu jian luo lou qin zhong yin jiang shuai wen jiao wan zhe zhe ma ma guo liao mao xi cong li man xiao none zhang mang xiang mo zi si qiu te zhi peng peng jiao qu bie liao pan gui xi ji zhuan huang fei lao jue jue hui yin chan jiao shan rao xiao wu chong xun si none cheng dang li xie shan yi jing da chan qi zi xiang she luo qin ying chai li ze xuan lian zhu ze xie mang xie qi rong jian meng hao ru huo zhuo jie bin he mie fan lei jie la mi li chun li qiu nie lu du xiao zhu long li long feng ye pi rang gu juan ying none xi can qu quan du can man qu jie zhu zha xue huang nu: pei nu: xin zhong mo er mie mie shi xing yan kan yuan none ling xuan shu xian tong long jie xian ya hu wei dao chong wei dao zhun heng qu yi yi bu gan yu biao cha yi shan chen fu gun fen shuai jie na zhong dan ri zhong zhong xie qi xie ran zhi ren qin jin jun yuan mei chai ao niao hui ran jia tuo ling dai bao pao yao zuo bi shao tan ju he xue xiu zhen yi pa bo di wa fu gun zhi zhi ran pan yi mao none na kou xuan chan qu bei yu xi none bo none fu yi chi ku ren jiang jia cun mo jie er ge ru zhu gui yin cai lie none none zhuangdang none kun ken niao shu jia kun cheng li juan shen pou ge yi yu chen liu qiu qun ji yi bu zhuangshui sha qun li lian lian ku jian fou tan bi gun tao yuan ling chi chang chou duo biao liang shang pei pei fei yuan luo guo yan du ti zhi ju qi ji zhi gua ken none ti shi fu chong xie bian die kun duan xiu xiu he yuan bao bao fu yu tuan yan hui bei chu lu: none none yun ta gou da huai rong yuan ru nai jiong suo ban tun chi sang niao ying jie qian huai ku lian lan li zhe shi lu: yi die xie xian wei biao cao ji qiang sen bao xiang none pu jian zhuan jian zui ji dan za fan bo xiang xin bie rao man lan ao duo hui cao sui nong chan lian bi jin dang shu tan bi lan pu ru zhi none shu wa shi bai xie bo chen lai long xi xian lan zhe dai none zan shi jian pan yi none ya xi xi yao feng tan none none fu ba he ji ji jian guan bian yan gui jue pian mao mi mi mie shi si zhan luo jue mo tiao lian yao zhi jun xi shan wei xi tian yu lan e du qin pang ji ming ping gou qu zhan jin guan deng jian luo qu jian wei jue qu luo lan shen di guan jian guan yan gui mi shi chan lan jue ji xi di tian yu gou jin qu jiao jiu jin cu jue zhi chao ji gu dan zui di shan") .append("g hua quan ge zhi jie gui gong chu jie huan qiu xing su ni ji lu zhi zhu bi xing hu shang gong zhi xue chu xi yi li jue xi yan xi yan yan ding fu qiu qiu jiao hong ji fan xun diao hong cha tao xu jie yi ren xun yin shan qi tuo ji xun yin e fen ya yao song shen yin xin jue xiao ne chen you zhi xiong fang xin chao she xian sa zhun xu yi yi su chi he shen he xu zhen zhu zheng gou zi zi zhan gu fu jian die ling di yang li nao pan zhou gan shi ju ao zha tuo yi qu zhao ping bi xiong chu ba da zu tao zhu ci zhe yong xu xun yi huang he shi cha jiao shi hen cha gou gui quan hui jie hua gai xiang hui shen chou tong mi zhan ming e hui yan xiong gua er beng tiao chi lei zhu kuang kua wu yu teng ji zhi ren su lang e kuang e^ shi ting dan bei chan you heng qiao qin shua an yu xiao cheng jie xian wu wu gao song pu hui jing shuo zhen shuo du none chang shui jie ke qu cong xiao sui wang xuan fei chi ta yi na yin diao pi chuo chan chen zhun ji qi tan chui wei ju qing jian zheng ze zou qian zhuo liang jian zhu hao lun shen biao huai pian yu die xu pian shi xuan shi hun hua e zhong di xie fu pu ting jian qi yu zi chuan xi hui yin an xian nan chen feng zhu yang yan heng xuan ge nuo qi mou ye wei none teng zou shan jian bo none huang huo ge ying mi xiao mi xi qiang chen nu:e si su bang chi qian shi jiang yuan xie xue tao yao yao hu yu biao cong qing li mo mo shang zhe miu jian ze zha lian lou can ou guan xi zhuo ao ao jin zhe yi hu jiang man chao han hua chan xu zeng se xi she dui zheng nao lan e ying jue ji zun jiao bo hui zhuan wu jian zha shi qiao tan zen pu sheng xuan zao zhan dang sui qian ji jiao jing lian nou yi ai zhan pi hui hua yi yi shan rang nou qian zhui ta hu zhou hao ni ying jian yu jian hui du zhe xuan zan lei shen wei chan li yi bian zhe yan e chou wei chou yao chan rang yin lan chen huo zhe huan zan yi dang zhan yan du yan ji ding fu ren ji jie hong tao rang shan qi tuo xun yi xun ji ren jiang hui ou ju ya ne xu e lun xiong song feng she fang jue zheng gu he ping zu shi xiong zha su zhen di zhou ci qu zhao bi yi yi kuang lei shi gua shi jie hui cheng zhu shen hua dan gou quan gui xun yi zheng gai xiang cha hun xu zhou jie wu yu qiao wu gao you hui kuang shuo song ei qing zhu zou nuo du zhuo fei ke wei yu shei shen diao chan liang zhun sui tan shen yi mou chen die huang jian xie xue ye wei e yu xuan chan zi an yan di mi pian xu mo dang su xie yao bang shi qian mi jin man zhe jian miu tan jian qiao lan pu jue yan qian zhan chen gu qian hong ya jue hong han hong qi xi huo liao han du long dou jiang qi chi feng deng wan bi shu xian feng zhi zhi yan yan shi chu hui tun yi tun yi jian ba hou e cu xiang huan jian ken gai qu fu xi bin hao yu zhu jia fen xi hu wen huan bin di zong fen yi zhi bao chai han pi na pi gou duo you diao mo si xiu huan kun he he mo an mao li ni bi yu jia tuan mao pi xi e ju") .append(" mo chu tan huan qu bei zhen yuan fu cai gong te yi hang wan pin huo fan tan guan ze zhi er zhu shi bi zi er gui pian bian mai dai sheng kuang fei tie yi chi mao he bi lu lin hui gai pian zi jia xu zei jiao gai zang jian ying xun zhen she bin bin qiu she chuan zang zhou lai zan si chen shang tian pei geng xian mai jian sui fu dan cong cong zhi ji zhang du jin xiong shun yun bao zai lai feng cang ji sheng ai zhuan fu gou sai ze liao wei bai chen zhuan zhi zhui biao yun zeng tan zan yan none shan wan ying jin gan xian zang bi du shu yan none xuan long gan zang bei zhen fu yuan gong cai ze xian bai zhang huo zhi fan tan pin bian gou zhu guan er jian bi shi tie gui kuang dai mao fei he yi zei zhi jia hui zi lin lu zang zi gai jin qiu zhen lai she fu du ji shu shang ci bi zhou geng pei dan lai feng zhui fu zhuan sai ze yan zan yun zeng shan ying gan chi xi she nan xiong xi cheng he cheng zhe xia tang zou zou li jiu fu zhao gan qi shan qiong qin xian ci jue qin chi ci chen chen die ju chao di se zhan zhu yue qu jie chi chu gua xue zi tiao duo lie gan suo cu xi zhao su yin ju jian que tang chuo cui lu qu dang qiu zi ti qu chi huang qiao qiao yao zao yue none zan zan zu pa bao ku he dun jue fu chen jian fang zhi ta yue pa qi yue qiang tuo tai yi nian ling mei ba die ku tuo jia ci pao qia zhu ju die zhi fu pan ju shan bo ni ju li gen yi ji dai xian jiao duo chu quan kua zhuai gui qiong kui xiang chi lu beng zhi jia tiao cai jian da qiao bi xian duo ji ju ji shu tu chu xing nie xiao bo xue qun mou shu liang yong jiao chou xiao none ta jian qi wo wei chuo jie ji nie ju ju lun lu leng huai ju chi wan quan ti bo zu qie qi cu zong cai zong pan zhi zheng dian zhi yu duo dun chun yong zhong di zha chen chuai jian gua tang ju fu zu die pian rou nuo ti cha tui jian dao cuo xi ta qiang zhan dian ti ji nie pan liu zhan bi chong lu liao cu tang dai su xi kui ji zhi qiang di man zong lian beng zao nian bie tui ju deng ceng xian fan chu zhong dun bo cu zu jue jue lin ta qiao qiao pu liao dun cuan kuang zao ta bi bi zhu ju chu qiao dun chou ji wu yue nian lin lie zhi li zhi chan chu duan wei long lin xian wei zuan lan xie rang xie nie ta qu jie cuan zuan xi kui jue lin shen gong dan none qu ti duo duo gong lang none luo ai ji ju tang none none yan none kang qu lou lao duo zhi none ti dao none yu che ya gui jun wei yue xin di xuan fan ren shan qiang shu tun chen dai e na qi mao ruan ren qian zhuan hong hu qu huang di ling dai ao zhen fan kuang ang peng bei gu gu pao zhu rong e ba zhou zhi yao ke yi qing shi ping er qiong ju jiao guang lu kai quan zhou zai zhi ju liang yu shao you huan yun zhe wan fu qing zhou ni ling zhe zhan liang zi hui wang chuo guo kan yi peng qian gun nian ping guan bei lun pai liang ruan rou ji yang xian chuan cou chun ge you hong shu fu zi fu wen ben zhan yu wen tao gu zhen xia yuan lu jiu chao zhuan wei hun none che jiao zhan ") .append("pu lao fen fan lin ge se kan huan yi ji dui er yu xian hong lei pei li li lu lin che ya gui xuan dai ren zhuan e lun ruan hong gu ke lu zhou zhi yi hu zhen li yao qing shi zai zhi jiao zhou quan lu jiao zhe fu liang nian bei hui gun wang liang chuo zi cou fu ji wen shu pei yuan xia zhan lu zhe lin xin gu ci ci pi zui bian la la ci xue ban bian bian bian none bian ban ci bian bian chen ru nong nong zhen chuo chuo none reng bian bian none none liao da chan gan qian yu yu qi xun yi guo mai qi za wang none zhun ying ti yun jin hang ya fan wu ta e hai zhei none jin yuan wei lian chi che ni tiao zhi yi jiong jia chen dai er di po wang die ze tao shu tuo none jing hui tong you mi beng ji nai yi jie zhui lie xun tui song shi tao pang hou ni dun jiong xuan xun bu you xiao qiu tou zhu qiu di di tu jing ti dou yi zhe tong guang wu shi cheng su zao qun feng lian suo hui li none zui ben cuo jue beng huan dai lu you zhou jin yu chuo kui wei ti yi da yuan luo bi nuo yu dang sui dun sui yan chuan chi ti yu shi zhen you yun e bian guo e xia huang qiu dao da wei none yi gou yao chu liu xun ta di chi yuan su ta qian none yao guan zhang ao shi ce su su zao zhe dun zhi lou chi cuo lin zun rao qian xuan yu yi wu liao ju shi bi yao mai xie sui huan zhan deng er miao bian bian la li yuan you luo li yi ting deng qi yong shan han yu mang ru qiong none kuang fu kang bin fang xing nei none shen bang yuan cun huo xie bang wu ju you han tai qiu bi pi bing shao bei wa di zou ye lin kuang gui zhu shi ku yu gai he qie zhi ji xun hou xing jiao xi gui nuo lang jia kuai zheng lang yun yan cheng dou xi lu: fu wu fu gao hao lang jia geng jun ying bo xi bei li yun bu xiao qi pi qing guo none tan zou ping lai ni chen you bu xiang dan ju yong qiao yi dou yan mei ruo bei e yu juan yu yun hou kui xiang xiang sou tang ming xi ru chu zi zou ju wu xiang yun hao yong bi mao chao fu liao yin zhuan hu qiao yan zhang fan wu xu deng bi xin bi ceng wei zheng mao shan lin po dan meng ye cao kuai feng meng zou kuang lian zan chan you qi yan chan cuo ling huan xi feng zan li you ding qiu zhuo pei zhou yi gan yu jiu yan zui mao dan xu tou zhen fen none none yun tai tian qia tuo zuo han gu su fa chou dai ming lao chuo chou you tong zhi xian jiang cheng yin tu jiao mei ku suan lei pu zui hai yan shi niang wei lu lan yan tao pei zhan chun tan zui chuo cu kun ti xian du hu xu xing tan qiu chun yun fa ke sou mi quan chou cuo yun yong ang zha hai tang jiang piao lao yu li zao lao yi jiang bu jiao xi tan fa nong yi li ju yan yi niang ru xun chou yan ling mi mi niang xin jiao shi mi yan bian cai shi you shi shi li zhong ye liang li jin jin ga yi liao dao zhao ding li qiu he fu zhen zhi ba luan fu nai diao shan qiao kou chuan zi fan yu hua han gong qi mang jian di si xi yi chai ta tu xi nu: qian none jian pi ye yin ba fang chen jian tou yue yan fu bu ") .append(" na xin e jue dun gou yin qian ban ji ren chao niu fen yun yi qin pi guo hong yin jun shi yi zhong nie gai ri huo tai kang none lu none none duo zi ni tu shi min gu ke ling bing yi gu ba pi yu si zuo bu you dian jia zhen shi shi tie ju zhan ta she xuan zhao bao he bi sheng chu shi bo zhu chi za po tong qian fu zhai liu qian fu li yue pi yang ban bo jie gou shu zheng mu ni xi di jia mu tan shen yi si kuang ka bei jian tong xing hong jiao chi er ge bing shi mou jia yin jun zhou chong shang tong mo lei ji yu xu ren cun zhi qiong shan chi xian xing quan pi yi zhu hou ming kua yao xian xian xiu jun cha lao ji yong ru mi yi yin guang an diu you se kao qian luan none ai diao han rui shi keng qiu xiao zhe xiu zang ti cuo gua gong zhong dou lu: mei lang wan xin yun bei wu su yu chan ting bo han jia hong cuan feng chan wan zhi si xuan wu wu tiao gong zhuo lu:e xing qin shen han none ye chu zeng ju xian e mang pu li shi rui cheng gao li te none zhu none tu liu zui ju chang yuan jian gang diao tao chang lun guo ling bei lu li qing pei juan min zui peng an pi xian ya zhui lei a kong ta kun du wei chui zi zheng ben nie cong chun tan ding qi qian zhuo qi yu jin guan mao chang dian xi lian tao gu cuo shu zhen lu meng lu hua biao ga lai ken zhui none nai wan zan none de xian none huo liang none men kai ying di lian guo xian du tu wei cong fu rou ji e rou chen ti zha hong yang duan xia yu keng xing huang wei fu zhao cha qie she hong kui nuo mou qiao qiao hou zhen huo huan ye min jian duan jian si kui hu xuan zang jie zhen bian zhong zi xiu ye mei pai ai jie none mei cha ta bang xia lian suo xi liu zu ye nou weng rong tang suo qiang ge shuo chui bo pan ta bi sang gang zi wu ying huang tiao liu kai sun sha sou wan hao zhen zhen luo yi yuan tang nie xi jia ge ma juan rong none suo none none none na lu suo kou zu tuan xiu guan xuan lian shou ao man mo luo bi wei liu di qiao huo yin lu ao keng qiang cui qi chang tang man yong chan feng jing biao shu lou xiu cong long zan jian cao li xia xi kang none beng none none zheng lu hua ji pu hui qiang po lin suo xiu san cheng kui san liu nao huang pie sui fan qiao chuan yang tang xiang jue jiao zun liao jie lao dui tan zan ji jian zhong deng lou ying dui jue nou ti pu tie none none ding shan kai jian fei sui lu juan hui yu lian zhuo qiao qian zhuo lei bi tie huan ye duo guo dang ju fen da bei yi ai dang xun diao zhu heng zhui ji nie ta huo qing bin ying kui ning xu jian jian qiang cha zhi mie li lei ji zuan kuang shang peng la du shuo chuo lu: biao bao lu none none long e lu xin jian lan bo jian yao chan xiang jian xi guan cang nie lei cuan qu pan luo zuan luan zao nie jue tang shu lan jin ga yi zhen ding zhao po liao tu qian chuan shan sa fan diao men nu: yang chai xing gai bu tai ju dun chao zhong na bei gang ban qian yao qin jun wu gou kang fang huo tou niu ba yu qian zheng qian gu bo ke po bu bo yue zuan mu tan jia dian you ti") .append("e bo ling shuo qian mao bao shi xuan tuo bi ni pi duo xing kao lao er mang ya you cheng jia ye nao zhi dang tong lu: diao yin kai zha zhu xian ting diu xian hua quan sha ha yao ge ming zheng se jiao yi chan chong tang an yin ru zhu lao pu wu lai te lian keng xiao suo li zeng chu guo gao e xiu cuo lu:e feng xin liu kai jian rui ti lang qin ju a qing zhe nuo cuo mao ben qi de ke kun chang xi gu luo chui zhui jin zhi xian juan huo pei tan ding jian ju meng zi qie ying kai qiang si e cha qiao zhong duan sou huang huan ai du mei lou zi fei mei mo zhen bo ge nie tang juan nie na liu hao bang yi jia bin rong biao tang man luo beng yong jing di zu xuan liu chan jue liao pu lu dun lan pu cuan qiang deng huo lei huan zhuo lian yi cha biao la chan xiang chang chang jiu ao die qu liao mi zhang men ma shuan shan huo men yan bi han bi none kai kang beng hong run san xian xian jian min xia min dou zha nao none peng ke ling bian bi run he guan ge he fa chu hong gui min none kun lang lu: ting sha yan yue yue chan qu lin chang shai kun yan min yan e hun yu wen xiang none xiang qu yao wen ban an wei yin kuo que lan du none none tian nie da kai he que chuangguan dou qi kui tang guan piao kan xi hui chan pi dang huan ta wen none men shuan shan yan han bi wen chuangrun wei xian hong jian min kang men zha nao gui wen ta min lu: kai fa ge he kun jiu yue lang du yu yan chang xi wen hun yan yan chan lan qu hui kuo que he tian da que kan huan fu fu le dui xin qian wu yi tuo yin yang dou e sheng ban pei keng yun ruan zhi pi jing fang yang yin zhen jie cheng e qu di zu zuo dian ling a tuo tuo po bing fu ji lu long chen xing duo lou mo jiang shu duo xian er gui wu gai shan jun qiao xing chun fu bi shan shan sheng zhi pu dou yuan zhen chu xian zhi nie yun xian pei pei zou yi dui lun yin ju chui chen pi ling tao xian lu none xian yin zhu yang reng shan chong yan yin yu ti yu long wei wei nie dui sui an huang jie sui yin gai yan hui ge yun wu wei ai xi tang ji zhang dao ao xi yin sa rao lin tui deng pi sui sui yu xian fen ni er ji dao xi yin zhi hui long xi li li li zhui he zhi sun juan nan yi que yan qin ya xiong ya ji gu huan zhi gou jun ci yong ju chu hu za luo yu chou diao sui han huo shuangguan chu za yong ji sui chou liu li nan xue za ji ji yu yu xue na fou se mu wen fen pang yun li li yang ling lei an bao meng dian dang hang wu zhao xu ji mu chen xiao zha ting zhen pei mei ling qi chou huo sha fei weng zhan ying ni chou tun lin none dong ying wu ling shuangling xia hong yin mai mo yun liu meng bin wu wei kuo yin xi yi ai dan deng xian yu lu long dai ji pang yang ba pi wei none xi ji mai meng meng lei li huo ai fei dai long ling ai feng li bao none he he bing qing qing jing qi zhen jing cheng qing jing jing dian jing tian fei fei kao mi mian mian pao ye tian hui ye ge ding ren jian ren di du wu ren qin jin xue niu ba yin sa ren ") .append("mo zu da ban yi yao tao bei jia hong pao yang mo yin jia tao ji xie an an hen gong gong da qiao ting man ying sui tiao qiao xuan kong beng ta zhang bing kuo ju la xie rou bang yi qiu qiu he xiao mu ju jian bian di jian none tao gou ta bei xie pan ge bi kuo tang lou gui qiao xue ji jian jiang chan da huo xian qian du wa jian lan wei ren fu mei juan ge wei qiao han chang none rou xun she wei ge bei tao gou yun gao bi wei hui shu wa du wei ren fu han wei yun tao jiu jiu xian xie xian ji yin za yun shao luo peng huang ying yun peng yin yin xiang hu ye ding qing pan xiang shun han xu yi xu gu song kui qi hang yu wan ban dun di dan pan po ling cheng jing lei he qiao e e wei jie gua shen yi yi ke dui pian ping lei fu jia tou hui kui jia le ting cheng ying jun hu han jing tui tui pin lai tui zi zi chui ding lai yan han qian ke cui jiong qin yi sai ti e e yan hun kan yong zhuan yan xian xin yi yuan sang dian dian jiang ku lei liao piao yi man qi yao hao qiao gu xun qian hui zhan ru hong bin xian pin lu lan nie quan ye ding qing han xiang shun xu xu wan gu dun qi ban song hang yu lu ling po jing jie jia ting he ying jiong ke yi pin hui tui han ying ying ke ti yong e zhuan yan e nie man dian sang hao lei zhan ru pin quan feng biao none fu xia zhan biao sa fa tai lie gua xuan shao ju biao si wei yang yao sou kai sao fan liu xi liao piao piao liu biao biao biao liao none se feng biao feng yang zhan biao sa ju si sou yao liu piao biao biao fei fan fei fei shi shi can ji ding si tuo jian sun xiang tun ren yu juan chi yin fan fan sun yin zhu yi zhai bi jie tao liu ci tie si bao shi duo hai ren tian jiao jia bing yao tong ci xiang yang yang er yan le yi can bo nei e bu jun dou su yu shi yao hun guo shi jian zhui bing xian bu ye tan fei zhang wei guan e nuan hun hu huang tie hui jian hou he xing fen wei gu cha song tang bo gao xi kui liu sou tao ye yun mo tang man bi yu xiu jin san kui zhuan shan chi dan yi ji rao cheng yong tao hui xiang zhan fen hai meng yan mo chan xiang luo zuan nang shi ding ji tuo xing tun xi ren yu chi fan yin jian shi bao si duo yi er rao xiang he le jiao xi bing bo dou e yu nei jun guo hun xian guan cha kui gu sou chan ye mo bo liu xiu jin man san zhuan nang shou kui guo xiang fen ba ni bi bo tu han fei jian yan ai fu xian wen xin fen bin xing ma yu feng han di tuo tuo chi xun zhu zhi pei xin ri sa yin wen zhi dan lu: you bo bao kuai tuo yi qu wen qu jiong bo zhao yuan peng zhou ju zhu nu ju pi zang jia ling zhen tai fu yang shi bi tuo tuo si liu ma pian tao zhi rong teng dong xun quan shen jiong er hai bo none yin luo none dan xie liu ju song qin mang liang han tu xuan tui jun e cheng xing ai lu zhui zhou she pian kun tao lai zong ke qi qi yan fei sao yan jie yao wu pian cong pian qian fei huang jian huo yu ti quan xia zong kui rou si gua tuo kui sou qian cheng zhi liu pang teng xi cao ") .append(" du yan yuan zou sao shan li zhi shuanglu xi luo zhang mo ao can piao cong qu bi zhi yu xu hua bo su xiao lin zhan dun liu tuo zeng tan jiao tie yan luo zhan jing yi ye tuo bin zou yan peng lu: teng xiang ji shuangju xi huan li biao ma yu tuo xun chi qu ri bo lu: zang shi si fu ju zou zhu tuo nu jia yi tai xiao ma yin jiao hua luo hai pian biao li cheng yan xing qin jun qi qi ke zhui zong su can pian zhi kui sao wu ao liu qian shan piao luo cong zhan zhou ji shuangxiang gu wei wei wei yu gan yi ang tou jie bo bi ci ti di ku hai qiao hou kua ge tui geng pian bi ke qia yu sui lou bo xiao bang bo cuo kuan bin mo liao lou nao du zang sui ti bin kuan lu gao gao qiao kao qiao lao zao biao kun kun ti fang xiu ran mao dan kun bin fa tiao pi zi fa ran ti pao pi mao fu er rong qu none xiu gua ji peng zhua shao sha ti li bin zong ti peng song zheng quan zong shun jian duo hu la jiu qi lian zhen bin peng mo san man man seng xu lie qian qian nong huan kuai ning bin lie rang dou dou nao hong xi dou kan dou dou jiu chang yu yu li juan fu qian gui zong liu gui shang yu gui mei ji qi jie kui hun ba po mei xu yan xiao liang yu tui qi wang liang wei jian chi piao bi mo ji xu chou yan zhan yu dao ren ji ba hong tuo diao ji yu e que sha hang tun mo gai shen fan yuan pi lu wen hu lu za fang fen na you none none he xia qu han pi ling tuo ba qiu ping fu bi ji wei ju diao ba you gun pi nian xing tai bao fu zha ju gu none none none ta jie shua hou xiang er an wei tiao zhu yin lie luo tong yi qi bing wei jiao pu gui xian ge hui none none kao none duo jun ti mian shao za suo qin yu nei zhe gun geng none wu qiu ting fu huan chou li sha sha gao meng none none none none yong ni zi qi qing xiang nei chun ji diao qie gu zhou dong lai fei ni yi kun lu jiu chang jing lun ling zou li meng zong zhi nian none none none shi sao hun ti hou xing ju la zong ji bian bian huan quan ji wei wei yu chun rou die huang lian yan qiu qiu jian bi e yang fu sai jian ha tuo hu none ruo none wen jian hao wu pang sao liu ma shi shi guan zi teng ta yao ge rong qian qi wen ruo none lian ao le hui min ji tiao qu jian sao man xi qiu biao ji ji zhu jiang qiu zhuan yong zhang kang xue bie jue qu xiang bo jiao xun su huang zun shan shan fan gui lin xun miao xi none xiang fen guan hou kuai zei sao zhan gan gui sheng li chang none none ai ru ji xu huo none li lie li mie zhen xiang e lu guan li xian yu dao ji you tun lu fang ba ke ba ping nian lu you zha fu ba bao hou pi tai gui jie kao wei er tong zei hou kuai ji jiao xian zha xiang xun geng li lian jian li shi tiao gun sha huan jun ji yong qing ling qi zou fei kun chang gu ni nian diao jing shen shi zi fen die bi chang ti wen wei sai e qiu fu huang quan jiang bian sao ao qi ta guan yao pang jian le biao xue bie man min yong wei xi gui shan lin zun hu gan li shan guan niao yi fu li jiu bu ya") .append("n fu diao ji feng none gan shi feng ming bao yuan zhi hu qian fu fen wen jian shi yu fou yiao ju jue pi huan zhen bao yan ya zheng fang feng wen ou te jia nu ling mie fu tuo wen li bian zhi ge yuan zi qu xiao chi dan ju you gu zhong yu yang rong ya zhi yu none ying zhui wu er gua ai zhi yan heng jiao ji lie zhu ren ti hong luo ru mou ge ren jiao xiu zhou chi luo none none none luan jia ji yu huan tuo bu wu juan yu bo xun xun bi xi jun ju tu jing ti e e kuang hu wu shen la none none lu bing shu fu an zhao peng qin qian bei diao lu que jian ju tu ya yuan qi li ye zhui kong duo kun sheng qi jing ni e jing zi lai dong qi chun geng ju qu none none ji shu none chi miao rou fu qiu ti hu ti e jie mao fu chun tu yan he yuan pian yun mei hu ying dun mu ju none cang fang ge ying yuan xuan weng shi he chu tang xia ruo liu ji gu jian zhun han zi ci yi yao yan ji li tian kou ti ti ni tu ma jiao liu zhen chen li zhuan zhe ao yao yi ou chi zhi liao rong lou bi shuangzhuo yu wu jue yin tan si jiao yi hua bi ying su huang fan jiao liao yan kao jiu xian xian tu mai zun yu ying lu tuan xian xue yi pi shu luo qi yi ji zhe yu zhan ye yang pi ning hu mi ying meng di yue yu lei bo lu he long shuangyue ying guan qu li luan niao jiu ji yuan ming shi ou ya cang bao zhen gu dong lu ya xiao yang ling chi qu yuan xue tuo si zhi er gua xiu heng zhou ge luan hong wu bo li juan hu e yu xian ti wu que miao an kun bei peng qian chun geng yuan su hu he e gu qiu ci mei wu yi yao weng liu ji yi jian he yi ying zhe liu liao jiao jiu yu lu huan zhan ying hu meng guan shuanglu jin ling jian xian cuo jian jian yan cuo lu you cu ji biao cu pao zhu jun zhu jian mi mi wu liu chen jun lin ni qi lu jiu jun jing li xiang yan jia mi li she zhang lin jing qi ling yan cu mai mai ge chao fu mian mian fu pao qu qu mou fu xian lai qu mian chi feng fu qu mian ma ma mo hui none zou nen fen huang huang jin guang tian tou hong xi kuang hong shu li nian chi hei hei yi qian zhen xi tuan mo mo qian dai chu you dian yi xia yan qu mei yan qing yu li dang du can yin an yan tan an zhen dai can yi mei dan yan du lu zhi fen fu fu min min yuan cu qu chao wa zhu zhi mang ao bie tuo bi yuan chao tuo ding mi nai ding zi gu gu dong fen tao yuan pi chang gao qi yuan tang teng shu shu fen fei wen ba diao tuo tong qu sheng shi you shi ting wu nian jing hun ju yan tu si xi xian yan lei bi yao yan han hui wu hou xi ge zha xiu weng zha nong nang qi zhai ji zi ji ji qi ji chi chen chen he ya ken xie bao ze shi zi chi nian ju tiao ling ling chu quan xie yin nie jiu nie chuo kun yu chu yi ni cuo chuo qu nian xian yu e wo yi chi zou dian chu jin ya chi chen he yin ju ling bao tiao zi yin yu chuo qu wo long pang gong pang yan long long gong kan ta ling ta long gong kan gui qiu bie gui yue chui he jue ") .append("xie yue ").toString(); } }
Blankj/AndroidUtilCode
lib/subutil/src/main/java/com/blankj/subutil/util/PinyinUtils.java
2,143
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak; import org.keycloak.common.VerificationException; import org.keycloak.exceptions.TokenNotActiveException; import org.keycloak.exceptions.TokenSignatureInvalidException; import org.keycloak.jose.jws.AlgorithmType; import org.keycloak.jose.jws.JWSHeader; import org.keycloak.jose.jws.JWSInput; import org.keycloak.jose.jws.JWSInputException; import org.keycloak.crypto.SignatureVerifierContext; import org.keycloak.jose.jws.crypto.HMACProvider; import org.keycloak.jose.jws.crypto.RSAProvider; import org.keycloak.representations.JsonWebToken; import org.keycloak.util.TokenUtil; import javax.crypto.SecretKey; import java.security.PublicKey; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public class TokenVerifier<T extends JsonWebToken> { private static final Logger LOG = Logger.getLogger(TokenVerifier.class.getName()); // This interface is here as JDK 7 is a requirement for this project. // Once JDK 8 would become mandatory, java.util.function.Predicate would be used instead. /** * Functional interface of checks that verify some part of a JWT. * @param <T> Type of the token handled by this predicate. */ // @FunctionalInterface public static interface Predicate<T extends JsonWebToken> { /** * Performs a single check on the given token verifier. * @param t Token, guaranteed to be non-null. * @return * @throws VerificationException */ boolean test(T t) throws VerificationException; } public static final Predicate<JsonWebToken> SUBJECT_EXISTS_CHECK = new Predicate<JsonWebToken>() { @Override public boolean test(JsonWebToken t) throws VerificationException { String subject = t.getSubject(); if (subject == null) { throw new VerificationException("Subject missing in token"); } return true; } }; /** * Check for token being neither expired nor used before it gets valid. * @see JsonWebToken#isActive() */ public static final Predicate<JsonWebToken> IS_ACTIVE = new Predicate<JsonWebToken>() { @Override public boolean test(JsonWebToken t) throws VerificationException { if (! t.isActive()) { throw new TokenNotActiveException(t, "Token is not active"); } return true; } }; public static class RealmUrlCheck implements Predicate<JsonWebToken> { private static final RealmUrlCheck NULL_INSTANCE = new RealmUrlCheck(null); private final String realmUrl; public RealmUrlCheck(String realmUrl) { this.realmUrl = realmUrl; } @Override public boolean test(JsonWebToken t) throws VerificationException { if (this.realmUrl == null) { throw new VerificationException("Realm URL not set"); } if (! this.realmUrl.equals(t.getIssuer())) { throw new VerificationException("Invalid token issuer. Expected '" + this.realmUrl + "'"); } return true; } }; public static class TokenTypeCheck implements Predicate<JsonWebToken> { private static final TokenTypeCheck INSTANCE_DEFAULT_TOKEN_TYPE = new TokenTypeCheck(Arrays.asList(TokenUtil.TOKEN_TYPE_BEARER, TokenUtil.TOKEN_TYPE_DPOP)); private final List<String> tokenTypes; public TokenTypeCheck(List<String> tokenTypes) { this.tokenTypes = tokenTypes; } @Override public boolean test(JsonWebToken t) throws VerificationException { for (String tokenType : tokenTypes) { if (tokenType.equalsIgnoreCase(t.getType())) return true; } throw new VerificationException("Token type is incorrect. Expected '" + tokenTypes.toString() + "' but was '" + t.getType() + "'"); } }; public static class AudienceCheck implements Predicate<JsonWebToken> { private final String expectedAudience; public AudienceCheck(String expectedAudience) { this.expectedAudience = expectedAudience; } @Override public boolean test(JsonWebToken t) throws VerificationException { if (expectedAudience == null) { throw new VerificationException("Missing expectedAudience"); } String[] audience = t.getAudience(); if (audience == null) { throw new VerificationException("No audience in the token"); } if (t.hasAudience(expectedAudience)) { return true; } throw new VerificationException("Expected audience not available in the token"); } }; public static class IssuedForCheck implements Predicate<JsonWebToken> { private final String expectedIssuedFor; public IssuedForCheck(String expectedIssuedFor) { this.expectedIssuedFor = expectedIssuedFor; } @Override public boolean test(JsonWebToken jsonWebToken) throws VerificationException { if (expectedIssuedFor == null) { throw new VerificationException("Missing expectedIssuedFor"); } if (expectedIssuedFor.equals(jsonWebToken.getIssuedFor())) { return true; } throw new VerificationException("Expected issuedFor doesn't match"); } } private String tokenString; private Class<? extends T> clazz; private PublicKey publicKey; private SecretKey secretKey; private String realmUrl; private List<String> expectedTokenType = Arrays.asList(TokenUtil.TOKEN_TYPE_BEARER, TokenUtil.TOKEN_TYPE_DPOP); private boolean checkTokenType = true; private boolean checkRealmUrl = true; private final LinkedList<Predicate<? super T>> checks = new LinkedList<>(); private JWSInput jws; private T token; private SignatureVerifierContext verifier = null; public TokenVerifier<T> verifierContext(SignatureVerifierContext verifier) { this.verifier = verifier; return this; } protected TokenVerifier(String tokenString, Class<T> clazz) { this.tokenString = tokenString; this.clazz = clazz; } protected TokenVerifier(T token) { this.token = token; } /** * Creates an instance of {@code TokenVerifier} from the given string on a JWT of the given class. * The token verifier has no checks defined. Note that the checks are only tested when * {@link #verify()} method is invoked. * @param <T> Type of the token * @param tokenString String representation of JWT * @param clazz Class of the token * @return */ public static <T extends JsonWebToken> TokenVerifier<T> create(String tokenString, Class<T> clazz) { return new TokenVerifier<>(tokenString, clazz); } /** * Creates an instance of {@code TokenVerifier} for the given token. * The token verifier has no checks defined. Note that the checks are only tested when * {@link #verify()} method is invoked. * <p> * <b>NOTE:</b> The returned token verifier cannot verify token signature since * that is not part of the {@link JsonWebToken} object. * @return */ public static <T extends JsonWebToken> TokenVerifier<T> createWithoutSignature(T token) { return new TokenVerifier<>(token); } /** * Adds default checks to the token verification: * <ul> * <li>Realm URL (JWT issuer field: {@code iss}) has to be defined and match realm set via {@link #realmUrl(java.lang.String)} method</li> * <li>Subject (JWT subject field: {@code sub}) has to be defined</li> * <li>Token type (JWT type field: {@code typ}) has to be {@code Bearer}. The type can be set via {@link #tokenType(java.lang.String)} method</li> * <li>Token has to be active, ie. both not expired and not used before its validity (JWT issuer fields: {@code exp} and {@code nbf})</li> * </ul> * @return This token verifier. */ public TokenVerifier<T> withDefaultChecks() { return withChecks( RealmUrlCheck.NULL_INSTANCE, TokenTypeCheck.INSTANCE_DEFAULT_TOKEN_TYPE, IS_ACTIVE ); } private void removeCheck(Class<? extends Predicate<?>> checkClass) { for (Iterator<Predicate<? super T>> it = checks.iterator(); it.hasNext();) { if (it.next().getClass() == checkClass) { it.remove(); } } } private void removeCheck(Predicate<? super T> check) { checks.remove(check); } @SuppressWarnings("unchecked") private <P extends Predicate<? super T>> TokenVerifier<T> replaceCheck(Class<? extends Predicate<?>> checkClass, boolean active, P... predicate) { removeCheck(checkClass); if (active) { checks.addAll(Arrays.asList(predicate)); } return this; } @SuppressWarnings("unchecked") private <P extends Predicate<? super T>> TokenVerifier<T> replaceCheck(Predicate<? super T> check, boolean active, P... predicate) { removeCheck(check); if (active) { checks.addAll(Arrays.asList(predicate)); } return this; } /** * Will test the given checks in {@link #verify()} method in addition to already set checks. * @param checks * @return */ @SafeVarargs public final TokenVerifier<T> withChecks(Predicate<? super T>... checks) { if (checks != null) { this.checks.addAll(Arrays.asList(checks)); } return this; } /** * Sets the key for verification of RSA-based signature. * @param publicKey * @return */ public TokenVerifier<T> publicKey(PublicKey publicKey) { this.publicKey = publicKey; return this; } /** * Sets the key for verification of HMAC-based signature. * @param secretKey * @return */ public TokenVerifier<T> secretKey(SecretKey secretKey) { this.secretKey = secretKey; return this; } /** * @deprecated This method is here only for backward compatibility with previous version of {@code TokenVerifier}. * @return This token verifier */ public TokenVerifier<T> realmUrl(String realmUrl) { this.realmUrl = realmUrl; return replaceCheck(RealmUrlCheck.class, checkRealmUrl, new RealmUrlCheck(realmUrl)); } /** * @deprecated This method is here only for backward compatibility with previous version of {@code TokenVerifier}. * @return This token verifier */ public TokenVerifier<T> checkTokenType(boolean checkTokenType) { this.checkTokenType = checkTokenType; return replaceCheck(TokenTypeCheck.class, this.checkTokenType, new TokenTypeCheck(expectedTokenType)); } /** * * @return This token verifier */ public TokenVerifier<T> tokenType(List<String> tokenTypes) { this.expectedTokenType = tokenTypes; return replaceCheck(TokenTypeCheck.class, this.checkTokenType, new TokenTypeCheck(expectedTokenType)); } /** * @deprecated This method is here only for backward compatibility with previous version of {@code TokenVerifier}. * @return This token verifier */ public TokenVerifier<T> checkActive(boolean checkActive) { return replaceCheck(IS_ACTIVE, checkActive, IS_ACTIVE); } /** * @deprecated This method is here only for backward compatibility with previous version of {@code TokenVerifier}. * @return This token verifier */ public TokenVerifier<T> checkRealmUrl(boolean checkRealmUrl) { this.checkRealmUrl = checkRealmUrl; return replaceCheck(RealmUrlCheck.class, this.checkRealmUrl, new RealmUrlCheck(realmUrl)); } /** * Add check for verifying that token contains the expectedAudience * * @param expectedAudiences Audiences, which needs to be in the target token. Can be <code>null</code>. * @return This token verifier */ public TokenVerifier<T> audience(String... expectedAudiences) { if (expectedAudiences == null || expectedAudiences.length == 0) { return this.replaceCheck(AudienceCheck.class, true, new AudienceCheck(null)); } AudienceCheck[] audienceChecks = new AudienceCheck[expectedAudiences.length]; for (int i = 0; i < expectedAudiences.length; ++i) { audienceChecks[i] = new AudienceCheck(expectedAudiences[i]); } return this.replaceCheck(AudienceCheck.class, true, audienceChecks); } /** * Add check for verifying that token issuedFor (azp claim) is the expected value * * @param expectedIssuedFor issuedFor, which needs to be in the target token. Can't be null * @return This token verifier */ public TokenVerifier<T> issuedFor(String expectedIssuedFor) { return this.replaceCheck(IssuedForCheck.class, true, new IssuedForCheck(expectedIssuedFor)); } public TokenVerifier<T> parse() throws VerificationException { if (jws == null) { if (tokenString == null) { throw new VerificationException("Token not set"); } try { jws = new JWSInput(tokenString); } catch (JWSInputException e) { throw new VerificationException("Failed to parse JWT", e); } try { token = jws.readJsonContent(clazz); } catch (JWSInputException e) { throw new VerificationException("Failed to read access token from JWT", e); } } return this; } public T getToken() throws VerificationException { if (token == null) { parse(); } return token; } public JWSHeader getHeader() throws VerificationException { parse(); return jws.getHeader(); } public void verifySignature() throws VerificationException { if (this.verifier != null) { try { if (!verifier.verify(jws.getEncodedSignatureInput().getBytes("UTF-8"), jws.getSignature())) { throw new TokenSignatureInvalidException(token, "Invalid token signature"); } } catch (Exception e) { throw new VerificationException(e); } } else { AlgorithmType algorithmType = getHeader().getAlgorithm().getType(); if (null == algorithmType) { throw new VerificationException("Unknown or unsupported token algorithm"); } else switch (algorithmType) { case RSA: if (publicKey == null) { throw new VerificationException("Public key not set"); } if (!RSAProvider.verify(jws, publicKey)) { throw new TokenSignatureInvalidException(token, "Invalid token signature"); } break; case HMAC: if (secretKey == null) { throw new VerificationException("Secret key not set"); } if (!HMACProvider.verify(jws, secretKey)) { throw new TokenSignatureInvalidException(token, "Invalid token signature"); } break; default: throw new VerificationException("Unknown or unsupported token algorithm"); } } } public TokenVerifier<T> verify() throws VerificationException { if (getToken() == null) { parse(); } if (jws != null) { verifySignature(); } for (Predicate<? super T> check : checks) { if (! check.test(getToken())) { throw new VerificationException("JWT check failed for check " + check); } } return this; } /** * Creates an optional predicate from a predicate that will proceed with check but always pass. * @param <T> * @param mandatoryPredicate * @return */ public static <T extends JsonWebToken> Predicate<T> optional(final Predicate<T> mandatoryPredicate) { return new Predicate<T>() { @Override public boolean test(T t) throws VerificationException { try { if (! mandatoryPredicate.test(t)) { LOG.finer("[optional] predicate failed: " + mandatoryPredicate); } return true; } catch (VerificationException ex) { LOG.log(Level.FINER, "[optional] predicate " + mandatoryPredicate + " failed.", ex); return true; } } }; } /** * Creates a predicate that will proceed with checks of the given predicates * and will pass if and only if at least one of the given predicates passes. * @param <T> * @param predicates * @return */ @SafeVarargs public static <T extends JsonWebToken> Predicate<T> alternative(final Predicate<? super T>... predicates) { return new Predicate<T>() { @Override public boolean test(T t) { for (Predicate<? super T> predicate : predicates) { try { if (predicate.test(t)) { return true; } LOG.finer("[alternative] predicate failed: " + predicate); } catch (VerificationException ex) { LOG.log(Level.FINER, "[alternative] predicate " + predicate + " failed.", ex); } } return false; } }; } }
keycloak/keycloak
core/src/main/java/org/keycloak/TokenVerifier.java
2,144
package mindustry.entities.comp; import arc.*; import arc.graphics.*; import arc.graphics.g2d.*; import arc.math.*; import arc.math.geom.*; import arc.scene.ui.layout.*; import arc.util.*; import mindustry.ai.*; import mindustry.ai.types.*; import mindustry.annotations.Annotations.*; import mindustry.async.*; import mindustry.content.*; import mindustry.core.*; import mindustry.ctype.*; import mindustry.entities.*; import mindustry.entities.abilities.*; import mindustry.entities.units.*; import mindustry.game.EventType.*; import mindustry.game.*; import mindustry.gen.*; import mindustry.graphics.*; import mindustry.logic.*; import mindustry.type.*; import mindustry.ui.*; import mindustry.world.*; import mindustry.world.blocks.environment.*; import mindustry.world.blocks.payloads.*; import static mindustry.Vars.*; import static mindustry.logic.GlobalVars.*; @Component(base = true) abstract class UnitComp implements Healthc, Physicsc, Hitboxc, Statusc, Teamc, Itemsc, Rotc, Unitc, Weaponsc, Drawc, Boundedc, Syncc, Shieldc, Displayable, Ranged, Minerc, Builderc, Senseable, Settable{ @Import boolean hovering, dead, disarmed; @Import float x, y, rotation, elevation, maxHealth, drag, armor, hitSize, health, shield, ammo, dragMultiplier, armorOverride, speedMultiplier; @Import Team team; @Import int id; @Import @Nullable Tile mineTile; @Import Vec2 vel; @Import WeaponMount[] mounts; @Import ItemStack stack; private UnitController controller; Ability[] abilities = {}; UnitType type = UnitTypes.alpha; boolean spawnedByCore; double flag; transient @Nullable Trail trail; //TODO could be better represented as a unit transient @Nullable UnitType dockedType; transient String lastCommanded; transient float shadowAlpha = -1f, healTime; transient int lastFogPos; private transient float resupplyTime = Mathf.random(10f); private transient boolean wasPlayer; private transient boolean wasHealed; /** Called when this unit was unloaded from a factory or spawn point. */ public void unloaded(){ } public void updateBoosting(boolean boost){ if(!type.canBoost || dead) return; elevation = Mathf.approachDelta(elevation, type.canBoost ? Mathf.num(boost || onSolid() || (isFlying() && !canLand())) : 0f, type.riseSpeed); } /** Move based on preferred unit movement type. */ public void movePref(Vec2 movement){ if(type.omniMovement){ moveAt(movement); }else{ rotateMove(movement); } } public void moveAt(Vec2 vector){ moveAt(vector, type.accel); } public void approach(Vec2 vector){ vel.approachDelta(vector, type.accel * speed()); } public void rotateMove(Vec2 vec){ moveAt(Tmp.v2.trns(rotation, vec.len())); if(!vec.isZero()){ rotation = Angles.moveToward(rotation, vec.angle(), type.rotateSpeed * Time.delta * speedMultiplier); } } public void aimLook(Position pos){ aim(pos); lookAt(pos); } public void aimLook(float x, float y){ aim(x, y); lookAt(x, y); } public boolean isPathImpassable(int tileX, int tileY){ return !type.flying && world.tiles.in(tileX, tileY) && type.pathCost.getCost(team.id, pathfinder.get(tileX, tileY)) == -1; } /** @return approx. square size of the physical hitbox for physics */ public float physicSize(){ return hitSize * 0.7f; } /** @return whether there is solid, un-occupied ground under this unit. */ public boolean canLand(){ return !onSolid() && Units.count(x, y, physicSize(), f -> f != self() && f.isGrounded()) == 0; } public boolean inRange(Position other){ return within(other, type.range); } public boolean hasWeapons(){ return type.hasWeapons(); } /** @return speed with boost & floor multipliers factored in. */ public float speed(){ float strafePenalty = isGrounded() || !isPlayer() ? 1f : Mathf.lerp(1f, type.strafePenalty, Angles.angleDist(vel().angle(), rotation) / 180f); float boost = Mathf.lerp(1f, type.canBoost ? type.boostMultiplier : 1f, elevation); return type.speed * strafePenalty * boost * floorSpeedMultiplier(); } /** @return where the unit wants to look at. */ public float prefRotation(){ if(activelyBuilding() && type.rotateToBuilding){ return angleTo(buildPlan()); }else if(mineTile != null){ return angleTo(mineTile); }else if(moving() && type.omniMovement){ return vel().angle(); } return rotation; } @Override public boolean displayable(){ return type.hoverable; } @Override @Replace public boolean isSyncHidden(Player player){ //shooting reveals position so bullets can be seen return !isShooting() && inFogTo(player.team()); } @Override public void handleSyncHidden(){ remove(); netClient.clearRemovedEntity(id); } @Override @Replace public boolean inFogTo(Team viewer){ if(this.team == viewer || !state.rules.fog) return false; if(hitSize <= 16f){ return !fogControl.isVisible(viewer, x, y); }else{ //for large hitsizes, check around the unit instead float trns = hitSize / 2f; for(var p : Geometry.d8){ if(fogControl.isVisible(viewer, x + p.x * trns, y + p.y * trns)){ return false; } } } return true; } @Override public float range(){ return type.maxRange; } @Replace public float clipSize(){ if(isBuilding()){ return state.rules.infiniteResources ? Float.MAX_VALUE : Math.max(type.clipSize, type.region.width) + type.buildRange + tilesize*4f; } if(mining()){ return type.clipSize + type.mineRange; } return type.clipSize; } @Override public double sense(LAccess sensor){ return switch(sensor){ case totalItems -> stack().amount; case itemCapacity -> type.itemCapacity; case rotation -> rotation; case health -> health; case shield -> shield; case maxHealth -> maxHealth; case ammo -> !state.rules.unitAmmo ? type.ammoCapacity : ammo; case ammoCapacity -> type.ammoCapacity; case x -> World.conv(x); case y -> World.conv(y); case dead -> dead || !isAdded() ? 1 : 0; case team -> team.id; case shooting -> isShooting() ? 1 : 0; case boosting -> type.canBoost && isFlying() ? 1 : 0; case range -> range() / tilesize; case shootX -> World.conv(aimX()); case shootY -> World.conv(aimY()); case cameraX -> controller instanceof Player player ? World.conv(player.con == null ? Core.camera.position.x : player.con.viewX) : 0; case cameraY -> controller instanceof Player player ? World.conv(player.con == null ? Core.camera.position.y : player.con.viewY) : 0; case cameraWidth -> controller instanceof Player player ? World.conv(player.con == null ? Core.camera.width : player.con.viewWidth) : 0; case cameraHeight -> controller instanceof Player player ? World.conv(player.con == null ? Core.camera.height : player.con.viewHeight) : 0; case mining -> mining() ? 1 : 0; case mineX -> mining() ? mineTile.x : -1; case mineY -> mining() ? mineTile.y : -1; case armor -> armorOverride >= 0f ? armorOverride : armor; case flag -> flag; case speed -> type.speed * 60f / tilesize * speedMultiplier; case controlled -> !isValid() ? 0 : controller instanceof LogicAI ? ctrlProcessor : controller instanceof Player ? ctrlPlayer : controller instanceof CommandAI command && command.hasCommand() ? ctrlCommand : 0; case payloadCount -> ((Object)this) instanceof Payloadc pay ? pay.payloads().size : 0; case size -> hitSize / tilesize; case color -> Color.toDoubleBits(team.color.r, team.color.g, team.color.b, 1f); default -> Float.NaN; }; } @Override public Object senseObject(LAccess sensor){ return switch(sensor){ case type -> type; case name -> controller instanceof Player p ? p.name : null; case firstItem -> stack().amount == 0 ? null : item(); case controller -> !isValid() ? null : controller instanceof LogicAI log ? log.controller : this; case payloadType -> ((Object)this) instanceof Payloadc pay ? (pay.payloads().isEmpty() ? null : pay.payloads().peek() instanceof UnitPayload p1 ? p1.unit.type : pay.payloads().peek() instanceof BuildPayload p2 ? p2.block() : null) : null; default -> noSensed; }; } @Override public double sense(Content content){ if(content == stack().item) return stack().amount; return Float.NaN; } @Override public void setProp(LAccess prop, double value){ switch(prop){ case health -> { health = (float)Mathf.clamp(value, 0, maxHealth); if(health <= 0f && !dead){ kill(); } } case shield -> shield = Math.max((float)value, 0f); case x -> { x = World.unconv((float)value); if(!isLocal()) snapInterpolation(); } case y -> { y = World.unconv((float)value); if(!isLocal()) snapInterpolation(); } case rotation -> rotation = (float)value; case team -> { if(!net.client()){ Team team = Team.get((int)value); if(controller instanceof Player p){ p.team(team); } this.team = team; } } case flag -> flag = value; case speed -> statusSpeed(Math.max((float)value, 0f)); case armor -> statusArmor(Math.max((float)value, 0f)); } } @Override public void setProp(LAccess prop, Object value){ switch(prop){ case team -> { if(value instanceof Team t && !net.client()){ if(controller instanceof Player p) p.team(t); team = t; } } case payloadType -> { //only serverside if(((Object)this) instanceof Payloadc pay && !net.client()){ if(value instanceof Block b){ if(b.synthetic()){ Building build = b.newBuilding().create(b, team()); if(pay.canPickup(build)) pay.addPayload(new BuildPayload(build)); } }else if(value instanceof UnitType ut){ Unit unit = ut.create(team()); if(pay.canPickup(unit)) pay.addPayload(new UnitPayload(unit)); }else if(value == null && pay.payloads().size > 0){ pay.payloads().pop(); } } } } } @Override public void setProp(UnlockableContent content, double value){ if(content instanceof Item item){ stack.item = item; stack.amount = Mathf.clamp((int)value, 0, type.itemCapacity); } } @Override @Replace public boolean canDrown(){ return isGrounded() && !hovering && type.canDrown; } @Override @Replace public boolean canShoot(){ //cannot shoot while boosting return !disarmed && !(type.canBoost && isFlying()); } public boolean isEnemy(){ return type.isEnemy; } @Override @Replace public boolean collides(Hitboxc other){ return hittable(); } @Override public void collision(Hitboxc other, float x, float y){ if(other instanceof Bullet bullet){ controller.hit(bullet); } } @Override public int itemCapacity(){ return type.itemCapacity; } @Override public float bounds(){ return hitSize * 2f; } @Override public void controller(UnitController next){ this.controller = next; if(controller.unit() != self()) controller.unit(self()); } @Override public UnitController controller(){ return controller; } public void resetController(){ controller(type.createController(self())); } @Override public void set(UnitType def, UnitController controller){ if(this.type != def){ setType(def); } controller(controller); } /** @return the collision layer to use for unit physics. Returning anything outside of PhysicsProcess contents will crash the game. */ public int collisionLayer(){ return type.allowLegStep && type.legPhysicsLayer ? PhysicsProcess.layerLegs : isGrounded() ? PhysicsProcess.layerGround : PhysicsProcess.layerFlying; } /** @return pathfinder path type for calculating costs. This is used for wave AI only. (TODO: remove) */ public int pathType(){ return Pathfinder.costGround; } public void lookAt(float angle){ rotation = Angles.moveToward(rotation, angle, type.rotateSpeed * Time.delta * speedMultiplier()); } public void lookAt(Position pos){ lookAt(angleTo(pos)); } public void lookAt(float x, float y){ lookAt(angleTo(x, y)); } public boolean isAI(){ return controller instanceof AIController; } public boolean isCommandable(){ return controller instanceof CommandAI; } public boolean canTarget(Unit other){ return other != null && other.checkTarget(type.targetAir, type.targetGround); } public CommandAI command(){ if(controller instanceof CommandAI ai){ return ai; }else{ throw new IllegalArgumentException("Unit cannot be commanded - check isCommandable() first."); } } public int count(){ return team.data().countType(type); } public int cap(){ return Units.getCap(team); } public void setType(UnitType type){ this.type = type; this.maxHealth = type.health; this.drag = type.drag; this.armor = type.armor; this.hitSize = type.hitSize; this.hovering = type.hovering; if(controller == null) controller(type.createController(self())); if(mounts().length != type.weapons.size) setupWeapons(type); if(abilities.length != type.abilities.size){ abilities = new Ability[type.abilities.size]; for(int i = 0; i < type.abilities.size; i ++){ abilities[i] = type.abilities.get(i).copy(); } } } public boolean targetable(Team targeter){ return type.targetable(self(), targeter); } public boolean hittable(){ return type.hittable(self()); } @Override public void afterSync(){ //set up type info after reading setType(this.type); controller.unit(self()); } @Override public void afterRead(){ afterSync(); //reset controller state if(!(controller instanceof AIController ai && ai.keepState())){ controller(type.createController(self())); } } @Override public void afterAllRead(){ controller.afterRead(self()); } @Override public void add(){ team.data().updateCount(type, 1); //check if over unit cap if(type.useUnitCap && count() > cap() && !spawnedByCore && !dead && !state.rules.editor){ Call.unitCapDeath(self()); team.data().updateCount(type, -1); } } @Override public void remove(){ team.data().updateCount(type, -1); controller.removed(self()); //make sure trail doesn't just go poof if(trail != null && trail.size() > 0){ Fx.trailFade.at(x, y, trail.width(), type.trailColor == null ? team.color : type.trailColor, trail.copy()); } } @Override public void landed(){ if(type.mechLandShake > 0f){ Effect.shake(type.mechLandShake, type.mechLandShake, this); } type.landed(self()); } @Override public void heal(float amount){ if(health < maxHealth && amount > 0){ wasHealed = true; } } @Override public void update(){ type.update(self()); if(wasHealed && healTime <= -1f){ healTime = 1f; } healTime -= Time.delta / 20f; wasHealed = false; //die on captured sectors immediately if(team.isOnlyAI() && state.isCampaign() && state.getSector().isCaptured()){ kill(); } if(!headless && type.loopSound != Sounds.none){ control.sound.loop(type.loopSound, this, type.loopSoundVolume); } //check if environment is unsupported if(!type.supportsEnv(state.rules.env) && !dead){ Call.unitEnvDeath(self()); team.data().updateCount(type, -1); } if(state.rules.unitAmmo && ammo < type.ammoCapacity - 0.0001f){ resupplyTime += Time.delta; //resupply only at a fixed interval to prevent lag if(resupplyTime > 10f){ type.ammoType.resupply(self()); resupplyTime = 0f; } } for(Ability a : abilities){ a.update(self()); } if(trail != null){ trail.length = type.trailLength; float scale = type.useEngineElevation ? elevation : 1f; float offset = type.engineOffset/2f + type.engineOffset/2f*scale; float cx = x + Angles.trnsx(rotation + 180, offset), cy = y + Angles.trnsy(rotation + 180, offset); trail.update(cx, cy); } drag = type.drag * (isGrounded() ? (floorOn().dragMultiplier) : 1f) * dragMultiplier * state.rules.dragMultiplier; //apply knockback based on spawns if(team != state.rules.waveTeam && state.hasSpawns() && (!net.client() || isLocal()) && hittable()){ float relativeSize = state.rules.dropZoneRadius + hitSize/2f + 1f; for(Tile spawn : spawner.getSpawns()){ if(within(spawn.worldx(), spawn.worldy(), relativeSize)){ velAddNet(Tmp.v1.set(this).sub(spawn.worldx(), spawn.worldy()).setLength(0.1f + 1f - dst(spawn) / relativeSize).scl(0.45f * Time.delta)); } } } //simulate falling down if(dead || health <= 0){ //less drag when dead drag = 0.01f; //standard fall smoke if(Mathf.chanceDelta(0.1)){ Tmp.v1.rnd(Mathf.range(hitSize)); type.fallEffect.at(x + Tmp.v1.x, y + Tmp.v1.y); } //thruster fall trail if(Mathf.chanceDelta(0.2)){ float offset = type.engineOffset/2f + type.engineOffset/2f * elevation; float range = Mathf.range(type.engineSize); type.fallEngineEffect.at( x + Angles.trnsx(rotation + 180, offset) + Mathf.range(range), y + Angles.trnsy(rotation + 180, offset) + Mathf.range(range), Mathf.random() ); } //move down elevation -= type.fallSpeed * Time.delta; if(isGrounded() || health <= -maxHealth){ Call.unitDestroy(id); } } Tile tile = tileOn(); Floor floor = floorOn(); if(tile != null && isGrounded() && !type.hovering){ //unit block update if(tile.build != null){ tile.build.unitOn(self()); } //apply damage if(floor.damageTaken > 0f){ damageContinuous(floor.damageTaken); } } //kill entities on tiles that are solid to them if(tile != null && !canPassOn()){ //boost if possible if(type.canBoost){ elevation = 1f; }else if(!net.client()){ kill(); } } //AI only updates on the server if(!net.client() && !dead){ controller.updateUnit(); } //clear controller when it becomes invalid if(!controller.isValidController()){ resetController(); } //remove units spawned by the core if(spawnedByCore && !isPlayer() && !dead){ Call.unitDespawn(self()); } } /** @return a preview UI icon for this unit. */ public TextureRegion icon(){ return type.uiIcon; } /** Actually destroys the unit, removing it and creating explosions. **/ public void destroy(){ if(!isAdded() || !type.killable) return; float explosiveness = 2f + item().explosiveness * stack().amount * 1.53f; float flammability = item().flammability * stack().amount / 1.9f; float power = item().charge * Mathf.pow(stack().amount, 1.11f) * 160f; if(!spawnedByCore){ Damage.dynamicExplosion(x, y, flammability, explosiveness, power, (bounds() + type.legLength/1.7f) / 2f, state.rules.damageExplosions && state.rules.unitCrashDamage(team) > 0, item().flammability > 1, team, type.deathExplosionEffect); }else{ type.deathExplosionEffect.at(x, y, bounds() / 2f / 8f); } float shake = hitSize / 3f; if(type.createScorch){ Effect.scorch(x, y, (int)(hitSize / 5)); } Effect.shake(shake, shake, this); type.deathSound.at(this); Events.fire(new UnitDestroyEvent(self())); if(explosiveness > 7f && (isLocal() || wasPlayer)){ Events.fire(Trigger.suicideBomb); } for(WeaponMount mount : mounts){ if(mount.weapon.shootOnDeath && !(mount.weapon.bullet.killShooter && mount.totalShots > 0)){ mount.reload = 0f; mount.shoot = true; mount.weapon.update(self(), mount); } } //if this unit crash landed (was flying), damage stuff in a radius if(type.flying && !spawnedByCore && type.createWreck && state.rules.unitCrashDamage(team) > 0){ Damage.damage(team, x, y, Mathf.pow(hitSize, 0.94f) * 1.25f, Mathf.pow(hitSize, 0.75f) * type.crashDamageMultiplier * 5f * state.rules.unitCrashDamage(team), true, false, true); } if(!headless && type.createScorch){ for(int i = 0; i < type.wreckRegions.length; i++){ if(type.wreckRegions[i].found()){ float range = type.hitSize /4f; Tmp.v1.rnd(range); Effect.decal(type.wreckRegions[i], x + Tmp.v1.x, y + Tmp.v1.y, rotation - 90); } } } for(Ability a : abilities){ a.death(self()); } type.killed(self()); remove(); } /** @return name of direct or indirect player controller. */ @Override public @Nullable String getControllerName(){ if(isPlayer()) return getPlayer().coloredName(); if(controller instanceof LogicAI ai && ai.controller != null) return ai.controller.lastAccessed; return null; } @Override public void display(Table table){ type.display(self(), table); } @Override public boolean isImmune(StatusEffect effect){ return type.immunities.contains(effect); } @Override public void draw(){ type.draw(self()); } @Override public boolean isPlayer(){ return controller instanceof Player; } @Nullable public Player getPlayer(){ return isPlayer() ? (Player)controller : null; } @Override public void killed(){ wasPlayer = isLocal(); health = Math.min(health, 0); dead = true; //don't waste time when the unit is already on the ground, just destroy it if(!type.flying || !type.createWreck){ destroy(); } } @Override @Replace public void kill(){ if(dead || net.client() || !type.killable) return; //deaths are synced; this calls killed() Call.unitDeath(id); } @Override @Replace public String toString(){ return "Unit#" + id() + ":" + type; } }
Anuken/Mindustry
core/src/mindustry/entities/comp/UnitComp.java
2,145
/* * Copyright (C) 2009-2019 The Project Lombok Authors. * * 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 lombok.eclipse; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.Initializer; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; /** * Standard adapter for the {@link EclipseASTVisitor} interface. Every method on that interface * has been implemented with an empty body. Override whichever methods you need. */ public abstract class EclipseASTAdapter implements EclipseASTVisitor { private final boolean deferUntilPostDiet = getClass().isAnnotationPresent(DeferUntilPostDiet.class); /** {@inheritDoc} */ public void visitCompilationUnit(EclipseNode top, CompilationUnitDeclaration unit) {} /** {@inheritDoc} */ public void endVisitCompilationUnit(EclipseNode top, CompilationUnitDeclaration unit) {} /** {@inheritDoc} */ public void visitType(EclipseNode typeNode, TypeDeclaration type) {} /** {@inheritDoc} */ public void visitAnnotationOnType(TypeDeclaration type, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ public void endVisitType(EclipseNode typeNode, TypeDeclaration type) {} /** {@inheritDoc} */ public void visitInitializer(EclipseNode initializerNode, Initializer initializer) {} /** {@inheritDoc} */ public void endVisitInitializer(EclipseNode initializerNode, Initializer initializer) {} /** {@inheritDoc} */ public void visitField(EclipseNode fieldNode, FieldDeclaration field) {} /** {@inheritDoc} */ public void visitAnnotationOnField(FieldDeclaration field, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ public void endVisitField(EclipseNode fieldNode, FieldDeclaration field) {} /** {@inheritDoc} */ public void visitMethod(EclipseNode methodNode, AbstractMethodDeclaration method) {} /** {@inheritDoc} */ public void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ public void endVisitMethod(EclipseNode methodNode, AbstractMethodDeclaration method) {} /** {@inheritDoc} */ public void visitMethodArgument(EclipseNode argNode, Argument arg, AbstractMethodDeclaration method) {} /** {@inheritDoc} */ public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ public void endVisitMethodArgument(EclipseNode argNode, Argument arg, AbstractMethodDeclaration method) {} /** {@inheritDoc} */ public void visitLocal(EclipseNode localNode, LocalDeclaration local) {} /** {@inheritDoc} */ public void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ public void endVisitLocal(EclipseNode localNode, LocalDeclaration local) {} /** {@inheritDoc} */ @Override public void visitTypeUse(EclipseNode typeUseNode, TypeReference typeUse) {} /** {@inheritDoc} */ public void visitAnnotationOnTypeUse(TypeReference typeUse, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ @Override public void endVisitTypeUse(EclipseNode typeUseNode, TypeReference typeUse) {} /** {@inheritDoc} */ public void visitStatement(EclipseNode statementNode, Statement statement) {} /** {@inheritDoc} */ public void endVisitStatement(EclipseNode statementNode, Statement statement) {} public boolean isDeferUntilPostDiet() { return deferUntilPostDiet ; } }
projectlombok/lombok
src/core/lombok/eclipse/EclipseASTAdapter.java
2,146
/* * Copyright (C) 2013,2014 Brett Wooldridge * * 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.zaxxer.hikari.pool; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLTransientConnectionException; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheckRegistry; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariPoolMXBean; import com.zaxxer.hikari.metrics.MetricsTrackerFactory; import com.zaxxer.hikari.metrics.PoolStats; import com.zaxxer.hikari.metrics.dropwizard.CodahaleHealthChecker; import com.zaxxer.hikari.metrics.dropwizard.CodahaleMetricsTrackerFactory; import com.zaxxer.hikari.util.ClockSource; import com.zaxxer.hikari.util.ConcurrentBag; import com.zaxxer.hikari.util.ConcurrentBag.IBagStateListener; import com.zaxxer.hikari.util.UtilityElf.DefaultThreadFactory; import com.zaxxer.hikari.util.SuspendResumeLock; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static com.zaxxer.hikari.pool.PoolEntry.LAST_ACCESS_COMPARABLE; import static com.zaxxer.hikari.util.ConcurrentBag.IConcurrentBagEntry.STATE_IN_USE; import static com.zaxxer.hikari.util.ConcurrentBag.IConcurrentBagEntry.STATE_NOT_IN_USE; import static com.zaxxer.hikari.util.ConcurrentBag.IConcurrentBagEntry.STATE_REMOVED; import static com.zaxxer.hikari.util.UtilityElf.createThreadPoolExecutor; import static com.zaxxer.hikari.util.UtilityElf.quietlySleep; /** * This is the primary connection pool class that provides the basic * pooling behavior for HikariCP. * * @author Brett Wooldridge */ public class HikariPool extends PoolBase implements HikariPoolMXBean, IBagStateListener { private final Logger LOGGER = LoggerFactory.getLogger(HikariPool.class); private static final ClockSource clockSource = ClockSource.INSTANCE; private static final int POOL_NORMAL = 0; private static final int POOL_SUSPENDED = 1; private static final int POOL_SHUTDOWN = 2; private volatile int poolState; private final long ALIVE_BYPASS_WINDOW_MS = Long.getLong("com.zaxxer.hikari.aliveBypassWindowMs", MILLISECONDS.toMillis(500)); private final long HOUSEKEEPING_PERIOD_MS = Long.getLong("com.zaxxer.hikari.housekeeping.periodMs", SECONDS.toMillis(30)); private final PoolEntryCreator POOL_ENTRY_CREATOR = new PoolEntryCreator(); private final AtomicInteger totalConnections; private final ThreadPoolExecutor addConnectionExecutor; private final ThreadPoolExecutor closeConnectionExecutor; private final ScheduledThreadPoolExecutor houseKeepingExecutorService; private final ConcurrentBag<PoolEntry> connectionBag; private final ProxyLeakTask leakTask; private final SuspendResumeLock suspendResumeLock; private MetricsTrackerDelegate metricsTracker; /** * Construct a HikariPool with the specified configuration. * * @param config a HikariConfig instance */ public HikariPool(final HikariConfig config) { super(config); this.connectionBag = new ConcurrentBag<>(this); this.totalConnections = new AtomicInteger(); this.suspendResumeLock = config.isAllowPoolSuspension() ? new SuspendResumeLock() : SuspendResumeLock.FAUX_LOCK; if (config.getMetricsTrackerFactory() != null) { setMetricsTrackerFactory(config.getMetricsTrackerFactory()); } else { setMetricRegistry(config.getMetricRegistry()); } setHealthCheckRegistry(config.getHealthCheckRegistry()); registerMBeans(this); checkFailFast(); ThreadFactory threadFactory = config.getThreadFactory(); this.addConnectionExecutor = createThreadPoolExecutor(config.getMaximumPoolSize(), poolName + " connection adder", threadFactory, new ThreadPoolExecutor.DiscardPolicy()); this.closeConnectionExecutor = createThreadPoolExecutor(config.getMaximumPoolSize(), poolName + " connection closer", threadFactory, new ThreadPoolExecutor.CallerRunsPolicy()); if (config.getScheduledExecutorService() == null) { threadFactory = threadFactory != null ? threadFactory : new DefaultThreadFactory(poolName + " housekeeper", true); this.houseKeepingExecutorService = new ScheduledThreadPoolExecutor(1, threadFactory, new ThreadPoolExecutor.DiscardPolicy()); this.houseKeepingExecutorService.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); this.houseKeepingExecutorService.setRemoveOnCancelPolicy(true); } else { this.houseKeepingExecutorService = config.getScheduledExecutorService(); } this.houseKeepingExecutorService.scheduleWithFixedDelay(new HouseKeeper(), 0L, HOUSEKEEPING_PERIOD_MS, MILLISECONDS); this.leakTask = new ProxyLeakTask(config.getLeakDetectionThreshold(), houseKeepingExecutorService); } /** * Get a connection from the pool, or timeout after connectionTimeout milliseconds. * * @return a java.sql.Connection instance * @throws SQLException thrown if a timeout occurs trying to obtain a connection */ public final Connection getConnection() throws SQLException { return getConnection(connectionTimeout); } /** * Get a connection from the pool, or timeout after the specified number of milliseconds. * * @param hardTimeout the maximum time to wait for a connection from the pool * @return a java.sql.Connection instance * @throws SQLException thrown if a timeout occurs trying to obtain a connection */ public final Connection getConnection(final long hardTimeout) throws SQLException { suspendResumeLock.acquire(); final long startTime = clockSource.currentTime(); try { long timeout = hardTimeout; do { final PoolEntry poolEntry = connectionBag.borrow(timeout, MILLISECONDS); if (poolEntry == null) { break; // We timed out... break and throw exception } final long now = clockSource.currentTime(); if (poolEntry.isMarkedEvicted() || (clockSource.elapsedMillis(poolEntry.lastAccessed, now) > ALIVE_BYPASS_WINDOW_MS && !isConnectionAlive(poolEntry.connection))) { closeConnection(poolEntry, "(connection is evicted or dead)"); // Throw away the dead connection (passed max age or failed alive test) timeout = hardTimeout - clockSource.elapsedMillis(startTime); } else { metricsTracker.recordBorrowStats(poolEntry, startTime); return poolEntry.createProxyConnection(leakTask.schedule(poolEntry), now); } } while (timeout > 0L); } catch (InterruptedException e) { throw new SQLException(poolName + " - Interrupted during connection acquisition", e); } finally { suspendResumeLock.release(); } logPoolState("Timeout failure "); metricsTracker.recordConnectionTimeout(); String sqlState = null; final Throwable originalException = getLastConnectionFailure(); if (originalException instanceof SQLException) { sqlState = ((SQLException) originalException).getSQLState(); } final SQLException connectionException = new SQLTransientConnectionException(poolName + " - Connection is not available, request timed out after " + clockSource.elapsedMillis(startTime) + "ms.", sqlState, originalException); if (originalException instanceof SQLException) { connectionException.setNextException((SQLException) originalException); } throw connectionException; } /** * Shutdown the pool, closing all idle connections and aborting or closing * active connections. * * @throws InterruptedException thrown if the thread is interrupted during shutdown */ public final synchronized void shutdown() throws InterruptedException { try { poolState = POOL_SHUTDOWN; LOGGER.info("{} - Close initiated...", poolName); logPoolState("Before closing "); softEvictConnections(); addConnectionExecutor.shutdown(); addConnectionExecutor.awaitTermination(5L, SECONDS); if (config.getScheduledExecutorService() == null && houseKeepingExecutorService != null) { houseKeepingExecutorService.shutdown(); houseKeepingExecutorService.awaitTermination(5L, SECONDS); } connectionBag.close(); final ExecutorService assassinExecutor = createThreadPoolExecutor(config.getMaximumPoolSize(), poolName + " connection assassinator", config.getThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy()); try { final long start = clockSource.currentTime(); do { abortActiveConnections(assassinExecutor); softEvictConnections(); } while (getTotalConnections() > 0 && clockSource.elapsedMillis(start) < SECONDS.toMillis(5)); } finally { assassinExecutor.shutdown(); assassinExecutor.awaitTermination(5L, SECONDS); } shutdownNetworkTimeoutExecutor(); closeConnectionExecutor.shutdown(); closeConnectionExecutor.awaitTermination(5L, SECONDS); } finally { logPoolState("After closing "); unregisterMBeans(); metricsTracker.close(); LOGGER.info("{} - Closed.", poolName); } } /** * Evict a connection from the pool. * * @param connection the connection to evict */ public final void evictConnection(Connection connection) { ProxyConnection proxyConnection = (ProxyConnection) connection; proxyConnection.cancelLeakTask(); softEvictConnection(proxyConnection.getPoolEntry(), "(connection evicted by user)", true /* owner */); } public void setMetricRegistry(Object metricRegistry) { if (metricRegistry != null) { setMetricsTrackerFactory(new CodahaleMetricsTrackerFactory((MetricRegistry) metricRegistry)); } else { setMetricsTrackerFactory(null); } } public void setMetricsTrackerFactory(MetricsTrackerFactory metricsTrackerFactory) { if (metricsTrackerFactory != null) { this.metricsTracker = new MetricsTrackerDelegate(metricsTrackerFactory.create(config.getPoolName(), getPoolStats())); } else { this.metricsTracker = new NopMetricsTrackerDelegate(); } } public void setHealthCheckRegistry(Object healthCheckRegistry) { if (healthCheckRegistry != null) { CodahaleHealthChecker.registerHealthChecks(this, config, (HealthCheckRegistry) healthCheckRegistry); } } // *********************************************************************** // IBagStateListener callback // *********************************************************************** /** {@inheritDoc} */ @Override public Future<Boolean> addBagItem() { return addConnectionExecutor.submit(POOL_ENTRY_CREATOR); } // *********************************************************************** // HikariPoolMBean methods // *********************************************************************** /** {@inheritDoc} */ @Override public final int getActiveConnections() { return connectionBag.getCount(STATE_IN_USE); } /** {@inheritDoc} */ @Override public final int getIdleConnections() { return connectionBag.getCount(STATE_NOT_IN_USE); } /** {@inheritDoc} */ @Override public final int getTotalConnections() { return connectionBag.size() - connectionBag.getCount(STATE_REMOVED); } /** {@inheritDoc} */ @Override public final int getThreadsAwaitingConnection() { return connectionBag.getPendingQueue(); } /** {@inheritDoc} */ @Override public void softEvictConnections() { for (PoolEntry poolEntry : connectionBag.values()) { softEvictConnection(poolEntry, "(connection evicted)", false /* not owner */); } } /** {@inheritDoc} */ @Override public final synchronized void suspendPool() { if (suspendResumeLock == SuspendResumeLock.FAUX_LOCK) { throw new IllegalStateException(poolName + " - is not suspendable"); } else if (poolState != POOL_SUSPENDED) { suspendResumeLock.suspend(); poolState = POOL_SUSPENDED; } } /** {@inheritDoc} */ @Override public final synchronized void resumePool() { if (poolState == POOL_SUSPENDED) { poolState = POOL_NORMAL; fillPool(); suspendResumeLock.resume(); } } // *********************************************************************** // Package methods // *********************************************************************** /** * Log the current pool state at debug level. * * @param prefix an optional prefix to prepend the log message */ final void logPoolState(String... prefix) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("{} - {}stats (total={}, active={}, idle={}, waiting={})", poolName, (prefix.length > 0 ? prefix[0] : ""), getTotalConnections(), getActiveConnections(), getIdleConnections(), getThreadsAwaitingConnection()); } } /** * Release a connection back to the pool, or permanently close it if it is broken. * * @param poolEntry the PoolBagEntry to release back to the pool */ @Override final void releaseConnection(final PoolEntry poolEntry) { metricsTracker.recordConnectionUsage(poolEntry); connectionBag.requite(poolEntry); } /** * Permanently close the real (underlying) connection (eat any exception). * * @param poolEntry poolEntry having the connection to close * @param closureReason reason to close */ final void closeConnection(final PoolEntry poolEntry, final String closureReason) { if (connectionBag.remove(poolEntry)) { final int tc = totalConnections.decrementAndGet(); if (tc < 0) { LOGGER.warn("{} - Unexpected value of totalConnections={}", poolName, tc, new Exception()); } final Connection connection = poolEntry.close(); closeConnectionExecutor.execute(new Runnable() { @Override public void run() { quietlyCloseConnection(connection, closureReason); } }); } } // *********************************************************************** // Private methods // *********************************************************************** /** * Create and add a single connection to the pool. */ private PoolEntry createPoolEntry() { try { final PoolEntry poolEntry = newPoolEntry(); final long maxLifetime = config.getMaxLifetime(); if (maxLifetime > 0) { // variance up to 2.5% of the maxlifetime final long variance = maxLifetime > 10_000 ? ThreadLocalRandom.current().nextLong( maxLifetime / 40 ) : 0; final long lifetime = maxLifetime - variance; poolEntry.setFutureEol(houseKeepingExecutorService.schedule(new Runnable() { @Override public void run() { softEvictConnection(poolEntry, "(connection has passed maxLifetime)", false /* not owner */); } }, lifetime, MILLISECONDS)); } LOGGER.debug("{} - Added connection {}", poolName, poolEntry.connection); return poolEntry; } catch (Exception e) { if (poolState == POOL_NORMAL) { LOGGER.debug("{} - Cannot acquire connection from data source", poolName, e); } return null; } } /** * Fill pool up from current idle connections (as they are perceived at the point of execution) to minimumIdle connections. */ private void fillPool() { final int connectionsToAdd = Math.min(config.getMaximumPoolSize() - totalConnections.get(), config.getMinimumIdle() - getIdleConnections()) - addConnectionExecutor.getQueue().size(); for (int i = 0; i < connectionsToAdd; i++) { addBagItem(); } if (connectionsToAdd > 0 && LOGGER.isDebugEnabled()) { addConnectionExecutor.execute(new Runnable() { @Override public void run() { logPoolState("After adding "); } }); } } /** * Attempt to abort() active connections, or close() them. */ private void abortActiveConnections(final ExecutorService assassinExecutor) { for (PoolEntry poolEntry : connectionBag.values(STATE_IN_USE)) { try { poolEntry.connection.abort(assassinExecutor); } catch (Throwable e) { quietlyCloseConnection(poolEntry.connection, "(connection aborted during shutdown)"); } finally { poolEntry.close(); if (connectionBag.remove(poolEntry)) { totalConnections.decrementAndGet(); } } } } /** * Fill the pool up to the minimum size. */ private void checkFailFast() { if (config.isInitializationFailFast()) { try { newConnection().close(); } catch (Throwable e) { try { shutdown(); } catch (Throwable ex) { e.addSuppressed(ex); } throw new PoolInitializationException(e); } } } private void softEvictConnection(final PoolEntry poolEntry, final String reason, final boolean owner) { if (owner || connectionBag.reserve(poolEntry)) { closeConnection(poolEntry, reason); } else { poolEntry.markEvicted(); } } private PoolStats getPoolStats() { return new PoolStats(SECONDS.toMillis(1)) { @Override protected void update() { this.pendingThreads = HikariPool.this.getThreadsAwaitingConnection(); this.idleConnections = HikariPool.this.getIdleConnections(); this.totalConnections = HikariPool.this.getTotalConnections(); this.activeConnections = HikariPool.this.getActiveConnections(); } }; } // *********************************************************************** // Non-anonymous Inner-classes // *********************************************************************** private class PoolEntryCreator implements Callable<Boolean> { @Override public Boolean call() throws Exception { long sleepBackoff = 250L; while (poolState == POOL_NORMAL && totalConnections.get() < config.getMaximumPoolSize()) { final PoolEntry poolEntry = createPoolEntry(); if (poolEntry != null) { totalConnections.incrementAndGet(); connectionBag.add(poolEntry); return Boolean.TRUE; } // failed to get connection from db, sleep and retry quietlySleep(sleepBackoff); sleepBackoff = Math.min(SECONDS.toMillis(10), Math.min(connectionTimeout, (long) (sleepBackoff * 1.5))); } // Pool is suspended or shutdown or at max size return Boolean.FALSE; } } /** * The house keeping task to retire idle connections. */ private class HouseKeeper implements Runnable { private volatile long previous = clockSource.plusMillis(clockSource.currentTime(), -HOUSEKEEPING_PERIOD_MS); @Override public void run() { // refresh timeouts in case they changed via MBean connectionTimeout = config.getConnectionTimeout(); validationTimeout = config.getValidationTimeout(); leakTask.updateLeakDetectionThreshold(config.getLeakDetectionThreshold()); final long idleTimeout = config.getIdleTimeout(); final long now = clockSource.currentTime(); // Detect retrograde time, allowing +128ms as per NTP spec. if (clockSource.plusMillis(now, 128) < clockSource.plusMillis(previous, HOUSEKEEPING_PERIOD_MS)) { LOGGER.warn("{} - Retrograde clock change detected (housekeeper delta={}), soft-evicting connections from pool.", clockSource.elapsedDisplayString(previous, now), poolName); previous = now; softEvictConnections(); fillPool(); return; } else if (now > clockSource.plusMillis(previous, (3 * HOUSEKEEPING_PERIOD_MS) / 2)) { // No point evicting for forward clock motion, this merely accelerates connection retirement anyway LOGGER.warn("{} - Thread starvation or clock leap detected (housekeeper delta={}).", clockSource.elapsedDisplayString(previous, now), poolName); } previous = now; String afterPrefix = "Pool "; if (idleTimeout > 0L) { final List<PoolEntry> idleList = connectionBag.values(STATE_NOT_IN_USE); int removable = idleList.size() - config.getMinimumIdle(); if (removable > 0) { logPoolState("Before cleanup "); afterPrefix = "After cleanup "; // Sort pool entries on lastAccessed Collections.sort(idleList, LAST_ACCESS_COMPARABLE); for (PoolEntry poolEntry : idleList) { if (clockSource.elapsedMillis(poolEntry.lastAccessed, now) > idleTimeout && connectionBag.reserve(poolEntry)) { closeConnection(poolEntry, "(connection has passed idleTimeout)"); if (--removable == 0) { break; // keep min idle cons } } } } } logPoolState(afterPrefix); fillPool(); // Try to maintain minimum connections } } public static class PoolInitializationException extends RuntimeException { private static final long serialVersionUID = 929872118275916520L; /** * Construct an exception, possibly wrapping the provided Throwable as the cause. * @param t the Throwable to wrap */ public PoolInitializationException(Throwable t) { super("Failed to initialize pool: " + t.getMessage(), t); } } }
brettwooldridge/HikariCP
src/main/java/com/zaxxer/hikari/pool/HikariPool.java
2,147
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2015-19 The Processing Foundation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package processing.app.ui; import java.awt.*; import java.awt.event.*; import javax.swing.*; import processing.app.Mode; abstract public class EditorButton extends JComponent implements MouseListener, MouseMotionListener, ActionListener { static public final int DIM = Toolkit.zoom(30); /** Button's description. */ protected String title; /** Description of alternate behavior when shift is down. */ protected String titleShift; /** Description of alternate behavior when alt is down. */ protected String titleAlt; protected boolean pressed; protected boolean selected; protected boolean rollover; // protected JLabel rolloverLabel; protected boolean shift; protected Image enabledImage; protected Image disabledImage; protected Image selectedImage; protected Image rolloverImage; protected Image pressedImage; protected Image gradient; protected EditorToolbar toolbar; // protected Mode mode; public EditorButton(EditorToolbar parent, String name, String title) { this(parent, name, title, title, title); } public EditorButton(EditorToolbar parent, String name, String title, String titleShift) { this(parent, name, title, titleShift, title); } public EditorButton(EditorToolbar parent, String name, String title, String titleShift, String titleAlt) { this.toolbar = parent; this.title = title; this.titleShift = titleShift; this.titleAlt = titleAlt; Mode mode = toolbar.mode; disabledImage = mode.loadImageX(name + "-disabled"); enabledImage = mode.loadImageX(name + "-enabled"); selectedImage = mode.loadImageX(name + "-selected"); pressedImage = mode.loadImageX(name + "-pressed"); rolloverImage = mode.loadImageX(name + "-rollover"); if (disabledImage == null) { disabledImage = enabledImage; } if (selectedImage == null) { selectedImage = enabledImage; } if (pressedImage == null) { pressedImage = enabledImage; // could be selected image } if (rolloverImage == null) { rolloverImage = enabledImage; // could be pressed image } addMouseListener(this); addMouseMotionListener(this); } @Override public void paintComponent(Graphics g) { Image image = enabledImage; if (!isEnabled()) { image = disabledImage; } else if (selected) { image = selectedImage; } else if (pressed) { image = pressedImage; } else if (rollover) { image = rolloverImage; } Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); int dim = getSize().width; // width == height if (gradient != null) { //g.drawImage(gradient, 0, 0, DIM, DIM, this); g.drawImage(gradient, 0, 0, dim, dim, this); } //g.drawImage(image, 0, 0, DIM, DIM, this); g.drawImage(image, 0, 0, dim, dim, this); } // public String toString() { // switch (this) { // case DISABLED: return "disabled"; // case ENABLED: return "enabled"; // case SELECTED: return "selected"; // case ROLLOVER: return "rollover"; // case PRESSED: return "pressed"; // //// for (State bs : State.values()) { //// Image image = mode.loadImage(bs.getFilename(name)); //// if (image != null) { //// imageMap.put(bs, image); //// } //// } //// //// enabled = true; //// //updateState(); //// setState(State.ENABLED); // } // public void setReverse() { // gradient = mode.makeGradient("reversed", DIM, DIM); // } // public void setGradient(Image gradient) { // this.gradient = gradient; // } // public void setRolloverLabel(JLabel label) { // rolloverLabel = label; // } @Override public void mouseClicked(MouseEvent e) { // if (isEnabled()) { // shift = e.isShiftDown(); // actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, // null, e.getModifiers())); // } } public boolean isShiftDown() { return shift; } @Override public void mousePressed(MouseEvent e) { setPressed(true); // Need to fire here (or on mouse up) because mouseClicked() // won't be fired if the user nudges the mouse while clicking. // https://github.com/processing/processing/issues/3529 shift = e.isShiftDown(); actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null, e.getModifiers())); } @Override public void mouseReleased(MouseEvent e) { setPressed(false); } public void setPressed(boolean pressed) { if (isEnabled()) { this.pressed = pressed; repaint(); } } public void setSelected(boolean selected) { this.selected = selected; } /* @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { updateRollover(e); } @Override public void keyPressed(KeyEvent e) { System.out.println(e); updateRollover(e); } */ public String getRolloverText(InputEvent e) { if (e.isShiftDown()) { return titleShift; } else if (e.isAltDown()) { return titleAlt; } return title; } /* public void updateRollover(InputEvent e) { if (rolloverLabel != null) { if (e.isShiftDown()) { rolloverLabel.setText(titleShift); } else if (e.isAltDown()) { rolloverLabel.setText(titleAlt); } else { rolloverLabel.setText(title); } } } */ @Override public void mouseEntered(MouseEvent e) { toolbar.setRollover(this, e); /* rollover = true; updateRollover(e); repaint(); */ } @Override public void mouseExited(MouseEvent e) { toolbar.setRollover(null, e); /* rollover = false; if (rolloverLabel != null) { rolloverLabel.setText(""); } repaint(); */ } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { } abstract public void actionPerformed(ActionEvent e); // @Override // public void actionPerformed(ActionEvent e) { // // To be overridden by all subclasses // } @Override public Dimension getPreferredSize() { return new Dimension(DIM, DIM); } @Override public Dimension getMinimumSize() { return getPreferredSize(); } @Override public Dimension getMaximumSize() { return getPreferredSize(); } // public Image getImage() { // return imageMap.get(state); // } // // //// protected void updateState() { //// state = ButtonState.ENABLED; //// } // // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // if (enabled) { // if (state == State.DISABLED) { // setState(State.ENABLED); // } // } else { // if (state == State.ENABLED) { // setState(State.DISABLED); // } // } // } // // // public void setState(State state) { // this.state = state; // } // public enum State { // DISABLED, ENABLED, SELECTED, ROLLOVER, PRESSED; // // /** // * @param name the root name // * @return // */ // public String getFilename(String name) { // final int res = Toolkit.highResDisplay() ? 2 : 1; // return name + "-" + toString() + "-" + res + "x.png"; // } // // public String toString() { // switch (this) { // case DISABLED: return "disabled"; // case ENABLED: return "enabled"; // case SELECTED: return "selected"; // case ROLLOVER: return "rollover"; // case PRESSED: return "pressed"; // } // return null; // } // } }
processing/processing
app/src/processing/app/ui/EditorButton.java
2,148
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyirght (c) 2012-19 The Processing Foundation Copyright (c) 2004-12 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology 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, version 2. 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.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.Box; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPopupMenu; import processing.app.Base; import processing.app.Language; import processing.app.Mode; /** * Run/Stop button plus Mode selection */ abstract public class EditorToolbar extends JPanel implements KeyListener { // haven't decided how to handle this/how to make public/consistency // for components/does it live in theme.txt static final int HIGH = Toolkit.zoom(53); // horizontal gap between buttons static final int GAP = Toolkit.zoom(9); // corner radius on the mode selector static final int RADIUS = Toolkit.zoom(3); protected Editor editor; protected Base base; protected Mode mode; protected EditorButton runButton; protected EditorButton stopButton; protected EditorButton rolloverButton; protected JLabel rolloverLabel; protected Box box; protected Image gradient; public EditorToolbar(Editor editor) { this.editor = editor; base = editor.getBase(); mode = editor.getMode(); gradient = mode.makeGradient("toolbar", Toolkit.zoom(400), HIGH); rebuild(); } public void rebuild() { removeAll(); // remove previous components, if any List<EditorButton> buttons = createButtons(); box = Box.createHorizontalBox(); box.add(Box.createHorizontalStrut(Editor.LEFT_GUTTER)); rolloverLabel = new JLabel(); rolloverLabel.setFont(mode.getFont("toolbar.rollover.font")); rolloverLabel.setForeground(mode.getColor("toolbar.rollover.color")); for (EditorButton button : buttons) { box.add(button); box.add(Box.createHorizontalStrut(GAP)); // registerButton(button); } // // remove the last gap // box.remove(box.getComponentCount() - 1); // box.add(Box.createHorizontalStrut(LABEL_GAP)); box.add(rolloverLabel); // currentButton = runButton; // runButton.setRolloverLabel(label); // stopButton.setRolloverLabel(label); box.add(Box.createHorizontalGlue()); addModeButtons(box, rolloverLabel); // Component items = createModeButtons(); // if (items != null) { // box.add(items); // } ModeSelector ms = new ModeSelector(); box.add(ms); box.add(Box.createHorizontalStrut(Editor.RIGHT_GUTTER)); setLayout(new BorderLayout()); add(box, BorderLayout.CENTER); } // public void registerButton(EditorButton button) { //button.setRolloverLabel(rolloverLabel); //editor.getTextArea().addKeyListener(button); // } // public void setReverse(EditorButton button) { // button.setGradient(reverseGradient); // } // public void setText(String text) { // label.setText(text); // } public void paintComponent(Graphics g) { Dimension size = getSize(); g.drawImage(gradient, 0, 0, size.width, size.height, this); } public List<EditorButton> createButtons() { runButton = new EditorButton(this, "/lib/toolbar/run", Language.text("toolbar.run"), Language.text("toolbar.present")) { @Override public void actionPerformed(ActionEvent e) { handleRun(e.getModifiers()); } }; stopButton = new EditorButton(this, "/lib/toolbar/stop", Language.text("toolbar.stop")) { @Override public void actionPerformed(ActionEvent e) { handleStop(); } }; return new ArrayList<>(Arrays.asList(runButton, stopButton)); } public void addModeButtons(Box box, JLabel label) { } public void addGap(Box box) { box.add(Box.createHorizontalStrut(GAP)); } // public Component createModeSelector() { // return new ModeSelector(); // } // protected void swapButton(EditorButton replacement) { // if (currentButton != replacement) { // box.remove(currentButton); // box.add(replacement, 1); // has to go after the strut // box.revalidate(); // box.repaint(); // may be needed // currentButton = replacement; // } // } public void activateRun() { runButton.setSelected(true); repaint(); } public void deactivateRun() { runButton.setSelected(false); repaint(); } public void activateStop() { stopButton.setSelected(true); repaint(); } public void deactivateStop() { stopButton.setSelected(false); repaint(); } abstract public void handleRun(int modifiers); abstract public void handleStop(); void setRollover(EditorButton button, InputEvent e) { rolloverButton = button; // if (rolloverButton != null) { updateRollover(e); // } else { // rolloverLabel.setText(""); // } } void updateRollover(InputEvent e) { if (rolloverButton != null) { rolloverLabel.setText(rolloverButton.getRolloverText(e)); } else { rolloverLabel.setText(""); } } @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { updateRollover(e); } @Override public void keyPressed(KeyEvent e) { updateRollover(e); } public Dimension getPreferredSize() { return new Dimension(super.getPreferredSize().width, HIGH); } public Dimension getMinimumSize() { return new Dimension(super.getMinimumSize().width, HIGH); } public Dimension getMaximumSize() { return new Dimension(super.getMaximumSize().width, HIGH); } class ModeSelector extends JPanel { Image offscreen; int width, height; String title; Font titleFont; Color titleColor; int titleAscent; int titleWidth; final int MODE_GAP_WIDTH = Toolkit.zoom(13); final int ARROW_GAP_WIDTH = Toolkit.zoom(6); final int ARROW_WIDTH = Toolkit.zoom(6); final int ARROW_TOP = Toolkit.zoom(12); final int ARROW_BOTTOM = Toolkit.zoom(18); int[] triangleX = new int[3]; int[] triangleY = new int[] { ARROW_TOP, ARROW_TOP, ARROW_BOTTOM }; // Image background; Color backgroundColor; Color outlineColor; @SuppressWarnings("deprecation") public ModeSelector() { title = mode.getTitle(); //.toUpperCase(); titleFont = mode.getFont("mode.title.font"); titleColor = mode.getColor("mode.title.color"); // getGraphics() is null and no offscreen yet titleWidth = getToolkit().getFontMetrics(titleFont).stringWidth(title); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent event) { JPopupMenu popup = editor.getModePopup(); popup.show(ModeSelector.this, event.getX(), event.getY()); } }); //background = mode.getGradient("reversed", 100, EditorButton.DIM); backgroundColor = mode.getColor("mode.background.color"); outlineColor = mode.getColor("mode.outline.color"); } @Override public void paintComponent(Graphics screen) { // Toolkit.debugOpacity(this); Dimension size = getSize(); width = 0; if (width != size.width || height != size.height) { offscreen = Toolkit.offscreenGraphics(this, size.width, size.height); width = size.width; height = size.height; } Graphics g = offscreen.getGraphics(); Graphics2D g2 = Toolkit.prepareGraphics(g); //Toolkit.clearGraphics(g, width, height); // g.clearRect(0, 0, width, height); // g.setColor(Color.GREEN); // g.fillRect(0, 0, width, height); g.setFont(titleFont); if (titleAscent == 0) { titleAscent = (int) Toolkit.getAscent(g); //metrics.getAscent(); } FontMetrics metrics = g.getFontMetrics(); titleWidth = metrics.stringWidth(title); // clear the background g.setColor(backgroundColor); g.fillRect(0, 0, width, height); // draw the outline for this feller g.setColor(outlineColor); //Toolkit.dpiStroke(g2); g2.draw(Toolkit.createRoundRect(1, 1, width-1, height-1, RADIUS, RADIUS, RADIUS, RADIUS)); g.setColor(titleColor); g.drawString(title, MODE_GAP_WIDTH, (height + titleAscent) / 2); int x = MODE_GAP_WIDTH + titleWidth + ARROW_GAP_WIDTH; triangleX[0] = x; triangleX[1] = x + ARROW_WIDTH; triangleX[2] = x + ARROW_WIDTH/2; g.fillPolygon(triangleX, triangleY, 3); screen.drawImage(offscreen, 0, 0, width, height, this); } @Override public Dimension getPreferredSize() { return new Dimension(MODE_GAP_WIDTH + titleWidth + ARROW_GAP_WIDTH + ARROW_WIDTH + MODE_GAP_WIDTH, EditorButton.DIM); } @Override public Dimension getMinimumSize() { return getPreferredSize(); } @Override public Dimension getMaximumSize() { return getPreferredSize(); } } }
processing/processing
app/src/processing/app/ui/EditorToolbar.java
2,149
/* * Copyright (C) 2009-2019 The Project Lombok Authors. * * 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 lombok.eclipse; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.io.PrintStream; import java.lang.reflect.Modifier; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.Initializer; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation; import org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; /** * Implement so you can ask any EclipseAST.Node to traverse depth-first through all children, * calling the appropriate visit and endVisit methods. */ public interface EclipseASTVisitor { /** * Called at the very beginning and end. */ void visitCompilationUnit(EclipseNode top, CompilationUnitDeclaration unit); void endVisitCompilationUnit(EclipseNode top, CompilationUnitDeclaration unit); /** * Called when visiting a type (a class, interface, annotation, enum, etcetera). */ void visitType(EclipseNode typeNode, TypeDeclaration type); void visitAnnotationOnType(TypeDeclaration type, EclipseNode annotationNode, Annotation annotation); void endVisitType(EclipseNode typeNode, TypeDeclaration type); /** * Called when visiting a field of a class. * Even though in Eclipse initializers (both instance and static) are represented as Initializer objects, * which are a subclass of FieldDeclaration, those do NOT result in a call to this method. They result * in a call to the visitInitializer method. */ void visitField(EclipseNode fieldNode, FieldDeclaration field); void visitAnnotationOnField(FieldDeclaration field, EclipseNode annotationNode, Annotation annotation); void endVisitField(EclipseNode fieldNode, FieldDeclaration field); /** * Called for static and instance initializers. You can tell the difference via the modifier flag on the * ASTNode (8 for static, 0 for not static). The content is in the 'block', not in the 'initialization', * which would always be null for an initializer instance. */ void visitInitializer(EclipseNode initializerNode, Initializer initializer); void endVisitInitializer(EclipseNode initializerNode, Initializer initializer); /** * Called for both methods (MethodDeclaration) and constructors (ConstructorDeclaration), but not for * Clinit objects, which are a vestigial Eclipse thing that never contain anything. Static initializers * show up as 'Initializer', in the visitInitializer method, with modifier bit STATIC set. */ void visitMethod(EclipseNode methodNode, AbstractMethodDeclaration method); void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation); void endVisitMethod(EclipseNode methodNode, AbstractMethodDeclaration method); /** * Visits a method argument */ void visitMethodArgument(EclipseNode argNode, Argument arg, AbstractMethodDeclaration method); void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation); void endVisitMethodArgument(EclipseNode argNode, Argument arg, AbstractMethodDeclaration method); /** * Visits a local declaration - that is, something like 'int x = 10;' on the method level. */ void visitLocal(EclipseNode localNode, LocalDeclaration local); void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode annotationNode, Annotation annotation); void endVisitLocal(EclipseNode localNode, LocalDeclaration local); /** * Visits a node that represents a type reference. Anything from {@code int} to {@code T} to {@code foo,.pkg.Bar<T>.Baz<?> @Ann []}. */ void visitTypeUse(EclipseNode typeUseNode, TypeReference typeUse); void visitAnnotationOnTypeUse(TypeReference typeUse, EclipseNode annotationNode, Annotation annotation); void endVisitTypeUse(EclipseNode typeUseNode, TypeReference typeUse); /** * Visits a statement that isn't any of the other visit methods (e.g. TypeDeclaration). */ void visitStatement(EclipseNode statementNode, Statement statement); void endVisitStatement(EclipseNode statementNode, Statement statement); /** * Prints the structure of an AST. */ public static class Printer implements EclipseASTVisitor { private final PrintStream out; private final boolean printContent; private int disablePrinting = 0; private int indent = 0; private boolean printClassNames = false; private final boolean printPositions; public boolean deferUntilPostDiet() { return false; } /** * @param printContent if true, bodies are printed directly, as java code, * instead of a tree listing of every AST node inside it. */ public Printer(boolean printContent) { this(printContent, System.out, false); } /** * @param printContent if true, bodies are printed directly, as java code, * instead of a tree listing of every AST node inside it. * @param out write output to this stream. You must close it yourself. flush() is called after every line. * * @see java.io.PrintStream#flush() */ public Printer(boolean printContent, PrintStream out, boolean printPositions) { this.printContent = printContent; this.out = out; this.printPositions = printPositions; } private void forcePrint(String text, Object... params) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indent; i++) sb.append(" "); sb.append(text); Object[] t; if (printClassNames && params.length > 0) { sb.append(" ["); for (int i = 0; i < params.length; i++) { if (i > 0) sb.append(", "); sb.append("%s"); } sb.append("]"); t = new Object[params.length + params.length]; for (int i = 0; i < params.length; i++) { t[i] = params[i]; t[i + params.length] = (params[i] == null) ? "NULL " : params[i].getClass(); } } else { t = params; } sb.append("\n"); out.printf(sb.toString(), t); out.flush(); } private void print(String text, Object... params) { if (disablePrinting == 0) forcePrint(text, params); } private String str(char[] c) { if (c == null) return "(NULL)"; return new String(c); } private String str(TypeReference type) { if (type == null) return "(NULL)"; char[][] c = type.getTypeName(); StringBuilder sb = new StringBuilder(); boolean first = true; for (char[] d : c) { sb.append(first ? "" : ".").append(new String(d)); first = false; } return sb.toString(); } public void visitCompilationUnit(EclipseNode node, CompilationUnitDeclaration unit) { out.println("---------------------------------------------------------"); out.println(node.isCompleteParse() ? "COMPLETE" : "incomplete"); print("<CUD %s%s%s>", node.getFileName(), isGenerated(unit) ? " (GENERATED)" : "", position(node)); indent++; } public void endVisitCompilationUnit(EclipseNode node, CompilationUnitDeclaration unit) { indent--; print("</CUD>"); } private String printFlags(int flags, ASTNode node) { StringBuilder out = new StringBuilder(); if ((flags & ClassFileConstants.AccPublic) != 0) { flags &= ~ClassFileConstants.AccPublic; out.append("public "); } if ((flags & ClassFileConstants.AccPrivate) != 0) { flags &= ~ClassFileConstants.AccPrivate; out.append("private "); } if ((flags & ClassFileConstants.AccProtected) != 0) { flags &= ~ClassFileConstants.AccProtected; out.append("protected "); } if ((flags & ClassFileConstants.AccStatic) != 0) { flags &= ~ClassFileConstants.AccStatic; out.append("static "); } if ((flags & ClassFileConstants.AccFinal) != 0) { flags &= ~ClassFileConstants.AccFinal; out.append("final "); } if ((flags & ClassFileConstants.AccSynchronized) != 0) { flags &= ~ClassFileConstants.AccSynchronized; out.append("synchronized "); } if ((flags & ClassFileConstants.AccNative) != 0) { flags &= ~ClassFileConstants.AccNative; out.append("native "); } if ((flags & ClassFileConstants.AccInterface) != 0) { flags &= ~ClassFileConstants.AccInterface; out.append("interface "); } if ((flags & ClassFileConstants.AccAbstract) != 0) { flags &= ~ClassFileConstants.AccAbstract; out.append("abstract "); } if ((flags & ClassFileConstants.AccStrictfp) != 0) { flags &= ~ClassFileConstants.AccStrictfp; out.append("strictfp "); } if ((flags & ClassFileConstants.AccSynthetic) != 0) { flags &= ~ClassFileConstants.AccSynthetic; out.append("synthetic "); } if ((flags & ClassFileConstants.AccAnnotation) != 0) { flags &= ~ClassFileConstants.AccAnnotation; out.append("annotation "); } if ((flags & ClassFileConstants.AccEnum) != 0) { flags &= ~ClassFileConstants.AccEnum; out.append("enum "); } if ((flags & ClassFileConstants.AccVolatile) != 0) { flags &= ~ClassFileConstants.AccVolatile; if (node instanceof FieldDeclaration) out.append("volatile "); else out.append("volatile/bridge "); } if ((flags & ClassFileConstants.AccTransient) != 0) { flags &= ~ClassFileConstants.AccTransient; if (node instanceof Argument) out.append("varargs "); else if (node instanceof FieldDeclaration) out.append("transient "); else out.append("transient/varargs "); } if (flags != 0) { out.append(String.format(" 0x%08X ", flags)); } return out.toString().trim(); } public void visitType(EclipseNode node, TypeDeclaration type) { print("<TYPE %s%s%s> %s", str(type.name), isGenerated(type) ? " (GENERATED)" : "", position(node), printFlags(type.modifiers, type)); indent++; if (printContent) { print("%s", type); disablePrinting++; } } public void visitAnnotationOnType(TypeDeclaration type, EclipseNode node, Annotation annotation) { forcePrint("<ANNOTATION%s: %s%s />", isGenerated(annotation) ? " (GENERATED)" : "", annotation, position(node)); } public void endVisitType(EclipseNode node, TypeDeclaration type) { if (printContent) disablePrinting--; indent--; print("</TYPE %s>", str(type.name)); } public void visitInitializer(EclipseNode node, Initializer initializer) { Block block = initializer.block; boolean s = (block != null && block.statements != null); print("<%s INITIALIZER: %s%s%s>", (initializer.modifiers & Modifier.STATIC) != 0 ? "static" : "instance", s ? "filled" : "blank", isGenerated(initializer) ? " (GENERATED)" : "", position(node)); indent++; if (printContent) { if (initializer.block != null) print("%s", initializer.block); disablePrinting++; } } public void endVisitInitializer(EclipseNode node, Initializer initializer) { if (printContent) disablePrinting--; indent--; print("</%s INITIALIZER>", (initializer.modifiers & Modifier.STATIC) != 0 ? "static" : "instance"); } public void visitField(EclipseNode node, FieldDeclaration field) { print("<FIELD%s %s %s = %s%s> %s", isGenerated(field) ? " (GENERATED)" : "", str(field.type), str(field.name), field.initialization, position(node), printFlags(field.modifiers, field)); indent++; if (printContent) { if (field.initialization != null) print("%s", field.initialization); disablePrinting++; } } public void visitAnnotationOnField(FieldDeclaration field, EclipseNode node, Annotation annotation) { forcePrint("<ANNOTATION%s: %s%s />", isGenerated(annotation) ? " (GENERATED)" : "", annotation, position(node)); } public void endVisitField(EclipseNode node, FieldDeclaration field) { if (printContent) disablePrinting--; indent--; print("</FIELD %s %s>", str(field.type), str(field.name)); } public void visitMethod(EclipseNode node, AbstractMethodDeclaration method) { String type = method instanceof ConstructorDeclaration ? "CONSTRUCTOR" : "METHOD"; print("<%s %s: %s%s%s> %s", type, str(method.selector), method.statements != null ? ("filled(" + method.statements.length + ")") : "blank", isGenerated(method) ? " (GENERATED)" : "", position(node), printFlags(method.modifiers, method)); indent++; if (method instanceof ConstructorDeclaration) { ConstructorDeclaration cd = (ConstructorDeclaration) method; print("--> constructorCall: %s", cd.constructorCall == null ? "-NONE-" : cd.constructorCall); } if (printContent) { if (method.statements != null) print("%s", method); disablePrinting++; } } public void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode node, Annotation annotation) { forcePrint("<ANNOTATION%s: %s%s>", isGenerated(method) ? " (GENERATED)" : "", annotation, position(node)); if (annotation instanceof MarkerAnnotation || disablePrinting != 0) { forcePrint("<ANNOTATION%s: %s%s />", isGenerated(method) ? " (GENERATED)" : "", annotation, position(node)); } else { forcePrint("<ANNOTATION%s: %s%s>", isGenerated(method) ? " (GENERATED)" : "", annotation, position(node)); indent++; if (annotation instanceof SingleMemberAnnotation) { Expression expr = ((SingleMemberAnnotation) annotation).memberValue; print("<SINGLE-MEMBER-VALUE %s /> %s", expr.getClass(), expr); } if (annotation instanceof NormalAnnotation) { for (MemberValuePair mvp : ((NormalAnnotation) annotation).memberValuePairs) { print("<Member %s: %s /> %s", new String(mvp.name), mvp.value.getClass(), mvp.value); } } indent--; } } public void endVisitMethod(EclipseNode node, AbstractMethodDeclaration method) { if (printContent) disablePrinting--; String type = method instanceof ConstructorDeclaration ? "CONSTRUCTOR" : "METHOD"; indent--; print("</%s %s>", type, str(method.selector)); } public void visitMethodArgument(EclipseNode node, Argument arg, AbstractMethodDeclaration method) { print("<METHODARG%s %s %s = %s%s> %s", isGenerated(arg) ? " (GENERATED)" : "", str(arg.type), str(arg.name), arg.initialization, position(node), printFlags(arg.modifiers, arg)); indent++; } public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode node, Annotation annotation) { print("<ANNOTATION%s: %s%s />", isGenerated(annotation) ? " (GENERATED)" : "", annotation, position(node)); } public void endVisitMethodArgument(EclipseNode node, Argument arg, AbstractMethodDeclaration method) { indent--; print("</METHODARG %s %s>", str(arg.type), str(arg.name)); } public void visitLocal(EclipseNode node, LocalDeclaration local) { print("<LOCAL%s %s %s = %s%s> %s", isGenerated(local) ? " (GENERATED)" : "", str(local.type), str(local.name), local.initialization, position(node), printFlags(local.modifiers, local)); indent++; } public void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode node, Annotation annotation) { print("<ANNOTATION%s: %s />", isGenerated(annotation) ? " (GENERATED)" : "", annotation); } public void endVisitLocal(EclipseNode node, LocalDeclaration local) { indent--; print("</LOCAL %s %s>", str(local.type), str(local.name)); } @Override public void visitTypeUse(EclipseNode typeUseNode, TypeReference typeUse) { print("<TYPE %s>", typeUse.getClass()); indent++; print("%s", typeUse); } @Override public void visitAnnotationOnTypeUse(TypeReference typeUse, EclipseNode annotationNode, Annotation annotation) { print("<ANNOTATION%s: %s />", isGenerated(annotation) ? " (GENERATED)" : "", annotation); } @Override public void endVisitTypeUse(EclipseNode typeUseNode, TypeReference typeUse) { indent--; print("</TYPE %s>", typeUse.getClass()); } public void visitStatement(EclipseNode node, Statement statement) { print("<%s%s%s>", statement.getClass(), isGenerated(statement) ? " (GENERATED)" : "", position(node)); if (statement instanceof AllocationExpression) { AllocationExpression alloc = (AllocationExpression) statement; print(" --> arguments: %s", alloc.arguments == null ? "NULL" : alloc.arguments.length); print(" --> genericTypeArguments: %s", alloc.genericTypeArguments == null ? "NULL" : alloc.genericTypeArguments.length); print(" --> typeArguments: %s", alloc.typeArguments == null ? "NULL" : alloc.typeArguments.length); print(" --> enumConstant: %s", alloc.enumConstant); print(" --> inferredReturnType: %s", alloc.inferredReturnType); } indent++; print("%s", statement); } public void endVisitStatement(EclipseNode node, Statement statement) { indent--; print("</%s>", statement.getClass()); } String position(EclipseNode node) { if (!printPositions) return ""; int start = node.get().sourceStart(); int end = node.get().sourceEnd(); return String.format(" [%d, %d]", start, end); } public boolean isDeferUntilPostDiet() { return false; } } boolean isDeferUntilPostDiet(); }
projectlombok/lombok
src/core/lombok/eclipse/EclipseASTVisitor.java
2,150
/* * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; import java.lang.ref.Cleaner.Cleanable; import jdk.internal.ref.CleanerFactory; /** * A facility for threads to schedule tasks for future execution in a * background thread. Tasks may be scheduled for one-time execution, or for * repeated execution at regular intervals. * * <p>Corresponding to each {@code Timer} object is a single background * thread that is used to execute all of the timer's tasks, sequentially. * Timer tasks should complete quickly. If a timer task takes excessive time * to complete, it "hogs" the timer's task execution thread. This can, in * turn, delay the execution of subsequent tasks, which may "bunch up" and * execute in rapid succession when (and if) the offending task finally * completes. * * <p>After the last live reference to a {@code Timer} object goes away * <i>and</i> all outstanding tasks have completed execution, the timer's task * execution thread terminates gracefully (and becomes subject to garbage * collection). However, this can take arbitrarily long to occur. By * default, the task execution thread does not run as a <i>daemon thread</i>, * so it is capable of keeping an application from terminating. If a caller * wants to terminate a timer's task execution thread rapidly, the caller * should invoke the timer's {@code cancel} method. * * <p>If the timer's task execution thread terminates unexpectedly, for * example, because its {@code stop} method is invoked, any further * attempt to schedule a task on the timer will result in an * {@code IllegalStateException}, as if the timer's {@code cancel} * method had been invoked. * * <p>This class is thread-safe: multiple threads can share a single * {@code Timer} object without the need for external synchronization. * * <p>This class does <i>not</i> offer real-time guarantees: it schedules * tasks using the {@code Object.wait(long)} method. * * @apiNote Java 5.0 introduced the {@code java.util.concurrent} package and * one of the concurrency utilities therein is the {@link * java.util.concurrent.ScheduledThreadPoolExecutor * ScheduledThreadPoolExecutor} which is a thread pool for repeatedly * executing tasks at a given rate or delay. It is effectively a more * versatile replacement for the {@code Timer}/{@code TimerTask} * combination, as it allows multiple service threads, accepts various * time units, and doesn't require subclassing {@code TimerTask} (just * implement {@code Runnable}). Configuring {@code * ScheduledThreadPoolExecutor} with one thread makes it equivalent to * {@code Timer}. * @implNote This class scales to large numbers of concurrently * scheduled tasks (thousands should present no problem). Internally, * it uses a binary heap to represent its task queue, so the cost to schedule * a task is O(log n), where n is the number of concurrently scheduled tasks. * <p> All constructors start a timer thread. * * @author Josh Bloch * @see TimerTask * @see Object#wait(long) * @since 1.3 */ public class Timer { /** * The timer task queue. This data structure is shared with the timer * thread. The timer produces tasks, via its various schedule calls, * and the timer thread consumes, executing timer tasks as appropriate, * and removing them from the queue when they're obsolete. */ private final TaskQueue queue = new TaskQueue(); /** * The timer thread. */ private final TimerThread thread = new TimerThread(queue); /** * An object of this class is registered with a Cleaner as the cleanup * handler for this Timer object. This causes the execution thread to * exit gracefully when there are no live references to the Timer object * and no tasks in the timer queue. */ private static class ThreadReaper implements Runnable { private final TaskQueue queue; private final TimerThread thread; ThreadReaper(TaskQueue queue, TimerThread thread) { this.queue = queue; this.thread = thread; } public void run() { synchronized(queue) { thread.newTasksMayBeScheduled = false; queue.notify(); // In case queue is empty. } } } private final Cleanable cleanup; /** * This ID is used to generate thread names. */ private static final AtomicInteger nextSerialNumber = new AtomicInteger(); private static int serialNumber() { return nextSerialNumber.getAndIncrement(); } /** * Creates a new timer. The associated thread does <i>not</i> * {@linkplain Thread#setDaemon run as a daemon}. */ public Timer() { this("Timer-" + serialNumber()); } /** * Creates a new timer whose associated thread may be specified to * {@linkplain Thread#setDaemon run as a daemon}. * A daemon thread is called for if the timer will be used to * schedule repeating "maintenance activities", which must be * performed as long as the application is running, but should not * prolong the lifetime of the application. * * @param isDaemon true if the associated thread should run as a daemon. */ public Timer(boolean isDaemon) { this("Timer-" + serialNumber(), isDaemon); } /** * Creates a new timer whose associated thread has the specified name. * The associated thread does <i>not</i> * {@linkplain Thread#setDaemon run as a daemon}. * * @param name the name of the associated thread * @throws NullPointerException if {@code name} is null * @since 1.5 */ public Timer(String name) { this(name, false); } /** * Creates a new timer whose associated thread has the specified name, * and may be specified to * {@linkplain Thread#setDaemon run as a daemon}. * * @param name the name of the associated thread * @param isDaemon true if the associated thread should run as a daemon * @throws NullPointerException if {@code name} is null * @since 1.5 */ @SuppressWarnings("this-escape") public Timer(String name, boolean isDaemon) { var threadReaper = new ThreadReaper(queue, thread); this.cleanup = CleanerFactory.cleaner().register(this, threadReaper); thread.setName(name); thread.setDaemon(isDaemon); thread.start(); } /** * Schedules the specified task for execution after the specified delay. * * @param task task to be scheduled. * @param delay delay in milliseconds before task is to be executed. * @throws IllegalArgumentException if {@code delay} is negative, or * {@code delay + System.currentTimeMillis()} is negative. * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. * @throws NullPointerException if {@code task} is null */ public void schedule(TimerTask task, long delay) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); sched(task, System.currentTimeMillis()+delay, 0); } /** * Schedules the specified task for execution at the specified time. If * the time is in the past, the task is scheduled for immediate execution. * * @param task task to be scheduled. * @param time time at which task is to be executed. * @throws IllegalArgumentException if {@code time.getTime()} is negative. * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. * @throws NullPointerException if {@code task} or {@code time} is null */ public void schedule(TimerTask task, Date time) { sched(task, time.getTime(), 0); } /** * Schedules the specified task for repeated <i>fixed-delay execution</i>, * beginning after the specified delay. Subsequent executions take place * at approximately regular intervals separated by the specified period. * * <p>In fixed-delay execution, each execution is scheduled relative to * the actual execution time of the previous execution. If an execution * is delayed for any reason (such as garbage collection or other * background activity), subsequent executions will be delayed as well. * In the long run, the frequency of execution will generally be slightly * lower than the reciprocal of the specified period (assuming the system * clock underlying {@code Object.wait(long)} is accurate). * * <p>Fixed-delay execution is appropriate for recurring activities * that require "smoothness." In other words, it is appropriate for * activities where it is more important to keep the frequency accurate * in the short run than in the long run. This includes most animation * tasks, such as blinking a cursor at regular intervals. It also includes * tasks wherein regular activity is performed in response to human * input, such as automatically repeating a character as long as a key * is held down. * * @param task task to be scheduled. * @param delay delay in milliseconds before task is to be executed. * @param period time in milliseconds between successive task executions. * @throws IllegalArgumentException if {@code delay < 0}, or * {@code delay + System.currentTimeMillis() < 0}, or * {@code period <= 0} * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. * @throws NullPointerException if {@code task} is null */ public void schedule(TimerTask task, long delay, long period) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, System.currentTimeMillis()+delay, -period); } /** * Schedules the specified task for repeated <i>fixed-delay execution</i>, * beginning at the specified time. Subsequent executions take place at * approximately regular intervals, separated by the specified period. * * <p>In fixed-delay execution, each execution is scheduled relative to * the actual execution time of the previous execution. If an execution * is delayed for any reason (such as garbage collection or other * background activity), subsequent executions will be delayed as well. * In the long run, the frequency of execution will generally be slightly * lower than the reciprocal of the specified period (assuming the system * clock underlying {@code Object.wait(long)} is accurate). As a * consequence of the above, if the scheduled first time is in the past, * it is scheduled for immediate execution. * * <p>Fixed-delay execution is appropriate for recurring activities * that require "smoothness." In other words, it is appropriate for * activities where it is more important to keep the frequency accurate * in the short run than in the long run. This includes most animation * tasks, such as blinking a cursor at regular intervals. It also includes * tasks wherein regular activity is performed in response to human * input, such as automatically repeating a character as long as a key * is held down. * * @param task task to be scheduled. * @param firstTime First time at which task is to be executed. * @param period time in milliseconds between successive task executions. * @throws IllegalArgumentException if {@code firstTime.getTime() < 0}, or * {@code period <= 0} * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. * @throws NullPointerException if {@code task} or {@code firstTime} is null */ public void schedule(TimerTask task, Date firstTime, long period) { if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, firstTime.getTime(), -period); } /** * Schedules the specified task for repeated <i>fixed-rate execution</i>, * beginning after the specified delay. Subsequent executions take place * at approximately regular intervals, separated by the specified period. * * <p>In fixed-rate execution, each execution is scheduled relative to the * scheduled execution time of the initial execution. If an execution is * delayed for any reason (such as garbage collection or other background * activity), two or more executions will occur in rapid succession to * "catch up." In the long run, the frequency of execution will be * exactly the reciprocal of the specified period (assuming the system * clock underlying {@code Object.wait(long)} is accurate). * * <p>Fixed-rate execution is appropriate for recurring activities that * are sensitive to <i>absolute</i> time, such as ringing a chime every * hour on the hour, or running scheduled maintenance every day at a * particular time. It is also appropriate for recurring activities * where the total time to perform a fixed number of executions is * important, such as a countdown timer that ticks once every second for * ten seconds. Finally, fixed-rate execution is appropriate for * scheduling multiple repeating timer tasks that must remain synchronized * with respect to one another. * * @param task task to be scheduled. * @param delay delay in milliseconds before task is to be executed. * @param period time in milliseconds between successive task executions. * @throws IllegalArgumentException if {@code delay < 0}, or * {@code delay + System.currentTimeMillis() < 0}, or * {@code period <= 0} * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. * @throws NullPointerException if {@code task} is null */ public void scheduleAtFixedRate(TimerTask task, long delay, long period) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, System.currentTimeMillis()+delay, period); } /** * Schedules the specified task for repeated <i>fixed-rate execution</i>, * beginning at the specified time. Subsequent executions take place at * approximately regular intervals, separated by the specified period. * * <p>In fixed-rate execution, each execution is scheduled relative to the * scheduled execution time of the initial execution. If an execution is * delayed for any reason (such as garbage collection or other background * activity), two or more executions will occur in rapid succession to * "catch up." In the long run, the frequency of execution will be * exactly the reciprocal of the specified period (assuming the system * clock underlying {@code Object.wait(long)} is accurate). As a * consequence of the above, if the scheduled first time is in the past, * then any "missed" executions will be scheduled for immediate "catch up" * execution. * * <p>Fixed-rate execution is appropriate for recurring activities that * are sensitive to <i>absolute</i> time, such as ringing a chime every * hour on the hour, or running scheduled maintenance every day at a * particular time. It is also appropriate for recurring activities * where the total time to perform a fixed number of executions is * important, such as a countdown timer that ticks once every second for * ten seconds. Finally, fixed-rate execution is appropriate for * scheduling multiple repeating timer tasks that must remain synchronized * with respect to one another. * * @param task task to be scheduled. * @param firstTime First time at which task is to be executed. * @param period time in milliseconds between successive task executions. * @throws IllegalArgumentException if {@code firstTime.getTime() < 0} or * {@code period <= 0} * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. * @throws NullPointerException if {@code task} or {@code firstTime} is null */ public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) { if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, firstTime.getTime(), period); } /** * Schedule the specified timer task for execution at the specified * time with the specified period, in milliseconds. If period is * positive, the task is scheduled for repeated execution; if period is * zero, the task is scheduled for one-time execution. Time is specified * in Date.getTime() format. This method checks timer state, task state, * and initial execution time, but not period. * * @throws IllegalArgumentException if {@code time} is negative. * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. * @throws NullPointerException if {@code task} is null */ private void sched(TimerTask task, long time, long period) { if (time < 0) throw new IllegalArgumentException("Illegal execution time."); // Constrain value of period sufficiently to prevent numeric // overflow while still being effectively infinitely large. if (Math.abs(period) > (Long.MAX_VALUE >> 1)) period >>= 1; synchronized(queue) { if (!thread.newTasksMayBeScheduled) throw new IllegalStateException("Timer already cancelled."); synchronized(task.lock) { if (task.state != TimerTask.VIRGIN) throw new IllegalStateException( "Task already scheduled or cancelled"); task.nextExecutionTime = time; task.period = period; task.state = TimerTask.SCHEDULED; } queue.add(task); if (queue.getMin() == task) queue.notify(); } } /** * Terminates this timer, <i>discarding</i> any currently scheduled tasks. * It should be noted that this method does not <i>cancel</i> the scheduled * tasks. For a task to be considered cancelled, the task itself should * invoke {@link TimerTask#cancel()}. * * <p>This method does not interfere with a currently executing task (if it exists). * Once a timer has been terminated, its execution thread terminates * gracefully, and no more tasks may be scheduled on it. * * <p>Note that calling this method from within the run method of a * timer task that was invoked by this timer absolutely guarantees that * the ongoing task execution is the last task execution that will ever * be performed by this timer. * * <p>This method may be called repeatedly; the second and subsequent * calls have no effect. * @see TimerTask#cancel() */ public void cancel() { synchronized(queue) { queue.clear(); cleanup.clean(); } } /** * Removes all <i>cancelled</i> tasks from this timer's task queue. * <i>Calling this method has no effect on the behavior of the timer</i>, * but eliminates the references to the cancelled tasks from the queue. * If there are no external references to these tasks, they become * eligible for garbage collection. * * <p>Most programs will have no need to call this method. * It is designed for use by the rare application that cancels a large * number of tasks. Calling this method trades time for space: the * runtime of the method may be proportional to {@code n + c log n}, where * {@code n} is the number of tasks in the queue and {@code c} is the number * of cancelled tasks. * * <p>Note that it is permissible to call this method from within * a task scheduled on this timer. * * @return the number of tasks removed from the queue. * @see #cancel() * @see TimerTask#cancel() * @since 1.5 */ public int purge() { int result = 0; synchronized(queue) { for (int i = queue.size(); i > 0; i--) { if (queue.get(i).state == TimerTask.CANCELLED) { queue.quickRemove(i); result++; } } if (result != 0) queue.heapify(); } return result; } } /** * This "helper class" implements the timer's task execution thread, which * waits for tasks on the timer queue, executions them when they fire, * reschedules repeating tasks, and removes cancelled tasks and spent * non-repeating tasks from the queue. */ class TimerThread extends Thread { /** * This flag is set to false by the reaper to inform us that there * are no more live references to our Timer object. Once this flag * is true and there are no more tasks in our queue, there is no * work left for us to do, so we terminate gracefully. Note that * this field is protected by queue's monitor! */ boolean newTasksMayBeScheduled = true; /** * Our Timer's queue. We store this reference in preference to * a reference to the Timer so the reference graph remains acyclic. * Otherwise, the Timer would never be garbage-collected and this * thread would never go away. */ private TaskQueue queue; TimerThread(TaskQueue queue) { this.queue = queue; } public void run() { try { mainLoop(); } finally { // Someone killed this Thread, behave as if Timer cancelled synchronized(queue) { newTasksMayBeScheduled = false; queue.clear(); // Eliminate obsolete references } } } /** * The main timer loop. (See class comment.) */ private void mainLoop() { while (true) { try { TimerTask task; boolean taskFired; synchronized(queue) { // Wait for queue to become non-empty while (queue.isEmpty() && newTasksMayBeScheduled) queue.wait(); if (queue.isEmpty()) break; // Queue is empty and will forever remain; die // Queue nonempty; look at first evt and do the right thing long currentTime, executionTime; task = queue.getMin(); synchronized(task.lock) { if (task.state == TimerTask.CANCELLED) { queue.removeMin(); continue; // No action required, poll queue again } currentTime = System.currentTimeMillis(); executionTime = task.nextExecutionTime; if (taskFired = (executionTime<=currentTime)) { if (task.period == 0) { // Non-repeating, remove queue.removeMin(); task.state = TimerTask.EXECUTED; } else { // Repeating task, reschedule queue.rescheduleMin( task.period<0 ? currentTime - task.period : executionTime + task.period); } } } if (!taskFired) // Task hasn't yet fired; wait queue.wait(executionTime - currentTime); } if (taskFired) // Task fired; run it, holding no locks task.run(); } catch(InterruptedException e) { } } } } /** * This class represents a timer task queue: a priority queue of TimerTasks, * ordered on nextExecutionTime. Each Timer object has one of these, which it * shares with its TimerThread. Internally this class uses a heap, which * offers log(n) performance for the add, removeMin and rescheduleMin * operations, and constant time performance for the getMin operation. */ class TaskQueue { /** * Priority queue represented as a balanced binary heap: the two children * of queue[n] are queue[2*n] and queue[2*n+1]. The priority queue is * ordered on the nextExecutionTime field: The TimerTask with the lowest * nextExecutionTime is in queue[1] (assuming the queue is nonempty). For * each node n in the heap, and each descendant of n, d, * n.nextExecutionTime <= d.nextExecutionTime. */ private TimerTask[] queue = new TimerTask[128]; /** * The number of tasks in the priority queue. (The tasks are stored in * queue[1] up to queue[size]). */ private int size = 0; /** * Returns the number of tasks currently on the queue. */ int size() { return size; } /** * Adds a new task to the priority queue. */ void add(TimerTask task) { // Grow backing store if necessary if (size + 1 == queue.length) queue = Arrays.copyOf(queue, 2*queue.length); queue[++size] = task; fixUp(size); } /** * Return the "head task" of the priority queue. (The head task is an * task with the lowest nextExecutionTime.) */ TimerTask getMin() { return queue[1]; } /** * Return the ith task in the priority queue, where i ranges from 1 (the * head task, which is returned by getMin) to the number of tasks on the * queue, inclusive. */ TimerTask get(int i) { return queue[i]; } /** * Remove the head task from the priority queue. */ void removeMin() { queue[1] = queue[size]; queue[size--] = null; // Drop extra reference to prevent memory leak fixDown(1); } /** * Removes the ith element from queue without regard for maintaining * the heap invariant. Recall that queue is one-based, so * 1 <= i <= size. */ void quickRemove(int i) { assert i <= size; queue[i] = queue[size]; queue[size--] = null; // Drop extra ref to prevent memory leak } /** * Sets the nextExecutionTime associated with the head task to the * specified value, and adjusts priority queue accordingly. */ void rescheduleMin(long newTime) { queue[1].nextExecutionTime = newTime; fixDown(1); } /** * Returns true if the priority queue contains no elements. */ boolean isEmpty() { return size==0; } /** * Removes all elements from the priority queue. */ void clear() { // Null out task references to prevent memory leak for (int i=1; i<=size; i++) queue[i] = null; size = 0; } /** * Establishes the heap invariant (described above) assuming the heap * satisfies the invariant except possibly for the leaf-node indexed by k * (which may have a nextExecutionTime less than its parent's). * * This method functions by "promoting" queue[k] up the hierarchy * (by swapping it with its parent) repeatedly until queue[k]'s * nextExecutionTime is greater than or equal to that of its parent. */ private void fixUp(int k) { while (k > 1) { int j = k >> 1; if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime) break; TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; k = j; } } /** * Establishes the heap invariant (described above) in the subtree * rooted at k, which is assumed to satisfy the heap invariant except * possibly for node k itself (which may have a nextExecutionTime greater * than its children's). * * This method functions by "demoting" queue[k] down the hierarchy * (by swapping it with its smaller child) repeatedly until queue[k]'s * nextExecutionTime is less than or equal to those of its children. */ private void fixDown(int k) { int j; while ((j = k << 1) <= size && j > 0) { if (j < size && queue[j].nextExecutionTime > queue[j+1].nextExecutionTime) j++; // j indexes smallest kid if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime) break; TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; k = j; } } /** * Establishes the heap invariant (described above) in the entire tree, * assuming nothing about the order of the elements prior to the call. */ void heapify() { for (int i = size/2; i >= 1; i--) fixDown(i); } }
openjdk/jdk
src/java.base/share/classes/java/util/Timer.java
2,151
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.testFramework.common; import com.intellij.diagnostic.JVMResponsivenessMonitor; import com.intellij.diagnostic.PerformanceWatcher; import com.intellij.execution.process.ProcessIOExecutorService; import com.intellij.openapi.Disposable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.ShutDownTracker; import com.intellij.util.FlushingDaemon; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.FilePageCacheLockFree; import com.intellij.util.ui.EDT; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.ApiStatus.Internal; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; import org.jetbrains.io.NettyUtil; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.util.*; import java.util.concurrent.ForkJoinWorkerThread; import java.util.concurrent.TimeUnit; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; @TestOnly @Internal public final class ThreadLeakTracker { private ThreadLeakTracker() { } private static final MethodHandle getThreads = getThreadsMethodHandle(); public static @NotNull Map<String, Thread> getThreads() { Thread[] threads; try { // faster than Thread.getAllStackTraces().keySet() threads = (Thread[])getThreads.invokeExact(); } catch (Throwable e) { throw new RuntimeException(e); } if (threads.length == 0) { return Collections.emptyMap(); } Map<String, Thread> map = new HashMap<>(threads.length); for (Thread thread : threads) { map.put(thread.getName(), thread); } return map; } // contains prefixes of the thread names which are known to be long-running (and thus exempted from the leaking threads' detection) private static final Set<String> wellKnownOffenders; static { @SuppressWarnings({"deprecation", "SpellCheckingInspection"}) List<String> offenders = List.of( "ApplicationImpl pooled thread ", // com.intellij.util.concurrency.AppScheduledExecutorService.POOLED_THREAD_PREFIX "AWT-EventQueue-", "AWT-Shutdown", "AWT-Windows", "BatchSpanProcessor_WorkerThread", // io.opentelemetry.sdk.trace.export.BatchSpanProcessor.WORKER_THREAD_NAME "Batik CleanerThread", "BC Entropy Daemon", "Cidr Symbol Building Thread", // ForkJoinPool com.jetbrains.cidr.lang.symbols.symtable.building.OCBuildingActivityExecutionService "Cleaner-0", // Thread[Cleaner-0,8,InnocuousThreadGroup], java.lang.ref.Cleaner in android layoutlib, Java9+ "CompilerThread0", "Coroutines Debugger Cleaner", // kotlinx.coroutines.debug.internal.DebugProbesImpl.startWeakRefCleanerThread "dockerjava-netty", "External compiler", FilePageCacheLockFree.DEFAULT_HOUSEKEEPER_THREAD_NAME, "Finalizer", FlushingDaemon.NAME, "grpc-default-worker-", // grpc_netty_shaded "HttpClient-", // JRE's HttpClient thread pool is not supposed to be disposed - to reuse connections ProcessIOExecutorService.POOLED_THREAD_PREFIX, "IDEA Test Case Thread", "Image Fetcher ", "InnocuousThreadGroup", "Java2D Disposer", "JNA Cleaner", "JobScheduler FJ pool ", "JPS thread pool", JVMResponsivenessMonitor.MONITOR_THREAD_NAME, "Keep-Alive-SocketCleaner", // Thread[Keep-Alive-SocketCleaner,8,InnocuousThreadGroup], JBR-11 "Keep-Alive-Timer", "main", "Monitor Ctrl-Break", "Netty ", "ObjectCleanerThread", "OkHttp ConnectionPool", // Dockers okhttp3.internal.connection.RealConnectionPool "Okio Watchdog", // Dockers "okio.AsyncTimeout.Watchdog" "Periodic tasks thread", // com.intellij.util.concurrency.AppDelayQueue.TransferThread "process reaper", // Thread[#46,process reaper(pid7496),10,InnocuousThreadGroup] (since JDK-8279488 part of InnocuousThreadGroup) "rd throttler", // daemon thread created by com.jetbrains.rd.util.AdditionalApiKt.getTimer "Reference Handler", "RMI GC Daemon", "RMI TCP ", "Save classpath indexes for file loader", "Shared Index Hash Index Flushing Queue", "Signal Dispatcher", "tc-okhttp-stream", // Dockers "com.github.dockerjava.okhttp.UnixDomainSocket.recv" "timer-int", //serverIm, "timer-sys", //clientIm, "TimerQueue", "UserActivityMonitor thread", "VM Periodic Task Thread", "VM Thread", "YJPAgent-Telemetry" ); validateWhitelistedThreads(offenders); wellKnownOffenders = new HashSet<>(offenders); try { // init zillions of timers in e.g., MacOSXPreferencesFile Preferences.userRoot().flush(); } catch (BackingStoreException e) { throw new RuntimeException(e); } } // marks Thread with this name as long-running, which should be ignored from the thread-leaking checks public static void longRunningThreadCreated(@NotNull Disposable parentDisposable, @NotNull String @NotNull ... threadNamePrefixes) { ContainerUtil.addAll(wellKnownOffenders, threadNamePrefixes); Disposer.register(parentDisposable, () -> ContainerUtil.removeAll(wellKnownOffenders, threadNamePrefixes)); } public static void awaitQuiescence() { NettyUtil.awaitQuiescenceOfGlobalEventExecutor(100, TimeUnit.SECONDS); ShutDownTracker.getInstance().waitFor(100, TimeUnit.SECONDS); } public static void checkLeak(@NotNull Map<String, Thread> threadsBefore) throws AssertionError { // compare threads by name because BoundedTaskExecutor reuses application thread pool for different bounded pools, // leaks of which we want to find Map<String, Thread> all = getThreads(); Map<String, Thread> after = new HashMap<>(all); after.keySet().removeAll(threadsBefore.keySet()); Map<Thread, StackTraceElement[]> stackTraces = ContainerUtil.map2Map( after.values(), thread -> new Pair<>(thread, thread.getStackTrace()) ); for (Thread thread : after.values()) { waitForThread(thread, stackTraces, all, after); } } private static void waitForThread(Thread thread, Map<Thread, StackTraceElement[]> stackTraces, Map<String, Thread> all, Map<String, Thread> after) { if (!shouldWaitForThread(thread)) { return; } long start = System.currentTimeMillis(); StackTraceElement[] traceBeforeWait = thread.getStackTrace(); if (shouldIgnore(thread, traceBeforeWait)) { return; } int WAIT_SEC = 10; long deadlineMs = start + TimeUnit.SECONDS.toMillis(WAIT_SEC); StackTraceElement[] stackTrace = traceBeforeWait; while (System.currentTimeMillis() < deadlineMs) { // give a blocked thread an opportunity to die if it's stuck doing invokeAndWait() if (EDT.isCurrentThreadEdt()) { UIUtil.dispatchAllInvocationEvents(); } else { UIUtil.pump(); } // after some time, the submitted task can finish and the thread can become idle stackTrace = thread.getStackTrace(); if (shouldIgnore(thread, stackTrace)) break; } // check once more because the thread name may be set via race stackTraces.put(thread, stackTrace); if (shouldIgnore(thread, stackTrace)) { return; } all.keySet().removeAll(after.keySet()); Map<Thread, StackTraceElement[]> otherStackTraces = ContainerUtil.map2Map(all.values(), t -> Pair.create(t, t.getStackTrace())); String trace = PerformanceWatcher.printStacktrace("", thread, stackTrace); String traceBefore = PerformanceWatcher.printStacktrace("", thread, traceBeforeWait); String internalDiagnostic = internalDiagnostic(stackTrace); throw new AssertionError( "Thread leaked: " + traceBefore + (trace.equals(traceBefore) ? "" : "(its trace after " + WAIT_SEC + " seconds wait:) " + trace) + internalDiagnostic + "\n\nLeaking threads dump:\n" + dumpThreadsToString(after, stackTraces) + "\n----\nAll other threads dump:\n" + dumpThreadsToString(all, otherStackTraces) ); } private static boolean shouldWaitForThread(Thread thread) { if (thread == Thread.currentThread()) { return false; } ThreadGroup group = thread.getThreadGroup(); if (group != null && "system".equals(group.getName()) || !thread.isAlive()) { return false; } return true; } private static boolean shouldIgnore(Thread thread, StackTraceElement[] stackTrace) { if (!thread.isAlive()) return true; if (stackTrace.length == 0) return true; if (isWellKnownOffender(thread.getName())) return true; return isIdleApplicationPoolThread(stackTrace) || isIdleCommonPoolThread(thread, stackTrace) || isFutureTaskAboutToFinish(stackTrace) || isIdleDefaultCoroutineExecutorThread(thread, stackTrace) || isCoroutineSchedulerPoolThread(thread, stackTrace) || isKotlinCIOSelector(stackTrace) || isStarterTestFramework(stackTrace) || isJMXRemoteCall(stackTrace) || isBuildLogCall(stackTrace); } private static boolean isWellKnownOffender(String threadName) { for (String t : wellKnownOffenders) { if (threadName.contains(t)) { return true; } } return false; } // true, if somebody started a new thread via "executeInPooledThread()" and then the thread is waiting for the next task private static boolean isIdleApplicationPoolThread(StackTraceElement[] stackTrace) { return ContainerUtil.exists(stackTrace, element -> element.getMethodName().equals("getTask") && element.getClassName().equals("java.util.concurrent.ThreadPoolExecutor")); } private static boolean isKotlinCIOSelector(StackTraceElement[] stackTrace) { return ContainerUtil.exists(stackTrace, element -> element.getMethodName().equals("select") && element.getClassName().equals("io.ktor.network.selector.ActorSelectorManager")); } private static boolean isIdleCommonPoolThread(Thread thread, StackTraceElement[] stackTrace) { if (!ForkJoinWorkerThread.class.isAssignableFrom(thread.getClass())) { return false; } boolean insideAwaitWork = ContainerUtil.exists( stackTrace, element -> element.getMethodName().equals("awaitWork") && element.getClassName().equals("java.util.concurrent.ForkJoinPool") ); if (insideAwaitWork) return true; //java.lang.AssertionError: Thread leaked: Thread[ForkJoinPool.commonPool-worker-13,4,main] (alive) WAITING //--- its stacktrace: // at [email protected]/jdk.internal.misc.Unsafe.park(Native Method) // at [email protected]/java.util.concurrent.locks.LockSupport.park(LockSupport.java:194) // at [email protected]/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1628) // at [email protected]/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177) return stackTrace.length > 2 // can be both sun.misc.Unsafe and jdk.internal.misc.Unsafe on depending on the jdk && stackTrace[0].getClassName().endsWith(".Unsafe") && stackTrace[0].getMethodName().equals("park") && stackTrace[1].getClassName().equals("java.util.concurrent.locks.LockSupport") && stackTrace[1].getMethodName().equals("park") && stackTrace[2].getClassName().equals("java.util.concurrent.ForkJoinPool") && stackTrace[2].getMethodName().equals("runWorker"); } // in newer JDKs strange long hangups observed in Unsafe.unpark: // "Document Committing Pool" (alive) TIMED_WAITING // at sun.misc.Unsafe.unpark(Native Method) // at java.util.concurrent.locks.LockSupport.unpark(LockSupport.java:141) // at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:372) // at java.util.concurrent.FutureTask.set(FutureTask.java:233) // at java.util.concurrent.FutureTask.run(FutureTask.java:274) // at com.intellij.util.concurrency.BoundedTaskExecutor.doRun(BoundedTaskExecutor.java:207) // at com.intellij.util.concurrency.BoundedTaskExecutor.access$100(BoundedTaskExecutor.java:29) // at com.intellij.util.concurrency.BoundedTaskExecutor$1.lambda$run$0(BoundedTaskExecutor.java:185) // at com.intellij.util.concurrency.BoundedTaskExecutor$1$$Lambda$157/1473781324.run(Unknown Source) // at com.intellij.util.ConcurrencyUtil.runUnderThreadName(ConcurrencyUtil.java:208) // at com.intellij.util.concurrency.BoundedTaskExecutor$1.run(BoundedTaskExecutor.java:181) // at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) // at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) // at java.lang.Thread.run(Thread.java:748) private static boolean isFutureTaskAboutToFinish(StackTraceElement[] stackTrace) { if (stackTrace.length < 5) { return false; } return stackTrace[0].getClassName().equals("sun.misc.Unsafe") && stackTrace[0].getMethodName().equals("unpark") && stackTrace[2].getClassName().equals("java.util.concurrent.FutureTask") && stackTrace[2].getMethodName().equals("finishCompletion"); } /** * at sun.misc.Unsafe.park(Native Method) * at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215) * at kotlinx.coroutines.DefaultExecutor.run(DefaultExecutor.kt:83) * at java.lang.Thread.run(Thread.java:748) */ private static boolean isIdleDefaultCoroutineExecutorThread(Thread thread, StackTraceElement[] stackTrace) { if (stackTrace.length != 4) { return false; } return "kotlinx.coroutines.DefaultExecutor".equals(thread.getName()) && (stackTrace[0].getClassName().equals("sun.misc.Unsafe") || stackTrace[0].getClassName().equals("jdk.internal.misc.Unsafe")) && stackTrace[0].getMethodName().equals("park") && stackTrace[2].getClassName().equals("kotlinx.coroutines.DefaultExecutor") && stackTrace[2].getMethodName().equals("run"); } private static boolean isCoroutineSchedulerPoolThread(Thread thread, StackTraceElement[] stackTrace) { if (!"kotlinx.coroutines.scheduling.CoroutineScheduler$Worker".equals(thread.getClass().getName())) { return false; } //noinspection UnnecessaryLocalVariable boolean insideCpuWorkerIdle = ContainerUtil.exists( stackTrace, element -> element.getMethodName().equals("park") && element.getClassName().equals("kotlinx.coroutines.scheduling.CoroutineScheduler$Worker") ); return insideCpuWorkerIdle; } /** * Starter framework [intellij.ide.starter] / [intellij.ide.starter.extended] registers its own JUnit listeners. * A listener's order of execution isn't defined, so when the thread leak detector detects a leak, * the listener from starter might not have a chance to clean up after tests. */ private static boolean isStarterTestFramework(StackTraceElement[] stackTrace) { // java.lang.AssertionError: Thread leaked: Thread[Redirect stderr,5,main] (alive) RUNNABLE //--- its stacktrace: // ... // at app//com.intellij.ide.starter.process.exec.ProcessExecutor$redirectProcessOutput$1.invoke(ProcessExecutor.kt:40) // at app//kotlin.concurrent.ThreadsKt$thread$thread$1.run(Thread.kt:30) return ContainerUtil.exists( stackTrace, element -> element.getClassName().contains("com.intellij.ide.starter") ); } /** * {@code com.intellij.driver.client.*} is using JMX. That might lead to long-living tasks. */ private static boolean isJMXRemoteCall(StackTraceElement[] stackTrace) { // Thread leaked: Thread[JMX client heartbeat 3,5,main] (alive) TIMED_WAITING // --- its stacktrace: // at [email protected]/java.lang.Thread.sleep(Native Method) // at [email protected]/com.sun.jmx.remote.internal.ClientCommunicatorAdmin$Checker.run(ClientCommunicatorAdmin.java:180) // at [email protected]/java.lang.Thread.run(Thread.java:840) return ContainerUtil.exists(stackTrace, element -> element.getClassName().contains("com.sun.jmx.remote")); } /** * <a href="https://youtrack.jetbrains.com/issue/IDEA-349419/Flaky-thread-leak-in-ConsoleSpanExporter">IDEA-349419</a> */ private static boolean isBuildLogCall(StackTraceElement[] stackTrace) { //java.lang.AssertionError: Thread leaked: Thread[#204,DefaultDispatcher-worker-6,5,main] (alive) RUNNABLE // --- its stacktrace: //at java.base/java.io.FileOutputStream.writeBytes(Native Method) //at org.jetbrains.intellij.build.ConsoleSpanExporter.export(ConsoleSpanExporter.kt:44) //at com.intellij.platform.diagnostic.telemetry.exporters.BatchSpanProcessor$exportCurrentBatch$2.invokeSuspend(BatchSpanProcessor.kt:155) return ContainerUtil.exists(stackTrace, element -> element.getClassName().contains("org.jetbrains.intellij.build.ConsoleSpanExporter")); } private static CharSequence dumpThreadsToString(Map<String, Thread> after, Map<Thread, StackTraceElement[]> stackTraces) { StringBuilder f = new StringBuilder(); for (Map.Entry<String, Thread> entry : after.entrySet()) { Thread t = entry.getValue(); f.append('"').append(entry.getKey()).append("\" (").append(t.isAlive() ? "alive" : "dead").append(") ").append(t.getState()) .append('\n'); for (StackTraceElement element : stackTraces.get(t)) { f.append("\tat ").append(element).append('\n'); } f.append('\n'); } return f; } private static String internalDiagnostic(StackTraceElement[] stackTrace) { return stackTrace.length < 5 ? "stackTrace.length: " + stackTrace.length : "(diagnostic: " + "0: " + stackTrace[0].getClassName() + " : " + stackTrace[0].getClassName().equals("sun.misc.Unsafe") + " . " + stackTrace[0].getMethodName() + " : " + stackTrace[0].getMethodName().equals("unpark") + " 2: " + stackTrace[2].getClassName() + " : " + stackTrace[2].getClassName().equals("java.util.concurrent.FutureTask") + " . " + stackTrace[2].getMethodName() + " : " + stackTrace[2].getMethodName().equals("finishCompletion") + ")"; } private static MethodHandle getThreadsMethodHandle() { try { return MethodHandles.privateLookupIn(Thread.class, MethodHandles.lookup()) .findStatic(Thread.class, "getThreads", MethodType.methodType(Thread[].class)); } catch (Throwable e) { throw new IllegalStateException("Unable to access the Thread#getThreads method", e); } } private static void validateWhitelistedThreads(List<String> offenders) { List<String> sorted = new ArrayList<>(offenders); sorted.sort(String::compareToIgnoreCase); if (offenders.equals(sorted)) { return; } @SuppressWarnings("deprecation") String proper = String .join(",\n", ContainerUtil.map(sorted, s -> '"' + s + '"')) .replaceAll('"' + FlushingDaemon.NAME + '"', "FlushingDaemon.NAME") .replaceAll('"' + ProcessIOExecutorService.POOLED_THREAD_PREFIX + '"', "ProcessIOExecutorService.POOLED_THREAD_PREFIX"); throw new AssertionError("Thread names must be sorted (for ease of maintenance). Something like this will do:\n" + proper); } }
JetBrains/intellij-community
platform/testFramework/common/src/common/ThreadLeakTracker.java
2,152
/* * Copyright (c) 1998, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.awt; import java.awt.EventQueue; import java.awt.Window; import java.awt.SystemTray; import java.awt.TrayIcon; import java.awt.Toolkit; import java.awt.GraphicsEnvironment; import java.awt.event.InvocationEvent; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; import java.util.Set; import java.util.HashSet; import java.beans.PropertyChangeSupport; import java.beans.PropertyChangeListener; import java.lang.ref.SoftReference; import jdk.internal.access.JavaAWTAccess; import jdk.internal.access.SharedSecrets; import sun.util.logging.PlatformLogger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; /** * The AppContext is a table referenced by ThreadGroup which stores * application service instances. (If you are not writing an application * service, or don't know what one is, please do not use this class.) * The AppContext allows applet access to what would otherwise be * potentially dangerous services, such as the ability to peek at * EventQueues or change the look-and-feel of a Swing application.<p> * * Most application services use a singleton object to provide their * services, either as a default (such as getSystemEventQueue or * getDefaultToolkit) or as static methods with class data (System). * The AppContext works with the former method by extending the concept * of "default" to be ThreadGroup-specific. Application services * lookup their singleton in the AppContext.<p> * * For example, here we have a Foo service, with its pre-AppContext * code:<p> * <pre>{@code * public class Foo { * private static Foo defaultFoo = new Foo(); * * public static Foo getDefaultFoo() { * return defaultFoo; * } * * ... Foo service methods * } * }</pre><p> * * The problem with the above is that the Foo service is global in scope, * so that applets and other untrusted code can execute methods on the * single, shared Foo instance. The Foo service therefore either needs * to block its use by untrusted code using a SecurityManager test, or * restrict its capabilities so that it doesn't matter if untrusted code * executes it.<p> * * Here's the Foo class written to use the AppContext:<p> * <pre>{@code * public class Foo { * public static Foo getDefaultFoo() { * Foo foo = (Foo)AppContext.getAppContext().get(Foo.class); * if (foo == null) { * foo = new Foo(); * getAppContext().put(Foo.class, foo); * } * return foo; * } * * ... Foo service methods * } * }</pre><p> * * Since a separate AppContext can exist for each ThreadGroup, trusted * and untrusted code have access to different Foo instances. This allows * untrusted code access to "system-wide" services -- the service remains * within the AppContext "sandbox". For example, say a malicious applet * wants to peek all of the key events on the EventQueue to listen for * passwords; if separate EventQueues are used for each ThreadGroup * using AppContexts, the only key events that applet will be able to * listen to are its own. A more reasonable applet request would be to * change the Swing default look-and-feel; with that default stored in * an AppContext, the applet's look-and-feel will change without * disrupting other applets or potentially the browser itself.<p> * * Because the AppContext is a facility for safely extending application * service support to applets, none of its methods may be blocked by a * a SecurityManager check in a valid Java implementation. Applets may * therefore safely invoke any of its methods without worry of being * blocked. * * @author Thomas Ball * @author Fred Ecks */ public final class AppContext { private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.AppContext"); /* Since the contents of an AppContext are unique to each Java * session, this class should never be serialized. */ /* * The key to put()/get() the Java EventQueue into/from the AppContext. */ public static final Object EVENT_QUEUE_KEY = new StringBuffer("EventQueue"); /* * The keys to store EventQueue push/pop lock and condition. */ public static final Object EVENT_QUEUE_LOCK_KEY = new StringBuilder("EventQueue.Lock"); public static final Object EVENT_QUEUE_COND_KEY = new StringBuilder("EventQueue.Condition"); /* A map of AppContexts, referenced by ThreadGroup. */ private static final Map<ThreadGroup, AppContext> threadGroup2appContext = Collections.synchronizedMap(new IdentityHashMap<ThreadGroup, AppContext>()); /** * Returns a set containing all {@code AppContext}s. */ public static Set<AppContext> getAppContexts() { synchronized (threadGroup2appContext) { return new HashSet<AppContext>(threadGroup2appContext.values()); } } /* The main "system" AppContext, used by everything not otherwise contained in another AppContext. It is implicitly created for standalone apps only (i.e. not applets) */ private static volatile AppContext mainAppContext; private static class GetAppContextLock {} private static final Object getAppContextLock = new GetAppContextLock(); /* * The hash map associated with this AppContext. A private delegate * is used instead of subclassing HashMap so as to avoid all of * HashMap's potentially risky methods, such as clear(), elements(), * putAll(), etc. */ private final Map<Object, Object> table = new HashMap<>(); private final ThreadGroup threadGroup; /** * If any {@code PropertyChangeListeners} have been registered, * the {@code changeSupport} field describes them. * * @see #addPropertyChangeListener * @see #removePropertyChangeListener * @see PropertyChangeSupport#firePropertyChange */ private PropertyChangeSupport changeSupport = null; public static final String DISPOSED_PROPERTY_NAME = "disposed"; public static final String GUI_DISPOSED = "guidisposed"; private enum State { VALID, BEING_DISPOSED, DISPOSED } private volatile State state = State.VALID; public boolean isDisposed() { return state == State.DISPOSED; } /* * The total number of AppContexts, system-wide. This number is * incremented at the beginning of the constructor, and decremented * at the end of dispose(). getAppContext() checks to see if this * number is 1. If so, it returns the sole AppContext without * checking Thread.currentThread(). */ private static final AtomicInteger numAppContexts = new AtomicInteger(); /* * The context ClassLoader that was used to create this AppContext. */ private final ClassLoader contextClassLoader; /** * Constructor for AppContext. This method is <i>not</i> public, * nor should it ever be used as such. The proper way to construct * an AppContext is through the use of SunToolkit.createNewAppContext. * A ThreadGroup is created for the new AppContext, a Thread is * created within that ThreadGroup, and that Thread calls * SunToolkit.createNewAppContext before calling anything else. * That creates both the new AppContext and its EventQueue. * * @param threadGroup The ThreadGroup for the new AppContext * @see sun.awt.SunToolkit * @since 1.2 */ @SuppressWarnings("removal") AppContext(ThreadGroup threadGroup) { numAppContexts.incrementAndGet(); this.threadGroup = threadGroup; threadGroup2appContext.put(threadGroup, this); this.contextClassLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }); // Initialize push/pop lock and its condition to be used by all the // EventQueues within this AppContext Lock eventQueuePushPopLock = new ReentrantLock(); put(EVENT_QUEUE_LOCK_KEY, eventQueuePushPopLock); Condition eventQueuePushPopCond = eventQueuePushPopLock.newCondition(); put(EVENT_QUEUE_COND_KEY, eventQueuePushPopCond); } private static final ThreadLocal<AppContext> threadAppContext = new ThreadLocal<AppContext>(); @SuppressWarnings("removal") private static void initMainAppContext() { // On the main Thread, we get the ThreadGroup, make a corresponding // AppContext, and instantiate the Java EventQueue. This way, legacy // code is unaffected by the move to multiple AppContext ability. AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup(); ThreadGroup parentThreadGroup = currentThreadGroup.getParent(); while (parentThreadGroup != null) { // Find the root ThreadGroup to construct our main AppContext currentThreadGroup = parentThreadGroup; parentThreadGroup = currentThreadGroup.getParent(); } mainAppContext = SunToolkit.createNewAppContext(currentThreadGroup); return null; } }); } /** * Returns the appropriate AppContext for the caller, * as determined by its ThreadGroup. * * @return the AppContext for the caller. * @see java.lang.ThreadGroup * @since 1.2 */ @SuppressWarnings("removal") public static AppContext getAppContext() { // we are standalone app, return the main app context if (numAppContexts.get() == 1 && mainAppContext != null) { return mainAppContext; } AppContext appContext = threadAppContext.get(); if (null == appContext) { appContext = AccessController.doPrivileged(new PrivilegedAction<AppContext>() { public AppContext run() { // Get the current ThreadGroup, and look for it and its // parents in the hash from ThreadGroup to AppContext -- // it should be found, because we use createNewContext() // when new AppContext objects are created. ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup(); ThreadGroup threadGroup = currentThreadGroup; // Special case: we implicitly create the main app context // if no contexts have been created yet. This covers standalone apps // and excludes applets because by the time applet starts // a number of contexts have already been created by the plugin. synchronized (getAppContextLock) { if (numAppContexts.get() == 0) { if (System.getProperty("javaplugin.version") == null && System.getProperty("javawebstart.version") == null) { initMainAppContext(); } else if (System.getProperty("javafx.version") != null && threadGroup.getParent() != null) { // Swing inside JavaFX case SunToolkit.createNewAppContext(); } } } AppContext context = threadGroup2appContext.get(threadGroup); while (context == null) { threadGroup = threadGroup.getParent(); if (threadGroup == null) { // We've got up to the root thread group and did not find an AppContext // Try to get it from the security manager SecurityManager securityManager = System.getSecurityManager(); if (securityManager != null) { ThreadGroup smThreadGroup = securityManager.getThreadGroup(); if (smThreadGroup != null) { /* * If we get this far then it's likely that * the ThreadGroup does not actually belong * to the applet, so do not cache it. */ return threadGroup2appContext.get(smThreadGroup); } } return null; } context = threadGroup2appContext.get(threadGroup); } // In case we did anything in the above while loop, we add // all the intermediate ThreadGroups to threadGroup2appContext // so we won't spin again. for (ThreadGroup tg = currentThreadGroup; tg != threadGroup; tg = tg.getParent()) { threadGroup2appContext.put(tg, context); } // Now we're done, so we cache the latest key/value pair. threadAppContext.set(context); return context; } }); } return appContext; } /** * Returns true if the specified AppContext is the main AppContext. * * @param ctx the context to compare with the main context * @return true if the specified AppContext is the main AppContext. * @since 1.8 */ public static boolean isMainContext(AppContext ctx) { return (ctx != null && ctx == mainAppContext); } private long DISPOSAL_TIMEOUT = 5000; // Default to 5-second timeout // for disposal of all Frames // (we wait for this time twice, // once for dispose(), and once // to clear the EventQueue). private long THREAD_INTERRUPT_TIMEOUT = 1000; // Default to 1-second timeout for all // interrupted Threads to exit, and another // 1 second for all stopped Threads to die. /** * Disposes of this AppContext, all of its top-level Frames, and * all Threads and ThreadGroups contained within it. * * This method must be called from a Thread which is not contained * within this AppContext. * * @throws IllegalThreadStateException if the current thread is * contained within this AppContext * @since 1.2 */ @SuppressWarnings({"deprecation", "removal"}) public void dispose() throws IllegalThreadStateException { System.err.println( """ WARNING: sun.awt.AppContext.dispose() no longer stops threads. Additionally AppContext will be removed in a future release. Remove all uses of this internal class as soon as possible. There is no replacement. """); // Check to be sure that the current Thread isn't in this AppContext if (this.threadGroup.parentOf(Thread.currentThread().getThreadGroup())) { throw new IllegalThreadStateException( "Current Thread is contained within AppContext to be disposed." ); } synchronized(this) { if (this.state != State.VALID) { return; // If already disposed or being disposed, bail. } this.state = State.BEING_DISPOSED; } final PropertyChangeSupport changeSupport = this.changeSupport; if (changeSupport != null) { changeSupport.firePropertyChange(DISPOSED_PROPERTY_NAME, false, true); } // First, we post an InvocationEvent to be run on the // EventDispatchThread which disposes of all top-level Frames and TrayIcons final Object notificationLock = new Object(); Runnable runnable = new Runnable() { public void run() { Window[] windowsToDispose = Window.getOwnerlessWindows(); for (Window w : windowsToDispose) { try { w.dispose(); } catch (Throwable t) { log.finer("exception occurred while disposing app context", t); } } AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { if (!GraphicsEnvironment.isHeadless() && SystemTray.isSupported()) { SystemTray systemTray = SystemTray.getSystemTray(); TrayIcon[] trayIconsToDispose = systemTray.getTrayIcons(); for (TrayIcon ti : trayIconsToDispose) { systemTray.remove(ti); } } return null; } }); // Alert PropertyChangeListeners that the GUI has been disposed. if (changeSupport != null) { changeSupport.firePropertyChange(GUI_DISPOSED, false, true); } synchronized(notificationLock) { notificationLock.notifyAll(); // Notify caller that we're done } } }; synchronized(notificationLock) { SunToolkit.postEvent(this, new InvocationEvent(Toolkit.getDefaultToolkit(), runnable)); try { notificationLock.wait(DISPOSAL_TIMEOUT); } catch (InterruptedException e) { } } // Next, we post another InvocationEvent to the end of the // EventQueue. When it's executed, we know we've executed all // events in the queue. runnable = new Runnable() { public void run() { synchronized(notificationLock) { notificationLock.notifyAll(); // Notify caller that we're done } } }; synchronized(notificationLock) { SunToolkit.postEvent(this, new InvocationEvent(Toolkit.getDefaultToolkit(), runnable)); try { notificationLock.wait(DISPOSAL_TIMEOUT); } catch (InterruptedException e) { } } // We are done with posting events, so change the state to disposed synchronized(this) { this.state = State.DISPOSED; } // Next, we interrupt all Threads in the ThreadGroup this.threadGroup.interrupt(); // Note, the EventDispatchThread we've interrupted may dump an // InterruptedException to the console here. This needs to be // fixed in the EventDispatchThread, not here. // Next, we sleep 10ms at a time, waiting for all of the active // Threads in the ThreadGroup to exit. long startTime = System.currentTimeMillis(); long endTime = startTime + THREAD_INTERRUPT_TIMEOUT; while ((this.threadGroup.activeCount() > 0) && (System.currentTimeMillis() < endTime)) { try { Thread.sleep(10); } catch (InterruptedException e) { } } // Next, we remove this and all subThreadGroups from threadGroup2appContext int numSubGroups = this.threadGroup.activeGroupCount(); if (numSubGroups > 0) { ThreadGroup [] subGroups = new ThreadGroup[numSubGroups]; numSubGroups = this.threadGroup.enumerate(subGroups); for (int subGroup = 0; subGroup < numSubGroups; subGroup++) { threadGroup2appContext.remove(subGroups[subGroup]); } } threadGroup2appContext.remove(this.threadGroup); threadAppContext.set(null); synchronized (table) { this.table.clear(); // Clear out the Hashtable to ease garbage collection } numAppContexts.decrementAndGet(); mostRecentKeyValue = null; } static final class PostShutdownEventRunnable implements Runnable { private final AppContext appContext; PostShutdownEventRunnable(AppContext ac) { appContext = ac; } public void run() { final EventQueue eq = (EventQueue)appContext.get(EVENT_QUEUE_KEY); if (eq != null) { eq.postEvent(AWTAutoShutdown.getShutdownEvent()); } } } static final class CreateThreadAction implements PrivilegedAction<Thread> { private final AppContext appContext; private final Runnable runnable; CreateThreadAction(AppContext ac, Runnable r) { appContext = ac; runnable = r; } public Thread run() { Thread t = new Thread(appContext.getThreadGroup(), runnable, "AppContext Disposer", 0, false); t.setContextClassLoader(appContext.getContextClassLoader()); t.setPriority(Thread.NORM_PRIORITY + 1); t.setDaemon(true); return t; } } static void stopEventDispatchThreads() { for (AppContext appContext: getAppContexts()) { if (appContext.isDisposed()) { continue; } Runnable r = new PostShutdownEventRunnable(appContext); // For security reasons EventQueue.postEvent should only be called // on a thread that belongs to the corresponding thread group. if (appContext != AppContext.getAppContext()) { // Create a thread that belongs to the thread group associated // with the AppContext and invokes EventQueue.postEvent. PrivilegedAction<Thread> action = new CreateThreadAction(appContext, r); @SuppressWarnings("removal") Thread thread = AccessController.doPrivileged(action); thread.start(); } else { r.run(); } } } private MostRecentKeyValue mostRecentKeyValue = null; private MostRecentKeyValue shadowMostRecentKeyValue = null; /** * Returns the value to which the specified key is mapped in this context. * * @param key a key in the AppContext. * @return the value to which the key is mapped in this AppContext; * {@code null} if the key is not mapped to any value. * @see #put(Object, Object) * @since 1.2 */ public Object get(Object key) { /* * The most recent reference should be updated inside a synchronized * block to avoid a race when put() and get() are executed in * parallel on different threads. */ synchronized (table) { // Note: this most recent key/value caching is thread-hot. // A simple test using SwingSet found that 72% of lookups // were matched using the most recent key/value. By instantiating // a simple MostRecentKeyValue object on cache misses, the // cache hits can be processed without synchronization. MostRecentKeyValue recent = mostRecentKeyValue; if ((recent != null) && (recent.key == key)) { return recent.value; } Object value = table.get(key); if(mostRecentKeyValue == null) { mostRecentKeyValue = new MostRecentKeyValue(key, value); shadowMostRecentKeyValue = new MostRecentKeyValue(key, value); } else { MostRecentKeyValue auxKeyValue = mostRecentKeyValue; shadowMostRecentKeyValue.setPair(key, value); mostRecentKeyValue = shadowMostRecentKeyValue; shadowMostRecentKeyValue = auxKeyValue; } return value; } } /** * Maps the specified {@code key} to the specified * {@code value} in this AppContext. Neither the key nor the * value can be {@code null}. * <p> * The value can be retrieved by calling the {@code get} method * with a key that is equal to the original key. * * @param key the AppContext key. * @param value the value. * @return the previous value of the specified key in this * AppContext, or {@code null} if it did not have one. * @throws NullPointerException if the key or value is * {@code null}. * @see #get(Object) * @since 1.2 */ public Object put(Object key, Object value) { synchronized (table) { MostRecentKeyValue recent = mostRecentKeyValue; if ((recent != null) && (recent.key == key)) recent.value = value; return table.put(key, value); } } /** * Removes the key (and its corresponding value) from this * AppContext. This method does nothing if the key is not in the * AppContext. * * @param key the key that needs to be removed. * @return the value to which the key had been mapped in this AppContext, * or {@code null} if the key did not have a mapping. * @since 1.2 */ public Object remove(Object key) { synchronized (table) { MostRecentKeyValue recent = mostRecentKeyValue; if ((recent != null) && (recent.key == key)) recent.value = null; return table.remove(key); } } /** * Returns the root ThreadGroup for all Threads contained within * this AppContext. * @since 1.2 */ public ThreadGroup getThreadGroup() { return threadGroup; } /** * Returns the context ClassLoader that was used to create this * AppContext. * * @see java.lang.Thread#getContextClassLoader */ public ClassLoader getContextClassLoader() { return contextClassLoader; } /** * Returns a string representation of this AppContext. * @since 1.2 */ @Override public String toString() { return getClass().getName() + "[threadGroup=" + threadGroup.getName() + "]"; } /** * Returns an array of all the property change listeners * registered on this component. * * @return all of this component's {@code PropertyChangeListener}s * or an empty array if no property change * listeners are currently registered * * @see #addPropertyChangeListener * @see #removePropertyChangeListener * @see #getPropertyChangeListeners(java.lang.String) * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners * @since 1.4 */ public synchronized PropertyChangeListener[] getPropertyChangeListeners() { if (changeSupport == null) { return new PropertyChangeListener[0]; } return changeSupport.getPropertyChangeListeners(); } /** * Adds a PropertyChangeListener to the listener list for a specific * property. The specified property may be one of the following: * <ul> * <li>if this AppContext is disposed ("disposed")</li> * </ul> * <ul> * <li>if this AppContext's unowned Windows have been disposed * ("guidisposed"). Code to cleanup after the GUI is disposed * (such as LookAndFeel.uninitialize()) should execute in response to * this property being fired. Notifications for the "guidisposed" * property are sent on the event dispatch thread.</li> * </ul> * <p> * If listener is null, no exception is thrown and no action is performed. * * @param propertyName one of the property names listed above * @param listener the PropertyChangeListener to be added * * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) * @see #getPropertyChangeListeners(java.lang.String) * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) */ public synchronized void addPropertyChangeListener( String propertyName, PropertyChangeListener listener) { if (listener == null) { return; } if (changeSupport == null) { changeSupport = new PropertyChangeSupport(this); } changeSupport.addPropertyChangeListener(propertyName, listener); } /** * Removes a PropertyChangeListener from the listener list for a specific * property. This method should be used to remove PropertyChangeListeners * that were registered for a specific bound property. * <p> * If listener is null, no exception is thrown and no action is performed. * * @param propertyName a valid property name * @param listener the PropertyChangeListener to be removed * * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) * @see #getPropertyChangeListeners(java.lang.String) * @see PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener) */ public synchronized void removePropertyChangeListener( String propertyName, PropertyChangeListener listener) { if (listener == null || changeSupport == null) { return; } changeSupport.removePropertyChangeListener(propertyName, listener); } /** * Returns an array of all the listeners which have been associated * with the named property. * * @return all of the {@code PropertyChangeListeners} associated with * the named property or an empty array if no listeners have * been added * * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) * @see #getPropertyChangeListeners * @since 1.4 */ public synchronized PropertyChangeListener[] getPropertyChangeListeners( String propertyName) { if (changeSupport == null) { return new PropertyChangeListener[0]; } return changeSupport.getPropertyChangeListeners(propertyName); } // Set up JavaAWTAccess in SharedSecrets static { SharedSecrets.setJavaAWTAccess(new JavaAWTAccess() { @SuppressWarnings("removal") private boolean hasRootThreadGroup(final AppContext ecx) { return AccessController.doPrivileged(new PrivilegedAction<Boolean>() { @Override public Boolean run() { return ecx.threadGroup.getParent() == null; } }); } /** * Returns the AppContext used for applet logging isolation, or null if * the default global context can be used. * If there's no applet, or if the caller is a stand alone application, * or running in the main app context, returns null. * Otherwise, returns the AppContext of the calling applet. * @return null if the global default context can be used, * an AppContext otherwise. **/ public Object getAppletContext() { // There's no AppContext: return null. // No need to call getAppContext() if numAppContext == 0: // it means that no AppContext has been created yet, and // we don't want to trigger the creation of a main app // context since we don't need it. if (numAppContexts.get() == 0) return null; AppContext ecx = null; // Not sure we really need to re-check numAppContexts here. // If all applets have gone away then we could have a // numAppContexts coming back to 0. So we recheck // it here because we don't want to trigger the // creation of a main AppContext in that case. // This is probably not 100% MT-safe but should reduce // the window of opportunity in which that issue could // happen. if (numAppContexts.get() > 0) { // Defaults to thread group caching. // This is probably not required as we only really need // isolation in a deployed applet environment, in which // case ecx will not be null when we reach here // However it helps emulate the deployed environment, // in tests for instance. ecx = ecx != null ? ecx : getAppContext(); } // getAppletContext() may be called when initializing the main // app context - in which case mainAppContext will still be // null. To work around this issue we simply use // AppContext.threadGroup.getParent() == null instead, since // mainAppContext is the only AppContext which should have // the root TG as its thread group. // See: JDK-8023258 final boolean isMainAppContext = ecx == null || mainAppContext == ecx || mainAppContext == null && hasRootThreadGroup(ecx); return isMainAppContext ? null : ecx; } }); } public static <T> T getSoftReferenceValue(Object key, Supplier<T> supplier) { final AppContext appContext = AppContext.getAppContext(); @SuppressWarnings("unchecked") SoftReference<T> ref = (SoftReference<T>) appContext.get(key); if (ref != null) { final T object = ref.get(); if (object != null) { return object; } } final T object = supplier.get(); ref = new SoftReference<>(object); appContext.put(key, ref); return object; } } final class MostRecentKeyValue { Object key; Object value; MostRecentKeyValue(Object k, Object v) { key = k; value = v; } void setPair(Object k, Object v) { key = k; value = v; } }
openjdk/jdk
src/java.desktop/share/classes/sun/awt/AppContext.java
2,153
/* * Copyright 2002-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.transaction.jta; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.List; import java.util.Properties; import javax.naming.NamingException; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.InvalidTransactionException; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.Status; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import jakarta.transaction.TransactionSynchronizationRegistry; import jakarta.transaction.UserTransaction; import org.springframework.beans.factory.InitializingBean; import org.springframework.jndi.JndiTemplate; import org.springframework.lang.Nullable; import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.HeuristicCompletionException; import org.springframework.transaction.IllegalTransactionStateException; import org.springframework.transaction.InvalidIsolationLevelException; import org.springframework.transaction.NestedTransactionNotSupportedException; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionSuspensionNotSupportedException; import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.UnexpectedRollbackException; import org.springframework.transaction.support.AbstractPlatformTransactionManager; import org.springframework.transaction.support.DefaultTransactionStatus; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * {@link org.springframework.transaction.PlatformTransactionManager} implementation * for JTA, delegating to a backend JTA provider. This is typically used to delegate * to a Jakarta EE server's transaction coordinator, but may also be configured with a * local JTA provider which is embedded within the application. * * <p>This transaction manager is appropriate for handling distributed transactions, * i.e. transactions that span multiple resources, and for controlling transactions on * application server resources (e.g. JDBC DataSources available in JNDI) in general. * For a single JDBC DataSource, DataSourceTransactionManager is perfectly sufficient, * and for accessing a single resource with Hibernate (including transactional cache), * HibernateTransactionManager is appropriate, for example. * * <p><b>For typical JTA transactions (REQUIRED, SUPPORTS, MANDATORY, NEVER), a plain * JtaTransactionManager definition is all you need, portable across all Jakarta EE servers.</b> * This corresponds to the functionality of the JTA UserTransaction, for which Jakarta EE * specifies a standard JNDI name ("java:comp/UserTransaction"). There is no need to * configure a server-specific TransactionManager lookup for this kind of JTA usage. * * <p><b>Transaction suspension (REQUIRES_NEW, NOT_SUPPORTED) is just available with a * JTA TransactionManager being registered.</b> Common TransactionManager locations are * autodetected by JtaTransactionManager, provided that the "autodetectTransactionManager" * flag is set to "true" (which it is by default). * * <p>Note: Support for the JTA TransactionManager interface is not required by Jakarta EE. * Almost all Jakarta EE servers expose it, but do so as extension to EE. There might be some * issues with compatibility, despite the TransactionManager interface being part of JTA. * * <p>This pure JtaTransactionManager class supports timeouts but not per-transaction * isolation levels. Custom subclasses may override the {@link #doJtaBegin} method for * specific JTA extensions in order to provide this functionality. Such adapters for * specific Jakarta EE transaction coordinators may also expose transaction names for * monitoring; with standard JTA, transaction names will simply be ignored. * * <p>JTA 1.1 adds the TransactionSynchronizationRegistry facility, as public Jakarta EE * API in addition to the standard JTA UserTransaction handle. As of Spring 2.5, this * JtaTransactionManager autodetects the TransactionSynchronizationRegistry and uses * it for registering Spring-managed synchronizations when participating in an existing * JTA transaction (e.g. controlled by EJB CMT). If no TransactionSynchronizationRegistry * is available, then such synchronizations will be registered via the (non-EE) JTA * TransactionManager handle. * * <p>This class is serializable. However, active synchronizations do not survive serialization. * * @author Juergen Hoeller * @since 24.03.2003 * @see jakarta.transaction.UserTransaction * @see jakarta.transaction.TransactionManager * @see jakarta.transaction.TransactionSynchronizationRegistry * @see #setUserTransactionName * @see #setUserTransaction * @see #setTransactionManagerName * @see #setTransactionManager */ @SuppressWarnings("serial") public class JtaTransactionManager extends AbstractPlatformTransactionManager implements TransactionFactory, InitializingBean, Serializable { /** * Default JNDI location for the JTA UserTransaction. Many Jakarta EE servers * also provide support for the JTA TransactionManager interface there. * @see #setUserTransactionName * @see #setAutodetectTransactionManager */ public static final String DEFAULT_USER_TRANSACTION_NAME = "java:comp/UserTransaction"; /** * Fallback JNDI locations for the JTA TransactionManager. Applied if * the JTA UserTransaction does not implement the JTA TransactionManager * interface, provided that the "autodetectTransactionManager" flag is "true". * @see #setTransactionManagerName * @see #setAutodetectTransactionManager */ public static final String[] FALLBACK_TRANSACTION_MANAGER_NAMES = new String[] {"java:comp/TransactionManager", "java:appserver/TransactionManager", "java:pm/TransactionManager", "java:/TransactionManager"}; /** * Standard Jakarta EE JNDI location for the JTA TransactionSynchronizationRegistry. * Autodetected when available. */ public static final String DEFAULT_TRANSACTION_SYNCHRONIZATION_REGISTRY_NAME = "java:comp/TransactionSynchronizationRegistry"; private transient JndiTemplate jndiTemplate = new JndiTemplate(); @Nullable private transient UserTransaction userTransaction; @Nullable private String userTransactionName; private boolean autodetectUserTransaction = true; private boolean cacheUserTransaction = true; private boolean userTransactionObtainedFromJndi = false; @Nullable private transient TransactionManager transactionManager; @Nullable private String transactionManagerName; private boolean autodetectTransactionManager = true; @Nullable private transient TransactionSynchronizationRegistry transactionSynchronizationRegistry; @Nullable private String transactionSynchronizationRegistryName; private boolean autodetectTransactionSynchronizationRegistry = true; private boolean allowCustomIsolationLevels = false; /** * Create a new JtaTransactionManager instance, to be configured as bean. * Invoke {@code afterPropertiesSet} to activate the configuration. * @see #setUserTransactionName * @see #setUserTransaction * @see #setTransactionManagerName * @see #setTransactionManager * @see #afterPropertiesSet() */ public JtaTransactionManager() { setNestedTransactionAllowed(true); } /** * Create a new JtaTransactionManager instance. * @param userTransaction the JTA UserTransaction to use as direct reference */ public JtaTransactionManager(UserTransaction userTransaction) { this(); Assert.notNull(userTransaction, "UserTransaction must not be null"); this.userTransaction = userTransaction; } /** * Create a new JtaTransactionManager instance. * @param userTransaction the JTA UserTransaction to use as direct reference * @param transactionManager the JTA TransactionManager to use as direct reference */ public JtaTransactionManager(UserTransaction userTransaction, TransactionManager transactionManager) { this(); Assert.notNull(userTransaction, "UserTransaction must not be null"); Assert.notNull(transactionManager, "TransactionManager must not be null"); this.userTransaction = userTransaction; this.transactionManager = transactionManager; } /** * Create a new JtaTransactionManager instance. * @param transactionManager the JTA TransactionManager to use as direct reference */ public JtaTransactionManager(TransactionManager transactionManager) { this(); Assert.notNull(transactionManager, "TransactionManager must not be null"); this.transactionManager = transactionManager; this.userTransaction = buildUserTransaction(transactionManager); } /** * Set the JndiTemplate to use for JNDI lookups. * A default one is used if not set. */ public void setJndiTemplate(JndiTemplate jndiTemplate) { Assert.notNull(jndiTemplate, "JndiTemplate must not be null"); this.jndiTemplate = jndiTemplate; } /** * Return the JndiTemplate used for JNDI lookups. */ public JndiTemplate getJndiTemplate() { return this.jndiTemplate; } /** * Set the JNDI environment to use for JNDI lookups. * Creates a JndiTemplate with the given environment settings. * @see #setJndiTemplate */ public void setJndiEnvironment(@Nullable Properties jndiEnvironment) { this.jndiTemplate = new JndiTemplate(jndiEnvironment); } /** * Return the JNDI environment to use for JNDI lookups. */ @Nullable public Properties getJndiEnvironment() { return this.jndiTemplate.getEnvironment(); } /** * Set the JTA UserTransaction to use as direct reference. * <p>Typically just used for local JTA setups; in a Jakarta EE environment, * the UserTransaction will always be fetched from JNDI. * @see #setUserTransactionName * @see #setAutodetectUserTransaction */ public void setUserTransaction(@Nullable UserTransaction userTransaction) { this.userTransaction = userTransaction; } /** * Return the JTA UserTransaction that this transaction manager uses. */ @Nullable public UserTransaction getUserTransaction() { return this.userTransaction; } /** * Set the JNDI name of the JTA UserTransaction. * <p>Note that the UserTransaction will be autodetected at the Jakarta EE * default location "java:comp/UserTransaction" if not specified explicitly. * @see #DEFAULT_USER_TRANSACTION_NAME * @see #setUserTransaction * @see #setAutodetectUserTransaction */ public void setUserTransactionName(String userTransactionName) { this.userTransactionName = userTransactionName; } /** * Set whether to autodetect the JTA UserTransaction at its default * JNDI location "java:comp/UserTransaction", as specified by Jakarta EE. * Will proceed without UserTransaction if none found. * <p>Default is "true", autodetecting the UserTransaction unless * it has been specified explicitly. Turn this flag off to allow for * JtaTransactionManager operating against the TransactionManager only, * despite a default UserTransaction being available. * @see #DEFAULT_USER_TRANSACTION_NAME */ public void setAutodetectUserTransaction(boolean autodetectUserTransaction) { this.autodetectUserTransaction = autodetectUserTransaction; } /** * Set whether to cache the JTA UserTransaction object fetched from JNDI. * <p>Default is "true": UserTransaction lookup will only happen at startup, * reusing the same UserTransaction handle for all transactions of all threads. * This is the most efficient choice for all application servers that provide * a shared UserTransaction object (the typical case). * <p>Turn this flag off to enforce a fresh lookup of the UserTransaction * for every transaction. This is only necessary for application servers * that return a new UserTransaction for every transaction, keeping state * tied to the UserTransaction object itself rather than the current thread. * @see #setUserTransactionName */ public void setCacheUserTransaction(boolean cacheUserTransaction) { this.cacheUserTransaction = cacheUserTransaction; } /** * Set the JTA TransactionManager to use as direct reference. * <p>A TransactionManager is necessary for suspending and resuming transactions, * as this not supported by the UserTransaction interface. * <p>Note that the TransactionManager will be autodetected if the JTA * UserTransaction object implements the JTA TransactionManager interface too, * as well as autodetected at various well-known fallback JNDI locations. * @see #setTransactionManagerName * @see #setAutodetectTransactionManager */ public void setTransactionManager(@Nullable TransactionManager transactionManager) { this.transactionManager = transactionManager; } /** * Return the JTA TransactionManager that this transaction manager uses, if any. */ @Nullable public TransactionManager getTransactionManager() { return this.transactionManager; } /** * Set the JNDI name of the JTA TransactionManager. * <p>A TransactionManager is necessary for suspending and resuming transactions, * as this not supported by the UserTransaction interface. * <p>Note that the TransactionManager will be autodetected if the JTA * UserTransaction object implements the JTA TransactionManager interface too, * as well as autodetected at various well-known fallback JNDI locations. * @see #setTransactionManager * @see #setAutodetectTransactionManager */ public void setTransactionManagerName(String transactionManagerName) { this.transactionManagerName = transactionManagerName; } /** * Set whether to autodetect a JTA UserTransaction object that implements * the JTA TransactionManager interface too (i.e. the JNDI location for the * TransactionManager is "java:comp/UserTransaction", same as for the UserTransaction). * Also checks the fallback JNDI locations "java:comp/TransactionManager" and * "java:/TransactionManager". Will proceed without TransactionManager if none found. * <p>Default is "true", autodetecting the TransactionManager unless it has been * specified explicitly. Can be turned off to deliberately ignore an available * TransactionManager, for example when there are known issues with suspend/resume * and any attempt to use REQUIRES_NEW or NOT_SUPPORTED should fail fast. * @see #FALLBACK_TRANSACTION_MANAGER_NAMES */ public void setAutodetectTransactionManager(boolean autodetectTransactionManager) { this.autodetectTransactionManager = autodetectTransactionManager; } /** * Set the JTA 1.1 TransactionSynchronizationRegistry to use as direct reference. * <p>A TransactionSynchronizationRegistry allows for interposed registration * of transaction synchronizations, as an alternative to the regular registration * methods on the JTA TransactionManager API. Also, it is an official part of the * Jakarta EE platform, in contrast to the JTA TransactionManager itself. * <p>Note that the TransactionSynchronizationRegistry will be autodetected in JNDI and * also from the UserTransaction/TransactionManager object if implemented there as well. * @see #setTransactionSynchronizationRegistryName * @see #setAutodetectTransactionSynchronizationRegistry */ public void setTransactionSynchronizationRegistry(@Nullable TransactionSynchronizationRegistry transactionSynchronizationRegistry) { this.transactionSynchronizationRegistry = transactionSynchronizationRegistry; } /** * Return the JTA 1.1 TransactionSynchronizationRegistry that this transaction manager uses, if any. */ @Nullable public TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() { return this.transactionSynchronizationRegistry; } /** * Set the JNDI name of the JTA 1.1 TransactionSynchronizationRegistry. * <p>Note that the TransactionSynchronizationRegistry will be autodetected * at the Jakarta EE default location "java:comp/TransactionSynchronizationRegistry" * if not specified explicitly. * @see #DEFAULT_TRANSACTION_SYNCHRONIZATION_REGISTRY_NAME */ public void setTransactionSynchronizationRegistryName(String transactionSynchronizationRegistryName) { this.transactionSynchronizationRegistryName = transactionSynchronizationRegistryName; } /** * Set whether to autodetect a JTA 1.1 TransactionSynchronizationRegistry object * at its default JDNI location ("java:comp/TransactionSynchronizationRegistry") * if the UserTransaction has also been obtained from JNDI, and also whether * to fall back to checking whether the JTA UserTransaction/TransactionManager * object implements the JTA TransactionSynchronizationRegistry interface too. * <p>Default is "true", autodetecting the TransactionSynchronizationRegistry * unless it has been specified explicitly. Can be turned off to delegate * synchronization registration to the regular JTA TransactionManager API. */ public void setAutodetectTransactionSynchronizationRegistry(boolean autodetectTransactionSynchronizationRegistry) { this.autodetectTransactionSynchronizationRegistry = autodetectTransactionSynchronizationRegistry; } /** * Set whether to allow custom isolation levels to be specified. * <p>Default is "false", throwing an exception if a non-default isolation level * is specified for a transaction. Turn this flag on if affected resource adapters * check the thread-bound transaction context and apply the specified isolation * levels individually (e.g. through an IsolationLevelDataSourceAdapter). * @see org.springframework.jdbc.datasource.IsolationLevelDataSourceAdapter * @see org.springframework.jdbc.datasource.lookup.IsolationLevelDataSourceRouter */ public void setAllowCustomIsolationLevels(boolean allowCustomIsolationLevels) { this.allowCustomIsolationLevels = allowCustomIsolationLevels; } /** * Initialize the UserTransaction as well as the TransactionManager handle. * @see #initUserTransactionAndTransactionManager() */ @Override public void afterPropertiesSet() throws TransactionSystemException { initUserTransactionAndTransactionManager(); checkUserTransactionAndTransactionManager(); initTransactionSynchronizationRegistry(); } /** * Initialize the UserTransaction as well as the TransactionManager handle. * @throws TransactionSystemException if initialization failed */ protected void initUserTransactionAndTransactionManager() throws TransactionSystemException { if (this.userTransaction == null) { // Fetch JTA UserTransaction from JNDI, if necessary. if (StringUtils.hasLength(this.userTransactionName)) { this.userTransaction = lookupUserTransaction(this.userTransactionName); this.userTransactionObtainedFromJndi = true; } else { this.userTransaction = retrieveUserTransaction(); if (this.userTransaction == null && this.autodetectUserTransaction) { // Autodetect UserTransaction at its default JNDI location. this.userTransaction = findUserTransaction(); } } } if (this.transactionManager == null) { // Fetch JTA TransactionManager from JNDI, if necessary. if (StringUtils.hasLength(this.transactionManagerName)) { this.transactionManager = lookupTransactionManager(this.transactionManagerName); } else { this.transactionManager = retrieveTransactionManager(); if (this.transactionManager == null && this.autodetectTransactionManager) { // Autodetect UserTransaction object that implements TransactionManager, // and check fallback JNDI locations otherwise. this.transactionManager = findTransactionManager(this.userTransaction); } } } // If only JTA TransactionManager specified, create UserTransaction handle for it. if (this.userTransaction == null && this.transactionManager != null) { this.userTransaction = buildUserTransaction(this.transactionManager); } } /** * Check the UserTransaction as well as the TransactionManager handle, * assuming standard JTA requirements. * @throws IllegalStateException if no sufficient handles are available */ protected void checkUserTransactionAndTransactionManager() throws IllegalStateException { // We at least need the JTA UserTransaction. if (this.userTransaction != null) { if (logger.isDebugEnabled()) { logger.debug("Using JTA UserTransaction: " + this.userTransaction); } } else { throw new IllegalStateException("No JTA UserTransaction available - specify either " + "'userTransaction' or 'userTransactionName' or 'transactionManager' or 'transactionManagerName'"); } // For transaction suspension, the JTA TransactionManager is necessary too. if (this.transactionManager != null) { if (logger.isDebugEnabled()) { logger.debug("Using JTA TransactionManager: " + this.transactionManager); } } else { logger.warn("No JTA TransactionManager found: transaction suspension not available"); } } /** * Initialize the JTA 1.1 TransactionSynchronizationRegistry, if available. * <p>To be called after {@link #initUserTransactionAndTransactionManager()}, * since it may check the UserTransaction and TransactionManager handles. * @throws TransactionSystemException if initialization failed */ protected void initTransactionSynchronizationRegistry() { if (this.transactionSynchronizationRegistry == null) { // Fetch JTA TransactionSynchronizationRegistry from JNDI, if necessary. if (StringUtils.hasLength(this.transactionSynchronizationRegistryName)) { this.transactionSynchronizationRegistry = lookupTransactionSynchronizationRegistry(this.transactionSynchronizationRegistryName); } else { this.transactionSynchronizationRegistry = retrieveTransactionSynchronizationRegistry(); if (this.transactionSynchronizationRegistry == null && this.autodetectTransactionSynchronizationRegistry) { // Autodetect in JNDI if applicable, and check UserTransaction/TransactionManager // object that implements TransactionSynchronizationRegistry otherwise. this.transactionSynchronizationRegistry = findTransactionSynchronizationRegistry(this.userTransaction, this.transactionManager); } } } if (this.transactionSynchronizationRegistry != null) { if (logger.isDebugEnabled()) { logger.debug("Using JTA TransactionSynchronizationRegistry: " + this.transactionSynchronizationRegistry); } } } /** * Build a UserTransaction handle based on the given TransactionManager. * @param transactionManager the TransactionManager * @return a corresponding UserTransaction handle */ protected UserTransaction buildUserTransaction(TransactionManager transactionManager) { if (transactionManager instanceof UserTransaction ut) { return ut; } else { return new UserTransactionAdapter(transactionManager); } } /** * Look up the JTA UserTransaction in JNDI via the configured name. * <p>Called by {@code afterPropertiesSet} if no direct UserTransaction reference was set. * Can be overridden in subclasses to provide a different UserTransaction object. * @param userTransactionName the JNDI name of the UserTransaction * @return the UserTransaction object * @throws TransactionSystemException if the JNDI lookup failed * @see #setJndiTemplate * @see #setUserTransactionName */ protected UserTransaction lookupUserTransaction(String userTransactionName) throws TransactionSystemException { try { if (logger.isDebugEnabled()) { logger.debug("Retrieving JTA UserTransaction from JNDI location [" + userTransactionName + "]"); } return getJndiTemplate().lookup(userTransactionName, UserTransaction.class); } catch (NamingException ex) { throw new TransactionSystemException( "JTA UserTransaction is not available at JNDI location [" + userTransactionName + "]", ex); } } /** * Look up the JTA TransactionManager in JNDI via the configured name. * <p>Called by {@code afterPropertiesSet} if no direct TransactionManager reference was set. * Can be overridden in subclasses to provide a different TransactionManager object. * @param transactionManagerName the JNDI name of the TransactionManager * @return the UserTransaction object * @throws TransactionSystemException if the JNDI lookup failed * @see #setJndiTemplate * @see #setTransactionManagerName */ protected TransactionManager lookupTransactionManager(String transactionManagerName) throws TransactionSystemException { try { if (logger.isDebugEnabled()) { logger.debug("Retrieving JTA TransactionManager from JNDI location [" + transactionManagerName + "]"); } return getJndiTemplate().lookup(transactionManagerName, TransactionManager.class); } catch (NamingException ex) { throw new TransactionSystemException( "JTA TransactionManager is not available at JNDI location [" + transactionManagerName + "]", ex); } } /** * Look up the JTA 1.1 TransactionSynchronizationRegistry in JNDI via the configured name. * <p>Can be overridden in subclasses to provide a different TransactionManager object. * @param registryName the JNDI name of the * TransactionSynchronizationRegistry * @return the TransactionSynchronizationRegistry object * @throws TransactionSystemException if the JNDI lookup failed * @see #setJndiTemplate * @see #setTransactionSynchronizationRegistryName */ protected TransactionSynchronizationRegistry lookupTransactionSynchronizationRegistry(String registryName) throws TransactionSystemException { try { if (logger.isDebugEnabled()) { logger.debug("Retrieving JTA TransactionSynchronizationRegistry from JNDI location [" + registryName + "]"); } return getJndiTemplate().lookup(registryName, TransactionSynchronizationRegistry.class); } catch (NamingException ex) { throw new TransactionSystemException( "JTA TransactionSynchronizationRegistry is not available at JNDI location [" + registryName + "]", ex); } } /** * Allows subclasses to retrieve the JTA UserTransaction in a vendor-specific manner. * Only called if no "userTransaction" or "userTransactionName" specified. * <p>The default implementation simply returns {@code null}. * @return the JTA UserTransaction handle to use, or {@code null} if none found * @throws TransactionSystemException in case of errors * @see #setUserTransaction * @see #setUserTransactionName */ @Nullable protected UserTransaction retrieveUserTransaction() throws TransactionSystemException { return null; } /** * Allows subclasses to retrieve the JTA TransactionManager in a vendor-specific manner. * Only called if no "transactionManager" or "transactionManagerName" specified. * <p>The default implementation simply returns {@code null}. * @return the JTA TransactionManager handle to use, or {@code null} if none found * @throws TransactionSystemException in case of errors * @see #setTransactionManager * @see #setTransactionManagerName */ @Nullable protected TransactionManager retrieveTransactionManager() throws TransactionSystemException { return null; } /** * Allows subclasses to retrieve the JTA 1.1 TransactionSynchronizationRegistry * in a vendor-specific manner. * <p>The default implementation simply returns {@code null}. * @return the JTA TransactionSynchronizationRegistry handle to use, * or {@code null} if none found * @throws TransactionSystemException in case of errors */ @Nullable protected TransactionSynchronizationRegistry retrieveTransactionSynchronizationRegistry() throws TransactionSystemException { return null; } /** * Find the JTA UserTransaction through a default JNDI lookup: * "java:comp/UserTransaction". * @return the JTA UserTransaction reference, or {@code null} if not found * @see #DEFAULT_USER_TRANSACTION_NAME */ @Nullable protected UserTransaction findUserTransaction() { String jndiName = DEFAULT_USER_TRANSACTION_NAME; try { UserTransaction ut = getJndiTemplate().lookup(jndiName, UserTransaction.class); if (logger.isDebugEnabled()) { logger.debug("JTA UserTransaction found at default JNDI location [" + jndiName + "]"); } this.userTransactionObtainedFromJndi = true; return ut; } catch (NamingException ex) { if (logger.isDebugEnabled()) { logger.debug("No JTA UserTransaction found at default JNDI location [" + jndiName + "]", ex); } return null; } } /** * Find the JTA TransactionManager through autodetection: checking whether the * UserTransaction object implements the TransactionManager, and checking the * fallback JNDI locations. * @param ut the JTA UserTransaction object * @return the JTA TransactionManager reference, or {@code null} if not found * @see #FALLBACK_TRANSACTION_MANAGER_NAMES */ @Nullable protected TransactionManager findTransactionManager(@Nullable UserTransaction ut) { if (ut instanceof TransactionManager tm) { if (logger.isDebugEnabled()) { logger.debug("JTA UserTransaction object [" + ut + "] implements TransactionManager"); } return tm; } // Check fallback JNDI locations. for (String jndiName : FALLBACK_TRANSACTION_MANAGER_NAMES) { try { TransactionManager tm = getJndiTemplate().lookup(jndiName, TransactionManager.class); if (logger.isDebugEnabled()) { logger.debug("JTA TransactionManager found at fallback JNDI location [" + jndiName + "]"); } return tm; } catch (NamingException ex) { if (logger.isDebugEnabled()) { logger.debug("No JTA TransactionManager found at fallback JNDI location [" + jndiName + "]", ex); } } } // OK, so no JTA TransactionManager is available... return null; } /** * Find the JTA 1.1 TransactionSynchronizationRegistry through autodetection: * checking whether the UserTransaction object or TransactionManager object * implements it, and checking Jakarta EE's standard JNDI location. * <p>The default implementation simply returns {@code null}. * @param ut the JTA UserTransaction object * @param tm the JTA TransactionManager object * @return the JTA TransactionSynchronizationRegistry handle to use, * or {@code null} if none found * @throws TransactionSystemException in case of errors */ @Nullable protected TransactionSynchronizationRegistry findTransactionSynchronizationRegistry( @Nullable UserTransaction ut, @Nullable TransactionManager tm) throws TransactionSystemException { if (this.userTransactionObtainedFromJndi) { // UserTransaction has already been obtained from JNDI, so the // TransactionSynchronizationRegistry probably sits there as well. String jndiName = DEFAULT_TRANSACTION_SYNCHRONIZATION_REGISTRY_NAME; try { TransactionSynchronizationRegistry tsr = getJndiTemplate().lookup(jndiName, TransactionSynchronizationRegistry.class); if (logger.isDebugEnabled()) { logger.debug("JTA TransactionSynchronizationRegistry found at default JNDI location [" + jndiName + "]"); } return tsr; } catch (NamingException ex) { if (logger.isDebugEnabled()) { logger.debug("No JTA TransactionSynchronizationRegistry found at default JNDI location [" + jndiName + "]", ex); } } } // Check whether the UserTransaction or TransactionManager implements it... if (ut instanceof TransactionSynchronizationRegistry tsr) { return tsr; } if (tm instanceof TransactionSynchronizationRegistry tsr) { return tsr; } // OK, so no JTA 1.1 TransactionSynchronizationRegistry is available... return null; } /** * This implementation returns a JtaTransactionObject instance for the * JTA UserTransaction. * <p>The UserTransaction object will either be looked up freshly for the * current transaction, or the cached one looked up at startup will be used. * The latter is the default: Most application servers use a shared singleton * UserTransaction that can be cached. Turn off the "cacheUserTransaction" * flag to enforce a fresh lookup for every transaction. * @see #setCacheUserTransaction */ @Override protected Object doGetTransaction() { UserTransaction ut = getUserTransaction(); if (ut == null) { throw new CannotCreateTransactionException("No JTA UserTransaction available - " + "programmatic PlatformTransactionManager.getTransaction usage not supported"); } if (!this.cacheUserTransaction) { ut = lookupUserTransaction( this.userTransactionName != null ? this.userTransactionName : DEFAULT_USER_TRANSACTION_NAME); } return doGetJtaTransaction(ut); } /** * Get a JTA transaction object for the given current UserTransaction. * <p>Subclasses can override this to provide a JtaTransactionObject * subclass, for example holding some additional JTA handle needed. * @param ut the UserTransaction handle to use for the current transaction * @return the JtaTransactionObject holding the UserTransaction */ protected JtaTransactionObject doGetJtaTransaction(UserTransaction ut) { return new JtaTransactionObject(ut); } @Override protected boolean isExistingTransaction(Object transaction) { JtaTransactionObject txObject = (JtaTransactionObject) transaction; try { return (txObject.getUserTransaction().getStatus() != Status.STATUS_NO_TRANSACTION); } catch (SystemException ex) { throw new TransactionSystemException("JTA failure on getStatus", ex); } } /** * This implementation returns false to cause a further invocation * of doBegin despite an already existing transaction. * <p>JTA implementations might support nested transactions via further * {@code UserTransaction.begin()} invocations, but never support savepoints. * @see #doBegin * @see jakarta.transaction.UserTransaction#begin() */ @Override protected boolean useSavepointForNestedTransaction() { return false; } @Override protected void doBegin(Object transaction, TransactionDefinition definition) { JtaTransactionObject txObject = (JtaTransactionObject) transaction; try { doJtaBegin(txObject, definition); } catch (NotSupportedException | UnsupportedOperationException ex) { throw new NestedTransactionNotSupportedException( "JTA implementation does not support nested transactions", ex); } catch (SystemException ex) { throw new CannotCreateTransactionException("JTA failure on begin", ex); } } /** * Perform a JTA begin on the JTA UserTransaction or TransactionManager. * <p>This implementation only supports standard JTA functionality: * that is, no per-transaction isolation levels and no transaction names. * Can be overridden in subclasses, for specific JTA implementations. * <p>Calls {@code applyIsolationLevel} and {@code applyTimeout} * before invoking the UserTransaction's {@code begin} method. * @param txObject the JtaTransactionObject containing the UserTransaction * @param definition the TransactionDefinition instance, describing propagation * behavior, isolation level, read-only flag, timeout, and transaction name * @throws NotSupportedException if thrown by JTA methods * @throws SystemException if thrown by JTA methods * @see #getUserTransaction * @see #getTransactionManager * @see #applyIsolationLevel * @see #applyTimeout * @see JtaTransactionObject#getUserTransaction() * @see jakarta.transaction.UserTransaction#setTransactionTimeout * @see jakarta.transaction.UserTransaction#begin */ protected void doJtaBegin(JtaTransactionObject txObject, TransactionDefinition definition) throws NotSupportedException, SystemException { applyIsolationLevel(txObject, definition.getIsolationLevel()); int timeout = determineTimeout(definition); applyTimeout(txObject, timeout); txObject.getUserTransaction().begin(); } /** * Apply the given transaction isolation level. The default implementation * will throw an exception for any level other than ISOLATION_DEFAULT. * <p>To be overridden in subclasses for specific JTA implementations, * as alternative to overriding the full {@link #doJtaBegin} method. * @param txObject the JtaTransactionObject containing the UserTransaction * @param isolationLevel isolation level taken from transaction definition * @throws InvalidIsolationLevelException if the given isolation level * cannot be applied * @throws SystemException if thrown by the JTA implementation * @see #doJtaBegin * @see JtaTransactionObject#getUserTransaction() * @see #getTransactionManager() */ protected void applyIsolationLevel(JtaTransactionObject txObject, int isolationLevel) throws InvalidIsolationLevelException, SystemException { if (!this.allowCustomIsolationLevels && isolationLevel != TransactionDefinition.ISOLATION_DEFAULT) { throw new InvalidIsolationLevelException( "JtaTransactionManager does not support custom isolation levels by default - " + "switch 'allowCustomIsolationLevels' to 'true'"); } } /** * Apply the given transaction timeout. The default implementation will call * {@code UserTransaction.setTransactionTimeout} for a non-default timeout value. * @param txObject the JtaTransactionObject containing the UserTransaction * @param timeout the timeout value taken from transaction definition * @throws SystemException if thrown by the JTA implementation * @see #doJtaBegin * @see JtaTransactionObject#getUserTransaction() * @see jakarta.transaction.UserTransaction#setTransactionTimeout(int) */ protected void applyTimeout(JtaTransactionObject txObject, int timeout) throws SystemException { if (timeout > TransactionDefinition.TIMEOUT_DEFAULT) { txObject.getUserTransaction().setTransactionTimeout(timeout); if (timeout > 0) { txObject.resetTransactionTimeout = true; } } } @Override protected Object doSuspend(Object transaction) { JtaTransactionObject txObject = (JtaTransactionObject) transaction; try { return doJtaSuspend(txObject); } catch (SystemException ex) { throw new TransactionSystemException("JTA failure on suspend", ex); } } /** * Perform a JTA suspend on the JTA TransactionManager. * <p>Can be overridden in subclasses, for specific JTA implementations. * @param txObject the JtaTransactionObject containing the UserTransaction * @return the suspended JTA Transaction object * @throws SystemException if thrown by JTA methods * @see #getTransactionManager() * @see jakarta.transaction.TransactionManager#suspend() */ protected Object doJtaSuspend(JtaTransactionObject txObject) throws SystemException { if (getTransactionManager() == null) { throw new TransactionSuspensionNotSupportedException( "JtaTransactionManager needs a JTA TransactionManager for suspending a transaction: " + "specify the 'transactionManager' or 'transactionManagerName' property"); } return getTransactionManager().suspend(); } @Override protected void doResume(@Nullable Object transaction, Object suspendedResources) { JtaTransactionObject txObject = (JtaTransactionObject) transaction; try { doJtaResume(txObject, suspendedResources); } catch (InvalidTransactionException ex) { throw new IllegalTransactionStateException("Tried to resume invalid JTA transaction", ex); } catch (IllegalStateException ex) { throw new TransactionSystemException("Unexpected internal transaction state", ex); } catch (SystemException ex) { throw new TransactionSystemException("JTA failure on resume", ex); } } /** * Perform a JTA resume on the JTA TransactionManager. * <p>Can be overridden in subclasses, for specific JTA implementations. * @param txObject the JtaTransactionObject containing the UserTransaction * @param suspendedTransaction the suspended JTA Transaction object * @throws InvalidTransactionException if thrown by JTA methods * @throws SystemException if thrown by JTA methods * @see #getTransactionManager() * @see jakarta.transaction.TransactionManager#resume(jakarta.transaction.Transaction) */ protected void doJtaResume(@Nullable JtaTransactionObject txObject, Object suspendedTransaction) throws InvalidTransactionException, SystemException { if (getTransactionManager() == null) { throw new TransactionSuspensionNotSupportedException( "JtaTransactionManager needs a JTA TransactionManager for suspending a transaction: " + "specify the 'transactionManager' or 'transactionManagerName' property"); } getTransactionManager().resume((Transaction) suspendedTransaction); } /** * This implementation returns "true": a JTA commit will properly handle * transactions that have been marked rollback-only at a global level. */ @Override protected boolean shouldCommitOnGlobalRollbackOnly() { return true; } @Override protected void doCommit(DefaultTransactionStatus status) { JtaTransactionObject txObject = (JtaTransactionObject) status.getTransaction(); try { int jtaStatus = txObject.getUserTransaction().getStatus(); if (jtaStatus == Status.STATUS_NO_TRANSACTION) { // Should never happen... would have thrown an exception before // and as a consequence led to a rollback, not to a commit call. // In any case, the transaction is already fully cleaned up. throw new UnexpectedRollbackException("JTA transaction already completed - probably rolled back"); } if (jtaStatus == Status.STATUS_ROLLEDBACK) { // Only really happens on JBoss 4.2 in case of an early timeout... // Explicit rollback call necessary to clean up the transaction. // IllegalStateException expected on JBoss; call still necessary. try { txObject.getUserTransaction().rollback(); } catch (IllegalStateException ex) { if (logger.isDebugEnabled()) { logger.debug("Rollback failure with transaction already marked as rolled back: " + ex); } } throw new UnexpectedRollbackException("JTA transaction already rolled back (probably due to a timeout)"); } txObject.getUserTransaction().commit(); } catch (RollbackException ex) { throw new UnexpectedRollbackException( "JTA transaction unexpectedly rolled back (maybe due to a timeout)", ex); } catch (HeuristicMixedException ex) { throw new HeuristicCompletionException(HeuristicCompletionException.STATE_MIXED, ex); } catch (HeuristicRollbackException ex) { throw new HeuristicCompletionException(HeuristicCompletionException.STATE_ROLLED_BACK, ex); } catch (IllegalStateException ex) { throw new TransactionSystemException("Unexpected internal transaction state", ex); } catch (SystemException ex) { throw new TransactionSystemException("JTA failure on commit", ex); } } @Override protected void doRollback(DefaultTransactionStatus status) { JtaTransactionObject txObject = (JtaTransactionObject) status.getTransaction(); try { int jtaStatus = txObject.getUserTransaction().getStatus(); if (jtaStatus != Status.STATUS_NO_TRANSACTION) { try { txObject.getUserTransaction().rollback(); } catch (IllegalStateException ex) { if (jtaStatus == Status.STATUS_ROLLEDBACK) { // Only really happens on JBoss 4.2 in case of an early timeout... if (logger.isDebugEnabled()) { logger.debug("Rollback failure with transaction already marked as rolled back: " + ex); } } else { throw new TransactionSystemException("Unexpected internal transaction state", ex); } } } } catch (SystemException ex) { throw new TransactionSystemException("JTA failure on rollback", ex); } } @Override protected void doSetRollbackOnly(DefaultTransactionStatus status) { JtaTransactionObject txObject = (JtaTransactionObject) status.getTransaction(); if (status.isDebug()) { logger.debug("Setting JTA transaction rollback-only"); } try { int jtaStatus = txObject.getUserTransaction().getStatus(); if (jtaStatus != Status.STATUS_NO_TRANSACTION && jtaStatus != Status.STATUS_ROLLEDBACK) { txObject.getUserTransaction().setRollbackOnly(); } } catch (IllegalStateException ex) { throw new TransactionSystemException("Unexpected internal transaction state", ex); } catch (SystemException ex) { throw new TransactionSystemException("JTA failure on setRollbackOnly", ex); } } @Override protected void registerAfterCompletionWithExistingTransaction( Object transaction, List<TransactionSynchronization> synchronizations) { JtaTransactionObject txObject = (JtaTransactionObject) transaction; logger.debug("Registering after-completion synchronization with existing JTA transaction"); try { doRegisterAfterCompletionWithJtaTransaction(txObject, synchronizations); } catch (SystemException ex) { throw new TransactionSystemException("JTA failure on registerSynchronization", ex); } catch (Exception ex) { // Note: JBoss throws plain RuntimeException with RollbackException as cause. if (ex instanceof RollbackException || ex.getCause() instanceof RollbackException) { logger.debug("Participating in existing JTA transaction that has been marked for rollback: " + "cannot register Spring after-completion callbacks with outer JTA transaction - " + "immediately performing Spring after-completion callbacks with outcome status 'rollback'. " + "Original exception: " + ex); invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_ROLLED_BACK); } else { logger.debug("Participating in existing JTA transaction, but unexpected internal transaction " + "state encountered: cannot register Spring after-completion callbacks with outer JTA " + "transaction - processing Spring after-completion callbacks with outcome status 'unknown'" + "Original exception: " + ex); invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN); } } } /** * Register a JTA synchronization on the JTA TransactionManager, for calling * {@code afterCompletion} on the given Spring TransactionSynchronizations. * <p>The default implementation registers the synchronizations on the * JTA 1.1 TransactionSynchronizationRegistry, if available, or on the * JTA TransactionManager's current Transaction - again, if available. * If none of the two is available, a warning will be logged. * <p>Can be overridden in subclasses, for specific JTA implementations. * @param txObject the current transaction object * @param synchronizations a List of TransactionSynchronization objects * @throws RollbackException if thrown by JTA methods * @throws SystemException if thrown by JTA methods * @see #getTransactionManager() * @see jakarta.transaction.Transaction#registerSynchronization * @see jakarta.transaction.TransactionSynchronizationRegistry#registerInterposedSynchronization */ protected void doRegisterAfterCompletionWithJtaTransaction( JtaTransactionObject txObject, List<TransactionSynchronization> synchronizations) throws RollbackException, SystemException { int jtaStatus = txObject.getUserTransaction().getStatus(); if (jtaStatus == Status.STATUS_NO_TRANSACTION) { throw new RollbackException("JTA transaction already completed - probably rolled back"); } if (jtaStatus == Status.STATUS_ROLLEDBACK) { throw new RollbackException("JTA transaction already rolled back (probably due to a timeout)"); } if (this.transactionSynchronizationRegistry != null) { // JTA 1.1 TransactionSynchronizationRegistry available - use it. this.transactionSynchronizationRegistry.registerInterposedSynchronization( new JtaAfterCompletionSynchronization(synchronizations)); } else if (getTransactionManager() != null) { // At least the JTA TransactionManager available - use that one. Transaction transaction = getTransactionManager().getTransaction(); if (transaction == null) { throw new IllegalStateException("No JTA Transaction available"); } transaction.registerSynchronization(new JtaAfterCompletionSynchronization(synchronizations)); } else { // No JTA TransactionManager available - log a warning. logger.warn("Participating in existing JTA transaction, but no JTA TransactionManager available: " + "cannot register Spring after-completion callbacks with outer JTA transaction - " + "processing Spring after-completion callbacks with outcome status 'unknown'"); invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN); } } @Override protected void doCleanupAfterCompletion(Object transaction) { JtaTransactionObject txObject = (JtaTransactionObject) transaction; if (txObject.resetTransactionTimeout) { try { txObject.getUserTransaction().setTransactionTimeout(0); } catch (SystemException ex) { logger.debug("Failed to reset transaction timeout after JTA completion", ex); } } } //--------------------------------------------------------------------- // Implementation of TransactionFactory interface //--------------------------------------------------------------------- @Override public Transaction createTransaction(@Nullable String name, int timeout) throws NotSupportedException, SystemException { TransactionManager tm = getTransactionManager(); Assert.state(tm != null, "No JTA TransactionManager available"); if (timeout >= 0) { tm.setTransactionTimeout(timeout); } tm.begin(); return new ManagedTransactionAdapter(tm); } @Override public boolean supportsResourceAdapterManagedTransactions() { return false; } //--------------------------------------------------------------------- // Serialization support //--------------------------------------------------------------------- private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { // Rely on default serialization; just initialize state after deserialization. ois.defaultReadObject(); // Create template for client-side JNDI lookup. this.jndiTemplate = new JndiTemplate(); // Perform a fresh lookup for JTA handles. initUserTransactionAndTransactionManager(); initTransactionSynchronizationRegistry(); } }
spring-projects/spring-framework
spring-tx/src/main/java/org/springframework/transaction/jta/JtaTransactionManager.java
2,154
package org.telegram.ui.Components; import static org.telegram.messenger.AndroidUtilities.dp; import static org.telegram.messenger.AndroidUtilities.dpf2; import static org.telegram.messenger.AndroidUtilities.lerp; import android.content.Context; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RadialGradient; import android.graphics.RectF; import android.graphics.Shader; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import com.google.zxing.common.detector.MathUtils; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.LiteMode; import org.telegram.messenger.R; import org.telegram.messenger.SvgHelper; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.Premium.StarParticlesView; import java.util.Arrays; public class CacheChart extends View { public static final int TYPE_CACHE = 0; public static final int TYPE_NETWORK = 1; private RectF chartMeasureBounds = new RectF(); private RectF chartBounds = new RectF(); private RectF chartInnerBounds = new RectF(); private static final int DEFAULT_SECTIONS_COUNT = 11; private static final int[] DEFAULT_COLORS = new int[] { Theme.key_statisticChartLine_lightblue, Theme.key_statisticChartLine_blue, Theme.key_statisticChartLine_green, Theme.key_statisticChartLine_purple, Theme.key_statisticChartLine_lightgreen, Theme.key_statisticChartLine_red, Theme.key_statisticChartLine_orange, Theme.key_statisticChartLine_cyan, Theme.key_statisticChartLine_purple, Theme.key_statisticChartLine_golden, Theme.key_statisticChartLine_golden }; private static final int[] DEFAULT_PARTICLES = new int[] { R.raw.cache_photos, R.raw.cache_videos, R.raw.cache_documents, R.raw.cache_music, R.raw.cache_videos, R.raw.cache_music, R.raw.cache_stickers, R.raw.cache_profile_photos, R.raw.cache_other, R.raw.cache_other, R.raw.cache_documents }; private final int sectionsCount; private final int[] colorKeys; private final int type; private final boolean svgParticles; private final int[] particles; private boolean loading = true; public AnimatedFloat loadingFloat = new AnimatedFloat(this, 750, CubicBezierInterpolator.EASE_OUT_QUINT); private boolean complete = false; private AnimatedFloat completeFloat = new AnimatedFloat(this, 650, CubicBezierInterpolator.EASE_OUT_QUINT); private Sector[] sectors; private float[] segmentsTmp = new float[2]; private RectF roundingRect = new RectF(); private Paint loadingBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private RectF completePathBounds; private Path completePath = new Path(); private Paint completePaintStroke = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint completePaint = new Paint(Paint.ANTI_ALIAS_FLAG); private LinearGradient completeGradient, completeTextGradient; private Matrix completeGradientMatrix, completeTextGradientMatrix; private AnimatedTextView.AnimatedTextDrawable topText = new AnimatedTextView.AnimatedTextDrawable(false, true, true); private AnimatedTextView.AnimatedTextDrawable bottomText = new AnimatedTextView.AnimatedTextDrawable(false, true, true); private AnimatedTextView.AnimatedTextDrawable topCompleteText = new AnimatedTextView.AnimatedTextDrawable(false, true, true); private AnimatedTextView.AnimatedTextDrawable bottomCompleteText = new AnimatedTextView.AnimatedTextDrawable(false, true, true); private StarParticlesView.Drawable completeDrawable; private static long particlesStart = -1; class Sector { Paint particlePaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); { particlePaint.setColor(0xFFFFFFFF); } Bitmap particle; float angleCenter, angleSize; AnimatedFloat angleCenterAnimated = new AnimatedFloat(CacheChart.this, 650, CubicBezierInterpolator.EASE_OUT_QUINT); AnimatedFloat angleSizeAnimated = new AnimatedFloat(CacheChart.this, 650, CubicBezierInterpolator.EASE_OUT_QUINT); float textAlpha; AnimatedFloat textAlphaAnimated = new AnimatedFloat(CacheChart.this, 0, 150, CubicBezierInterpolator.EASE_OUT); float textScale = 1; AnimatedFloat textScaleAnimated = new AnimatedFloat(CacheChart.this, 0, 150, CubicBezierInterpolator.EASE_OUT); AnimatedTextView.AnimatedTextDrawable text = new AnimatedTextView.AnimatedTextDrawable(false, true, true); float particlesAlpha; AnimatedFloat particlesAlphaAnimated = new AnimatedFloat(CacheChart.this, 0, 150, CubicBezierInterpolator.EASE_OUT); boolean selected; AnimatedFloat selectedAnimated = new AnimatedFloat(CacheChart.this, 0, 200, CubicBezierInterpolator.EASE_OUT_QUINT); { text.setTextColor(Color.WHITE); text.setAnimationProperties(.35f, 0, 200, CubicBezierInterpolator.EASE_OUT_QUINT); text.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); text.setTextSize(AndroidUtilities.dp(15)); text.setGravity(Gravity.CENTER); } Path path = new Path(); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); RectF pathBounds = new RectF(); Paint uncut = new Paint(Paint.ANTI_ALIAS_FLAG); Paint cut = new Paint(Paint.ANTI_ALIAS_FLAG); { cut.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); particlePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); } RectF rectF = new RectF(); int gradientWidth; RadialGradient gradient; Matrix gradientMatrix; private float lastAngleCenter, lastAngleSize, lastRounding, lastThickness, lastWidth, lastCx, lastCy; private void setupPath( RectF outerRect, RectF innerRect, float angleCenter, float angleSize, float rounding ) { rounding = Math.min(rounding, (outerRect.width() - innerRect.width()) / 4); rounding = Math.min(rounding, (float) (Math.PI * (angleSize / 180f) * (innerRect.width() / 2f))); float thickness = (outerRect.width() - innerRect.width()) / 2f; if (lastAngleCenter == angleCenter && lastAngleSize == angleSize && lastRounding == rounding && lastThickness == thickness && lastWidth == outerRect.width() && lastCx == outerRect.centerX() && lastCy == outerRect.centerY() ) { return; } lastAngleCenter = angleCenter; lastAngleSize = angleSize; lastRounding = rounding; lastThickness = thickness; lastWidth = outerRect.width(); lastCx = outerRect.centerX(); lastCy = outerRect.centerY(); float angleFrom = angleCenter - angleSize; float angleTo = angleCenter + angleSize; boolean hasRounding = rounding > 0; final float roundingOuterAngle = rounding / (float) (Math.PI * (outerRect.width() - rounding * 2)) * 360f; final float roundingInnerAngle = rounding / (float) (Math.PI * (innerRect.width() + rounding * 2)) * 360f + SEPARATOR_ANGLE / 4f * (angleSize > 175f ? 0 : 1); final float outerRadiusMinusRounding = outerRect.width() / 2 - rounding; final float innerRadiusPlusRounding = innerRect.width() / 2 + rounding; path.rewind(); if (angleTo - angleFrom < SEPARATOR_ANGLE / 4f) { return; } if (hasRounding) { setCircleBounds( roundingRect, outerRect.centerX() + outerRadiusMinusRounding * Math.cos(toRad(angleFrom + roundingOuterAngle)), outerRect.centerY() + outerRadiusMinusRounding * Math.sin(toRad(angleFrom + roundingOuterAngle)), rounding ); path.arcTo(roundingRect, angleFrom + roundingOuterAngle - 90, 90); } path.arcTo(outerRect, angleFrom + roundingOuterAngle, angleTo - angleFrom - roundingOuterAngle * 2); if (hasRounding) { setCircleBounds( roundingRect, outerRect.centerX() + outerRadiusMinusRounding * Math.cos(toRad(angleTo - roundingOuterAngle)), outerRect.centerY() + outerRadiusMinusRounding * Math.sin(toRad(angleTo - roundingOuterAngle)), rounding ); path.arcTo(roundingRect, angleTo - roundingOuterAngle, 90); setCircleBounds( roundingRect, innerRect.centerX() + innerRadiusPlusRounding * Math.cos(toRad(angleTo - roundingInnerAngle)), innerRect.centerY() + innerRadiusPlusRounding * Math.sin(toRad(angleTo - roundingInnerAngle)), rounding ); path.arcTo(roundingRect, angleTo - roundingInnerAngle + 90, 90); } path.arcTo(innerRect, angleTo - roundingInnerAngle, -(angleTo - angleFrom - roundingInnerAngle * 2)); if (hasRounding) { setCircleBounds( roundingRect, innerRect.centerX() + innerRadiusPlusRounding * Math.cos(toRad(angleFrom + roundingInnerAngle)), innerRect.centerY() + innerRadiusPlusRounding * Math.sin(toRad(angleFrom + roundingInnerAngle)), rounding ); path.arcTo(roundingRect, angleFrom + roundingInnerAngle + 180, 90); } path.close(); path.computeBounds(pathBounds, false); } private void setGradientBounds(float centerX, float centerY, float radius, float angle) { gradientMatrix.reset(); gradientMatrix.setTranslate(centerX, centerY); // gradientMatrix.preRotate(angle); gradient.setLocalMatrix(gradientMatrix); } private void drawParticles( Canvas canvas, float cx, float cy, float textX, float textY, float angleStart, float angleEnd, float innerRadius, float outerRadius, float textAlpha, float alpha ) { if (alpha <= 0 || !LiteMode.isEnabled(LiteMode.FLAGS_CHAT)) { return; } long now = System.currentTimeMillis(); float sqrt2 = (float) Math.sqrt(2); if (particlesStart < 0) { particlesStart = now; } float time = (now - particlesStart) / 10000f; if (particle != null) { int sz = particle.getWidth(); float szs = AndroidUtilities.dpf2(15) / sz; float stepangle = 7f; angleStart = angleStart % 360; angleEnd = angleEnd % 360; int fromAngle = (int) Math.floor(angleStart / stepangle); int toAngle = (int) Math.ceil(angleEnd / stepangle); for (int i = fromAngle; i <= toAngle; ++i) { float angle = i * stepangle; float t = (float) (((time + 100) * (1f + (Math.sin(angle * 2000) + 1) * .25f)) % 1); float r = lerp(innerRadius - sz * sqrt2, outerRadius + sz * sqrt2, t); float x = (float) (cx + r * Math.cos(toRad(angle))); float y = (float) (cy + r * Math.sin(toRad(angle))); float particleAlpha = .65f * alpha * (-1.75f * Math.abs(t - .5f) + 1) * (.25f * (float) (Math.sin(t * Math.PI) - 1) + 1) * lerp(1, Math.min(MathUtils.distance(x, y, textX, textY) / AndroidUtilities.dpf2(64), 1), textAlpha); particleAlpha = Math.max(0, Math.min(1, particleAlpha)); particlePaint.setAlpha((int) (0xFF * particleAlpha)); float s = szs * (float) (.75f * (.25f * (float) (Math.sin(t * Math.PI) - 1) + 1) * (.8f + (Math.sin(angle) + 1) * .25f)); canvas.save(); canvas.translate(x, y); canvas.scale(s, s); canvas.drawBitmap(particle, -(sz >> 1), -(sz >> 1), particlePaint); canvas.restore(); } } } void draw( Canvas canvas, RectF outerRect, RectF innerRect, float angleCenter, float angleSize, float rounding, float alpha, float textAlpha ) { float selected = selectedAnimated.set(this.selected ? 1 : 0); rectF.set(outerRect); rectF.inset(selected * -AndroidUtilities.dp(9), selected * -AndroidUtilities.dp(9)); float x = (float) (rectF.centerX() + Math.cos(toRad(angleCenter)) * (rectF.width() + innerRect.width()) / 4); float y = (float) (rectF.centerY() + Math.sin(toRad(angleCenter)) * (rectF.width() + innerRect.width()) / 4); float loading = textAlpha; textAlpha *= alpha * textAlphaAnimated.set(this.textAlpha); float particlesAlpha = particlesAlphaAnimated.set(this.particlesAlpha); paint.setAlpha((int) (0xFF * alpha)); if (angleSize * 2 >= 359f) { canvas.saveLayerAlpha(rectF, 0xFF, Canvas.ALL_SAVE_FLAG); canvas.drawCircle(rectF.centerX(), rectF.centerY(), rectF.width() / 2, uncut); canvas.drawRect(rectF, paint); drawParticles(canvas, rectF.centerX(), rectF.centerY(), x, y, 0, 359, innerRect.width() / 2f, rectF.width() / 2f, textAlpha, Math.max(0, loading / .75f - .75f) * particlesAlpha); canvas.drawCircle(innerRect.centerX(), innerRect.centerY(), innerRect.width() / 2, cut); canvas.restore(); } else { setupPath(rectF, innerRect, angleCenter, angleSize, rounding); setGradientBounds(rectF.centerX(), outerRect.centerY(), rectF.width() / 2, angleCenter); canvas.saveLayerAlpha(rectF, 0xFF, Canvas.ALL_SAVE_FLAG); canvas.drawPath(path, uncut); canvas.drawRect(rectF, paint); drawParticles(canvas, rectF.centerX(), rectF.centerY(), x, y, angleCenter - angleSize, angleCenter + angleSize, innerRect.width() / 2f, rectF.width() / 2f, textAlpha, Math.max(0, loading / .75f - .75f) * particlesAlpha); canvas.restore(); } float textScale = textScaleAnimated.set(this.textScale); setCircleBounds(roundingRect, x, y, 0); if (textScale != 1) { canvas.save(); canvas.scale(textScale, textScale, roundingRect.centerX(), roundingRect.centerY()); } text.setAlpha((int) (255 * textAlpha)); text.setBounds((int) roundingRect.left, (int) roundingRect.top, (int) roundingRect.right, (int) roundingRect.bottom); text.draw(canvas); if (textScale != 1) { canvas.restore(); } } } public CacheChart(Context context) { this(context, DEFAULT_SECTIONS_COUNT, DEFAULT_COLORS, TYPE_CACHE, DEFAULT_PARTICLES); } public CacheChart(Context context, int count, int[] colorKeys, int type, int[] particles) { super(context); setLayerType(LAYER_TYPE_HARDWARE, null); this.sectionsCount = count; this.colorKeys = colorKeys; this.particles = particles; this.type = type; this.svgParticles = type == TYPE_CACHE; this.sectors = new Sector[this.sectionsCount]; loadingBackgroundPaint.setStyle(Paint.Style.STROKE); loadingBackgroundPaint.setColor(Theme.getColor(Theme.key_listSelector)); completePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); completeGradient = new LinearGradient(0, 0, 0, AndroidUtilities.dp(200), new int[] { 0x006ED556, 0xFF6ED556, 0xFF41BA71, 0x0041BA71 }, new float[] { 0, .07f, .93f, 1 }, Shader.TileMode.CLAMP); completeTextGradient = new LinearGradient(0, 0, 0, AndroidUtilities.dp(200), new int[] { 0x006ED556, 0xFF6ED556, 0xFF41BA71, 0x0041BA71 }, new float[] { 0, .07f, .93f, 1 }, Shader.TileMode.CLAMP); completeGradientMatrix = new Matrix(); completeTextGradientMatrix = new Matrix(); completePaintStroke.setShader(completeGradient); completePaint.setShader(completeGradient); completePaintStroke.setStyle(Paint.Style.STROKE); completePaintStroke.setStrokeCap(Paint.Cap.ROUND); completePaintStroke.setStrokeJoin(Paint.Join.ROUND); topText.setAnimationProperties(.2f, 0, 450, CubicBezierInterpolator.EASE_OUT_QUINT); topText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); topText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); topText.setTextSize(AndroidUtilities.dp(32)); topText.setGravity(Gravity.CENTER); bottomText.setAnimationProperties(.6f, 0, 450, CubicBezierInterpolator.EASE_OUT_QUINT); bottomText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); bottomText.setTextSize(AndroidUtilities.dp(12)); bottomText.setGravity(Gravity.CENTER); topCompleteText.setAnimationProperties(.2f, 0, 450, CubicBezierInterpolator.EASE_OUT_QUINT); topCompleteText.getPaint().setShader(completeTextGradient); topCompleteText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); topCompleteText.setTextSize(AndroidUtilities.dp(32)); topCompleteText.setGravity(Gravity.CENTER); bottomCompleteText.setAnimationProperties(.6f, 0, 450, CubicBezierInterpolator.EASE_OUT_QUINT); bottomCompleteText.getPaint().setShader(completeTextGradient); bottomCompleteText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); bottomCompleteText.setTextSize(AndroidUtilities.dp(12)); bottomCompleteText.setGravity(Gravity.CENTER); for (int i = 0; i < sectors.length; ++i) { Sector sector = sectors[i] = new Sector(); final int color2 = Theme.blendOver(Theme.getColor(colorKeys[i]), 0x03000000); final int color1 = Theme.blendOver(Theme.getColor(colorKeys[i]), 0x30ffffff); sector.gradientWidth = AndroidUtilities.dp(50); sector.gradient = new RadialGradient(0, 0, dp(86), new int[]{ color1, color2 }, new float[] { .3f, 1 }, Shader.TileMode.CLAMP); sector.gradient.setLocalMatrix(sector.gradientMatrix = new Matrix()); sector.paint.setShader(sector.gradient); } } private boolean interceptTouch = true; public void setInterceptTouch(boolean value) { this.interceptTouch = value; } private boolean isAttached; @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); isAttached = true; for (int i = 0; i < sectors.length; ++i) { if (sectors[i].particle == null) { if (svgParticles) { sectors[i].particle = SvgHelper.getBitmap(particles[i], AndroidUtilities.dp(16), AndroidUtilities.dp(16), 0xffffffff); } else { sectors[i].particle = BitmapFactory.decodeResource(getContext().getResources(), particles[i]); } } } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); isAttached = false; for (int i = 0; i < sectors.length; ++i) { if (sectors[i].particle != null) { sectors[i].particle.recycle(); sectors[i].particle = null; } } } @Override public boolean dispatchTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); float r = MathUtils.distance(chartBounds.centerX(), chartBounds.centerY(), x, y); float a = (float) (Math.atan2(y - chartBounds.centerY(), x - chartBounds.centerX()) / Math.PI * 180f); if (a < 0) { a += 360; } int index = -1; if (r > chartInnerBounds.width() / 2 && r < chartBounds.width() / 2f + AndroidUtilities.dp(14)) { for (int i = 0; i < sectors.length; ++i) { if (a >= sectors[i].angleCenter - sectors[i].angleSize && a <= sectors[i].angleCenter + sectors[i].angleSize) { index = i; break; } } } if (event.getAction() == MotionEvent.ACTION_DOWN) { setSelected(index); if (index >= 0) { onSectionDown(index, index != -1); if (getParent() != null && interceptTouch) { getParent().requestDisallowInterceptTouchEvent(true); } } return true; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { onSectionDown(index, index != -1); setSelected(index); if (index != -1) { return true; } } else if (event.getAction() == MotionEvent.ACTION_UP) { boolean done = false; if (index != -1) { onSectionClick(index); done = true; } setSelected(-1); onSectionDown(index, false); if (done) { return true; } } else if (event.getAction() == MotionEvent.ACTION_CANCEL) { setSelected(-1); onSectionDown(index, false); } return super.dispatchTouchEvent(event); } protected void onSectionDown(int index, boolean down) { } protected void onSectionClick(int index) { } private int selectedIndex = -1; public void setSelected(int index) { if (index == selectedIndex) { return; } for (int i = 0; i < sectors.length; ++i) { if (index == i && sectors[i].angleSize <= 0) { index = -1; } sectors[i].selected = index == i; } selectedIndex = index; invalidate(); } private static final float SEPARATOR_ANGLE = 2; private int[] tempPercents; private float[] tempFloat; public static class SegmentSize { int index; public boolean selected; public long size; public static SegmentSize of(long size) { return of(size, true); } public static SegmentSize of(long size, boolean selected) { SegmentSize segment = new SegmentSize(); segment.size = size; segment.selected = selected; return segment; } } public void setSegments(long totalSize, boolean animated, SegmentSize ...segments) { if (segments == null || segments.length == 0) { loading = false; complete = totalSize == 0; if (!animated) { loadingFloat.set(loading ? 1 : 0, true); completeFloat.set(complete ? 1 : 0, true); } topCompleteText.setText(topText.getText(), false); topText.setText("0", animated); topCompleteText.setText("0", animated); bottomCompleteText.setText(bottomText.getText(), false); bottomText.setText("KB", animated); bottomCompleteText.setText("KB", animated); for (int i = 0; i < sectors.length; ++i) { sectors[i].textAlpha = 0; if (!animated) { sectors[i].textAlphaAnimated.set(0, true); } } invalidate(); return; } loading = false; if (!animated) { loadingFloat.set(0, true); } SpannableString percent = new SpannableString("%"); // percent.setSpan(new RelativeSizeSpan(0.733f), 0, percent.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); int segmentsCount = segments.length; long segmentsSum = 0; for (int i = 0; i < segments.length; ++i) { if (segments[i] == null) { segments[i] = new SegmentSize(); segments[i].size = 0; } segments[i].index = i; if (segments[i] != null && segments[i].selected) { segmentsSum += segments[i].size; } if (segments[i] == null || segments[i].size <= 0 || !segments[i].selected) { segmentsCount--; } } if (segmentsSum <= 0) { loading = false; complete = totalSize <= 0; if (!animated) { loadingFloat.set(loading ? 1 : 0, true); completeFloat.set(complete ? 1 : 0, true); } topCompleteText.setText(topText.getText(), false); topText.setText("0", animated); topCompleteText.setText("0", animated); bottomCompleteText.setText(bottomText.getText(), false); bottomText.setText("KB", animated); bottomCompleteText.setText("KB", animated); for (int i = 0; i < sectors.length; ++i) { sectors[i].textAlpha = 0; if (!animated) { sectors[i].textAlphaAnimated.set(0, true); } } invalidate(); return; } int underCount = 0; float minus = 0; for (int i = 0; i < segments.length; ++i) { float progress = segments[i] == null || !segments[i].selected ? 0 : (float) segments[i].size / segmentsSum; if (progress > 0 && progress < .02f) { underCount++; minus += progress; } } final int count = Math.min(segments.length, sectors.length); if (tempPercents == null || tempPercents.length != segments.length) { tempPercents = new int[segments.length]; } if (tempFloat == null || tempFloat.length != segments.length) { tempFloat = new float[segments.length]; } for (int i = 0; i < segments.length; ++i) { tempFloat[i] = segments[i] == null || !segments[i].selected ? 0 : segments[i].size / (float) segmentsSum; } AndroidUtilities.roundPercents(tempFloat, tempPercents); if (type == TYPE_CACHE) { // putting "other" section to being the first one Arrays.sort(segments, (a, b) -> Long.compare(a.size, b.size)); for (int i = 0; i <= segments.length; ++i) { if (segments[i].index == segments.length - 1) { int from = i, to = 0; SegmentSize temp = segments[to]; segments[to] = segments[from]; segments[from] = temp; break; } } } final float sum = 360 - SEPARATOR_ANGLE * (segmentsCount < 2 ? 0 : segmentsCount); float prev = 0; for (int index = 0, k = 0; index < segments.length; ++index) { int i = segments[index].index; float progress = segments[index] == null || !segments[index].selected ? 0 : (float) segments[index].size / segmentsSum; SpannableStringBuilder string = new SpannableStringBuilder(); string.append(String.format("%d", tempPercents[i])); string.append(percent); sectors[i].textAlpha = progress > .05 && progress < 1 ? 1f : 0f; sectors[i].textScale = progress < .08f || tempPercents[i] >= 100 ? .85f : 1f; sectors[i].particlesAlpha = 1; if (!animated) { sectors[i].textAlphaAnimated.set(sectors[i].textAlpha, true); sectors[i].textScaleAnimated.set(sectors[i].textScale, true); sectors[i].particlesAlphaAnimated.set(sectors[i].particlesAlpha, true); } if (sectors[i].textAlpha > 0) { sectors[i].text.setText(string, animated); } if (progress < .02f && progress > 0) { progress = .02f; } else { progress *= 1f - (.02f * underCount - minus); } float angleFrom = (prev * sum + k * SEPARATOR_ANGLE); float angleTo = angleFrom + progress * sum; if (progress <= 0) { sectors[i].angleCenter = (angleFrom + angleTo) / 2; sectors[i].angleSize = Math.abs(angleTo - angleFrom) / 2; sectors[i].textAlpha = 0; if (!animated) { sectors[i].angleCenterAnimated.set(sectors[i].angleCenter, true); sectors[i].angleSizeAnimated.set(sectors[i].angleSize, true); sectors[i].textAlphaAnimated.set(sectors[i].textAlpha, true); } continue; } sectors[i].angleCenter = (angleFrom + angleTo) / 2; sectors[i].angleSize = Math.abs(angleTo - angleFrom) / 2; if (!animated) { sectors[i].angleCenterAnimated.set(sectors[i].angleCenter, true); sectors[i].angleSizeAnimated.set(sectors[i].angleSize, true); } prev += progress; k++; } String[] fileSize = AndroidUtilities.formatFileSize(segmentsSum, true, true).split(" "); String top = fileSize.length > 0 ? fileSize[0] : ""; if (top.length() >= 4 && segmentsSum < 1024L * 1024L * 1024L) { top = top.split("\\.")[0]; } topText.setText(top, animated); bottomText.setText(fileSize.length > 1 ? fileSize[1] : "", animated); if (completeFloat.get() > 0) { topCompleteText.setText(topText.getText(), animated); bottomCompleteText.setText(bottomText.getText(), animated); } complete = false; if (!animated) { completeFloat.set(complete ? 1 : 0, true); } invalidate(); } private static float toRad(float angles) { return (float) (angles / 180f * Math.PI); } private static float toAngl(float rad) { return (float) (rad / Math.PI * 180f); } private static float lerpAngle(float a, float b, float f) { return (a + (((b - a + 360 + 180) % 360) - 180) * f + 360) % 360; } private static void setCircleBounds(RectF rect, float centerX, float centerY, float radius) { rect.set(centerX - radius, centerY - radius, centerX + radius, centerY + radius); } private static void setCircleBounds(RectF rect, double centerX, double centerY, float radius) { setCircleBounds(rect, (float) centerX, (float) centerY, radius); } private static Long start, loadedStart; @Override protected void dispatchDraw(Canvas canvas) { final float loading = loadingFloat.set(this.loading ? 1f : 0f); final float complete = completeFloat.set(this.complete ? 1f : 0f); chartBounds.set(chartMeasureBounds); final float minusDp = lerp(0, dpf2(padInsideDp()), complete); chartBounds.inset(minusDp, minusDp); chartInnerBounds.set(chartBounds); final float thickness = lerp(dpf2(38), dpf2(10), Math.max(loading, complete)); chartInnerBounds.inset(thickness, thickness); final float rounding = lerp(0, dp(60), loading); if (start == null) { start = System.currentTimeMillis(); } if (!this.loading && loadedStart == null) { loadedStart = System.currentTimeMillis(); } else if (this.loading && loadedStart != null) { loadedStart = null; } float loadingTime = ((loadedStart == null ? System.currentTimeMillis() : loadedStart) - start) * 0.6f; CircularProgressDrawable.getSegments(loadingTime % 5400, segmentsTmp); float minAngle = segmentsTmp[0], maxAngle = segmentsTmp[1]; if (loading > 0) { loadingBackgroundPaint.setStrokeWidth(thickness); int wasAlpha = loadingBackgroundPaint.getAlpha(); loadingBackgroundPaint.setAlpha((int) (wasAlpha * loading)); canvas.drawCircle(chartBounds.centerX(), chartBounds.centerY(), (chartBounds.width() - thickness) / 2, loadingBackgroundPaint); loadingBackgroundPaint.setAlpha(wasAlpha); } boolean wouldUpdate = loading > 0 || complete > 0; for (int i = 0; i < sectors.length; ++i) { Sector sector = sectors[i]; CircularProgressDrawable.getSegments((loadingTime + i * 80) % 5400, segmentsTmp); float angleFrom = Math.min(Math.max(segmentsTmp[0], minAngle), maxAngle); float angleTo = Math.min(Math.max(segmentsTmp[1], minAngle), maxAngle); if (loading >= 1 && angleFrom >= angleTo) { continue; } float angleCenter = (angleFrom + angleTo) / 2; float angleSize = Math.abs(angleTo - angleFrom) / 2; if (loading <= 0) { angleCenter = sector.angleCenterAnimated.set(sector.angleCenter); angleSize = sector.angleSizeAnimated.set(sector.angleSize); } else if (loading < 1) { float angleCenterSector = sector.angleCenterAnimated.set(sector.angleCenter); angleCenter = lerp(angleCenterSector + (float) Math.floor(maxAngle / 360) * 360, angleCenter, loading); angleSize = lerp(sector.angleSizeAnimated.set(sector.angleSize), angleSize, loading); } wouldUpdate = sector.angleCenterAnimated.isInProgress() || sector.angleSizeAnimated.isInProgress() || wouldUpdate; sector.draw(canvas, chartBounds, chartInnerBounds, angleCenter, angleSize, rounding, 1f - complete, 1f - loading); } if (type == TYPE_CACHE) { float textAlpha = (1f - loading) * (1f - complete); float topTextX = chartBounds.centerX(); float topTextY = chartBounds.centerY() - dpf2(5); wouldUpdate = drawAnimatedText(canvas, topText, topTextX, topTextY, 1f, textAlpha) || wouldUpdate; float bottomTextX = chartBounds.centerX(); float bottomTextY = chartBounds.centerY() + dpf2(22); wouldUpdate = drawAnimatedText(canvas, bottomText, bottomTextX, bottomTextY, 1f, textAlpha) || wouldUpdate; } else if (type == TYPE_NETWORK) { float textAlpha = 1f - loading; float topTextX = chartBounds.centerX() - AndroidUtilities.lerp(0, dpf2(4), complete); float topTextY = chartBounds.centerY() - AndroidUtilities.lerp(dpf2(5), 0, complete); float topTextScale = AndroidUtilities.lerp(1f, 2.25f, complete); wouldUpdate = drawAnimatedText(canvas, topCompleteText, topTextX, topTextY, topTextScale, textAlpha * complete) || wouldUpdate; wouldUpdate = drawAnimatedText(canvas, topText, topTextX, topTextY, topTextScale, textAlpha * (1f - complete)) || wouldUpdate; float bottomTextX = chartBounds.centerX() + AndroidUtilities.lerp(0, dpf2(26), complete); float bottomTextY = chartBounds.centerY() + AndroidUtilities.lerp(dpf2(22), -dpf2(18), complete); float bottomTextScale = AndroidUtilities.lerp(1f, 1.4f, complete); wouldUpdate = drawAnimatedText(canvas, bottomCompleteText, bottomTextX, bottomTextY, bottomTextScale, textAlpha * complete) || wouldUpdate; wouldUpdate = drawAnimatedText(canvas, bottomText, bottomTextX, bottomTextY, bottomTextScale, textAlpha * (1f - complete)) || wouldUpdate; } if (complete > 0) { boolean init = false; if (completeDrawable == null) { completeDrawable = new StarParticlesView.Drawable(25); completeDrawable.type = 100; completeDrawable.roundEffect = true; completeDrawable.useRotate = true; completeDrawable.useBlur = false; completeDrawable.checkBounds = true; completeDrawable.size1 = 18; completeDrawable.distributionAlgorithm = false; completeDrawable.excludeRadius = AndroidUtilities.dp(80); completeDrawable.k1 = completeDrawable.k2 = completeDrawable.k3 = .85f; completeDrawable.init(); init = true; } if (init || completePathBounds == null || !completePathBounds.equals(chartMeasureBounds)) { float d = Math.min(getMeasuredHeight(), Math.min(getMeasuredWidth(), AndroidUtilities.dp(150))); completeDrawable.rect.set(0, 0, d, d); completeDrawable.rect.offset((getMeasuredWidth() - completeDrawable.rect.width()) / 2, (getMeasuredHeight() - completeDrawable.rect.height()) / 2); completeDrawable.rect2.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); completeDrawable.resetPositions(); } canvas.saveLayerAlpha(0, 0, getWidth(), getHeight(), 255, Canvas.ALL_SAVE_FLAG); completeDrawable.onDraw(canvas, complete); completePaint.setAlpha((int) (0xFF * complete)); canvas.drawRect(0, 0, getWidth(), getHeight(), completePaint); canvas.restore(); completePaintStroke.setStrokeWidth(thickness); completePaintStroke.setAlpha((int) (0xFF * complete)); canvas.drawCircle(chartBounds.centerX(), chartBounds.centerY(), (chartBounds.width() - thickness) / 2, completePaintStroke); if (completePathBounds == null || !completePathBounds.equals(chartMeasureBounds)) { if (completePathBounds == null) { completePathBounds = new RectF(); } completePathBounds.set(chartMeasureBounds); completePath.rewind(); if (type == TYPE_CACHE) { completePath.moveTo(chartBounds.width() * .348f, chartBounds.height() * .538f); completePath.lineTo(chartBounds.width() * .447f, chartBounds.height() * .636f); completePath.lineTo(chartBounds.width() * .678f, chartBounds.height() * .402f); } else if (type == TYPE_NETWORK) { completePath.moveTo(chartBounds.width() * .2929f, chartBounds.height() * .4369f); completePath.lineTo(chartBounds.width() * .381f, chartBounds.height() * .35f); completePath.lineTo(chartBounds.width() * .4691f, chartBounds.height() * .4369f); completePath.moveTo(chartBounds.width() * .381f, chartBounds.height() * .35f); completePath.lineTo(chartBounds.width() * .381f, chartBounds.height() * .6548f); completePath.moveTo(chartBounds.width() * .5214f, chartBounds.height() * .5821f); completePath.lineTo(chartBounds.width() * .6095f, chartBounds.height() * .669f); completePath.lineTo(chartBounds.width() * .6976f, chartBounds.height() * .5821f); completePath.moveTo(chartBounds.width() * .6095f, chartBounds.height() * .669f); completePath.lineTo(chartBounds.width() * .6095f, chartBounds.height() * .3643f); } completePath.offset(chartBounds.left, chartBounds.top); } if (type == TYPE_CACHE) { completePaintStroke.setStrokeWidth(dpf2(10)); canvas.drawPath(completePath, completePaintStroke); } } if ((wouldUpdate || true) && isAttached) { invalidate(); } } private boolean drawAnimatedText(Canvas canvas, AnimatedTextView.AnimatedTextDrawable textDrawable, float x, float y, float scale, float alpha) { if (alpha <= 0) { return false; } textDrawable.setAlpha((int) (0xFF * alpha)); textDrawable.setBounds(0, 0, 0, 0); canvas.save(); canvas.translate(x, y); canvas.scale(scale, scale); textDrawable.draw(canvas); canvas.restore(); return textDrawable.isAnimating(); } protected int heightDp() { return 200; } protected int padInsideDp() { return 0; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int width = MeasureSpec.getSize(widthMeasureSpec); final int height = dp(heightDp()); final int d = dp(172); chartMeasureBounds.set( (width - d) / 2f, (height - d) / 2f, (width + d) / 2f, (height + d) / 2f ); completeGradientMatrix.reset(); completeGradientMatrix.setTranslate(chartMeasureBounds.left, 0); completeGradient.setLocalMatrix(completeGradientMatrix); completeTextGradientMatrix.reset(); completeTextGradientMatrix.setTranslate(chartMeasureBounds.left, -chartMeasureBounds.centerY()); completeTextGradient.setLocalMatrix(completeTextGradientMatrix); if (completeDrawable != null) { completeDrawable.rect.set(0, 0, AndroidUtilities.dp(140), AndroidUtilities.dp(140)); completeDrawable.rect.offset((getMeasuredWidth() - completeDrawable.rect.width()) / 2, (getMeasuredHeight() - completeDrawable.rect.height()) / 2); completeDrawable.rect2.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); completeDrawable.resetPositions(); } super.onMeasure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY) ); } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); requestLayout(); } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Components/CacheChart.java
2,155
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2024, Arnaud Roques * * This translation is distributed under the same Licence as the original C program. * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 smetana.core; import static smetana.core.Macro.ARR_TYPE_BOX; import static smetana.core.Macro.ARR_TYPE_CROW; import static smetana.core.Macro.ARR_TYPE_CURVE; import static smetana.core.Macro.ARR_TYPE_DIAMOND; import static smetana.core.Macro.ARR_TYPE_DOT; import static smetana.core.Macro.ARR_TYPE_GAP; import static smetana.core.Macro.ARR_TYPE_NORM; import static smetana.core.Macro.ARR_TYPE_TEE; import java.util.HashMap; import java.util.Map; import com.plantuml.api.cheerpj.WasmLog; import gen.lib.cdt.dttree__c; import gen.lib.cgraph.attr__c; import gen.lib.cgraph.edge__c; import gen.lib.cgraph.graph__c; import gen.lib.cgraph.id__c; import gen.lib.cgraph.mem__c; import gen.lib.cgraph.node__c; import gen.lib.cgraph.utils__c; import gen.lib.common.arrows__c; import gen.lib.common.shapes__c; import gen.lib.dotgen.dotsplines__c; import gen.lib.label.xlabels__c; import h.ST_Agdesc_s; import h.ST_Agedge_s; import h.ST_Agiddisc_s; import h.ST_Agmemdisc_s; import h.ST_Agnode_s; import h.ST_Agraph_s; import h.ST_Agsubnode_s; import h.ST_Agsym_s; import h.ST_Agtag_s; import h.ST_Pedge_t; import h.ST_arrowname_t; import h.ST_arrowtype_t; import h.ST_boxf; import h.ST_deque_t; import h.ST_dt_s; import h.ST_dtdisc_s; import h.ST_dtmethod_s; import h.ST_elist; import h.ST_nlist_t; import h.ST_pointf; import h.ST_pointnlink_t; import h.ST_polygon_t; import h.ST_port; import h.ST_shape_desc; import h.ST_shape_functions; import h.ST_splineInfo; import h.ST_textfont_t; import h.ST_tna_t; import h.ST_triangle_t; final public class Globals { public static Globals open() { WasmLog.log("Starting smetana instance"); return new Globals(); } public static void close() { WasmLog.log("Ending smetana instance"); } public final Map<Integer, CString> all = new HashMap<Integer, CString>(); public final ST_dtmethod_s _Dttree = new ST_dtmethod_s(); public final ST_dtmethod_s Dttree = _Dttree; public final ST_dtmethod_s _Dtobag = new ST_dtmethod_s(); public final ST_dtmethod_s Dtobag = _Dtobag; public final ST_dtdisc_s AgDataDictDisc = new ST_dtdisc_s(); public final ST_Agdesc_s ProtoDesc = new ST_Agdesc_s(); public ST_Agraph_s ProtoGraph; public final ST_Agtag_s Tag = new ST_Agtag_s(); public final ST_dtdisc_s Ag_mainedge_seq_disc = new ST_dtdisc_s(); public final ST_dtdisc_s Ag_subedge_seq_disc = new ST_dtdisc_s(); public final ST_dtdisc_s Ag_subedge_id_disc = new ST_dtdisc_s(); public final ST_dtdisc_s Ag_subgraph_id_disc = new ST_dtdisc_s(); public final ST_Agiddisc_s AgIdDisc = new ST_Agiddisc_s(); public final ST_Agmemdisc_s AgMemDisc = new ST_Agmemdisc_s(); public final ST_dtdisc_s Ag_subnode_id_disc = new ST_dtdisc_s(); public final ST_dtdisc_s Ag_subnode_seq_disc = new ST_dtdisc_s(); public int HTML_BIT; public int CNT_BITS; public final ST_dtdisc_s Refstrdisc = new ST_dtdisc_s(); public final ST_dtdisc_s Hdisc = new ST_dtdisc_s(); public ST_dt_s Refdict_default; public ST_Agraph_s Ag_dictop_G; public final ST_arrowname_t Arrowsynonyms[] = new ST_arrowname_t[] { create_arrowname_t(null, 0) }; public final ST_arrowname_t Arrownames[] = new ST_arrowname_t[] { create_arrowname_t("normal", ARR_TYPE_NORM), create_arrowname_t("none", ARR_TYPE_GAP), create_arrowname_t(null, 0) }; public final ST_arrowname_t Arrowmods[] = new ST_arrowname_t[] { create_arrowname_t(null, 0) }; public final ST_arrowtype_t Arrowtypes[] = new ST_arrowtype_t[] { createArrowtypes(ARR_TYPE_NORM, 1.0, arrows__c.arrow_type_normal), createArrowtypes(ARR_TYPE_CROW, 1.0, arrows__c.arrow_type_crow), createArrowtypes(ARR_TYPE_TEE, 0.5, arrows__c.arrow_type_tee), createArrowtypes(ARR_TYPE_BOX, 1.0, arrows__c.arrow_type_box), createArrowtypes(ARR_TYPE_DIAMOND, 1.2, arrows__c.arrow_type_diamond), createArrowtypes(ARR_TYPE_DOT, 0.8, arrows__c.arrow_type_dot), createArrowtypes(ARR_TYPE_CURVE, 1.0, arrows__c.arrow_type_curve), createArrowtypes(ARR_TYPE_GAP, 0.5, arrows__c.arrow_type_gap), createArrowtypes(0, 0.0, null) }; public __ptr__ Show_boxes; public int CL_type; public boolean Concentrate; public int MaxIter; public int State; public int EdgeLabelsDone; public double Initial_dist; public ST_Agsym_s G_activepencolor, G_activefillcolor, G_selectedpencolor, G_selectedfillcolor, G_visitedpencolor, G_visitedfillcolor, G_deletedpencolor, G_deletedfillcolor, G_ordering, G_peripheries, G_penwidth, G_gradientangle, G_margin; public ST_Agsym_s N_height, N_width, N_shape, N_color, N_fillcolor, N_activepencolor, N_activefillcolor, N_selectedpencolor, N_selectedfillcolor, N_visitedpencolor, N_visitedfillcolor, N_deletedpencolor, N_deletedfillcolor, N_fontsize, N_fontname, N_fontcolor, N_margin, N_label, N_xlabel, N_nojustify, N_style, N_showboxes, N_sides, N_peripheries, N_ordering, N_orientation, N_skew, N_distortion, N_fixed, N_imagescale, N_layer, N_group, N_comment, N_vertices, N_z, N_penwidth, N_gradientangle; public ST_Agsym_s E_weight, E_minlen, E_color, E_fillcolor, E_activepencolor, E_activefillcolor, E_selectedpencolor, E_selectedfillcolor, E_visitedpencolor, E_visitedfillcolor, E_deletedpencolor, E_deletedfillcolor, E_fontsize, E_fontname, E_fontcolor, E_label, E_xlabel, E_dir, E_style, E_decorate, E_showboxes, E_arrowsz, E_constr, E_layer, E_comment, E_label_float, E_samehead, E_sametail, E_arrowhead, E_arrowtail, E_headlabel, E_taillabel, E_labelfontsize, E_labelfontname, E_labelfontcolor, E_labeldistance, E_labelangle, E_tailclip, E_headclip, E_penwidth; public int N_nodes, N_edges; public int Minrank, Maxrank; public int S_i; public int Search_size; public final ST_nlist_t Tree_node = new ST_nlist_t(); public final ST_elist Tree_edge = new ST_elist(); public ST_Agedge_s Enter; public int Low, Lim, Slack; public int Rankdir; public boolean Flip; public final ST_pointf Offset = new ST_pointf(); public int nedges, nboxes; public int routeinit; public CArray<ST_pointf> ps; public int maxpn; public CArray<ST_pointf> polypoints; public int polypointn; public CArray<ST_Pedge_t> edges; public int edgen; public final ST_boxf[] boxes = ST_boxf.malloc(1000); public int MinQuit; public double Convergence; public ST_Agraph_s Root; public int GlobalMinRank, GlobalMaxRank; public boolean ReMincross; public CArrayOfStar<ST_Agedge_s> TE_list; public int TI_list[]; public ST_Agnode_s Last_node_decomp; public ST_Agnode_s Last_node_rank; public char Cmark; public int trin, tril; public CArray<ST_triangle_t> tris; public int pnln, pnll; public ST_pointnlink_t pnls[]; public ST_pointnlink_t pnlps[]; public final ST_port Center = new ST_port(); public final ST_polygon_t p_ellipse = new ST_polygon_t(); public final ST_polygon_t p_box = new ST_polygon_t(); public final ST_shape_functions poly_fns = new ST_shape_functions(); public final ST_shape_functions record_fns = new ST_shape_functions(); public CArray<ST_tna_t> tnas; public int tnan; public final ST_shape_desc Shapes[] = { __Shapes__("box", poly_fns, p_box), __Shapes__("ellipse", poly_fns, p_ellipse), __Shapes__("record", record_fns, null), __Shapes__(null, null, null) }; public final ST_dtdisc_s Ag_mainedge_id_disc = new ST_dtdisc_s(); public final ST_deque_t dq = new ST_deque_t(); public final ST_Agdesc_s Agdirected = new ST_Agdesc_s(); public final ST_splineInfo sinfo = new ST_splineInfo(); public ST_Agnode_s lastn; /* last node argument */ public ST_polygon_t poly; public int last, outp, sides; public final ST_pointf O = new ST_pointf(); /* point (0,0) */ public CArray<ST_pointf> vertex; public double xsize, ysize, scalex, scaley, box_URx, box_URy; public final ST_textfont_t tf = new ST_textfont_t(); public CArray<ST_pointf> pointfs; public CArray<ST_pointf> pointfs2; public int numpts; public int numpts2; public int[] Count; public int C; public int ctr = 1; public final ST_Agsubnode_s template = new ST_Agsubnode_s(); public final ST_Agnode_s dummy = new ST_Agnode_s(); public ST_Agraph_s G_ns; public ST_Agraph_s G_decomp; public int opl; public int opn_route; public int opn_shortest; public CArray<ST_pointf> ops_route; public CArray<ST_pointf> ops_shortest; public CString reclblp; public int isz; public CArray<ST_pointf> ispline; private ST_shape_desc __Shapes__(String s, ST_shape_functions shape_functions, ST_polygon_t polygon) { ST_shape_desc result = new ST_shape_desc(); result.name = s == null ? null : new CString(s); result.fns = shape_functions; result.polygon = polygon; return result; } private final static ST_arrowtype_t createArrowtypes(int type, double lenfact, CFunction function) { final ST_arrowtype_t result = new ST_arrowtype_t(); result.type = type; result.lenfact = lenfact; result.gen = function; return result; } private final static ST_arrowname_t create_arrowname_t(String name, int type) { final ST_arrowname_t result = new ST_arrowname_t(); result.name = name == null ? null : new CString(name); result.type = type; return result; } private Globals() { _Dttree.searchf = dttree__c.dttree; _Dttree.type = Macro.DT_OSET; _Dtobag.searchf = dttree__c.dttree; _Dtobag.type = Macro.DT_OBAG; AgDataDictDisc.key = FieldOffset.name; AgDataDictDisc.size = -1; AgDataDictDisc.link = FieldOffset.link; AgDataDictDisc.makef = null; AgDataDictDisc.freef = attr__c.freesym; AgDataDictDisc.comparf = null; AgDataDictDisc.hashf = null; ProtoDesc.directed = 1; ProtoDesc.strict = 0; ProtoDesc.no_loop = 1; ProtoDesc.maingraph = 0; ProtoDesc.flatlock = 1; ProtoDesc.no_write = 1; Ag_mainedge_seq_disc.key = FieldOffset.zero; Ag_mainedge_seq_disc.size = 0; Ag_mainedge_seq_disc.link = FieldOffset.seq_link; // seq_link is the third // field in Agedge_t Ag_mainedge_seq_disc.makef = null; Ag_mainedge_seq_disc.freef = null; Ag_mainedge_seq_disc.comparf = edge__c.agedgeseqcmpf; Ag_mainedge_seq_disc.hashf = null; Ag_mainedge_seq_disc.memoryf = utils__c.agdictobjmem; Ag_mainedge_seq_disc.eventf = null; Ag_subedge_seq_disc.key = FieldOffset.zero; Ag_subedge_seq_disc.size = 0; Ag_subedge_seq_disc.link = FieldOffset.externalHolder; Ag_subedge_seq_disc.makef = null; Ag_subedge_seq_disc.freef = null; Ag_subedge_seq_disc.comparf = edge__c.agedgeseqcmpf; Ag_subedge_seq_disc.hashf = null; Ag_subedge_seq_disc.memoryf = utils__c.agdictobjmem; Ag_subedge_seq_disc.eventf = null; Ag_subedge_id_disc.key = FieldOffset.zero; Ag_subedge_id_disc.size = 0; Ag_subedge_id_disc.link = FieldOffset.externalHolder; Ag_subedge_id_disc.makef = null; Ag_subedge_id_disc.freef = null; Ag_subedge_id_disc.comparf = edge__c.agedgeidcmpf; Ag_subedge_id_disc.hashf = null; Ag_subedge_id_disc.memoryf = utils__c.agdictobjmem; Ag_subedge_id_disc.eventf = null; Ag_subgraph_id_disc.key = FieldOffset.zero; Ag_subgraph_id_disc.size = 0; Ag_subgraph_id_disc.link = FieldOffset.link; // link is the third field in // Agraph_t Ag_subgraph_id_disc.makef = null; Ag_subgraph_id_disc.freef = null; Ag_subgraph_id_disc.comparf = graph__c.agraphidcmpf; Ag_subgraph_id_disc.hashf = null; Ag_subgraph_id_disc.memoryf = utils__c.agdictobjmem; Ag_subgraph_id_disc.eventf = null; AgIdDisc.open = id__c.idopen; AgIdDisc.map = id__c.idmap; AgIdDisc.alloc = id__c.idalloc; AgIdDisc.free = id__c.idfree; AgIdDisc.print = id__c.idprint; AgIdDisc.close = id__c.idclose; AgIdDisc.idregister = id__c.idregister; AgMemDisc.open = mem__c.memopen; AgMemDisc.alloc = mem__c.memalloc; AgMemDisc.resize = mem__c.memresize; AgMemDisc.free = mem__c.memfree; AgMemDisc.close = null; Ag_subnode_id_disc.key = FieldOffset.zero; Ag_subnode_id_disc.size = 0; Ag_subnode_id_disc.link = FieldOffset.id_link; // id_link is the second // field in Agsubnode_t Ag_subnode_id_disc.makef = null; Ag_subnode_id_disc.freef = null; Ag_subnode_id_disc.comparf = node__c.agsubnodeidcmpf; Ag_subnode_id_disc.hashf = null; Ag_subnode_id_disc.memoryf = utils__c.agdictobjmem; Ag_subnode_id_disc.eventf = null; Ag_subnode_seq_disc.key = FieldOffset.zero; Ag_subnode_seq_disc.size = 0; Ag_subnode_seq_disc.link = FieldOffset.seq_link; // link is the first // field in // Agsubnode_t Ag_subnode_seq_disc.makef = null; Ag_subnode_seq_disc.freef = node__c.free_subnode; Ag_subnode_seq_disc.comparf = node__c.agsubnodeseqcmpf; Ag_subnode_seq_disc.hashf = null; Ag_subnode_seq_disc.memoryf = utils__c.agdictobjmem; Ag_subnode_seq_disc.eventf = null; Refstrdisc.key = FieldOffset.s; // *s is the third field in refstr_t Refstrdisc.size = -1; Refstrdisc.link = FieldOffset.zero; Refstrdisc.makef = null; Refstrdisc.freef = utils__c.agdictobjfree; Refstrdisc.comparf = null; Refstrdisc.hashf = null; Refstrdisc.memoryf = utils__c.agdictobjmem; Refstrdisc.eventf = null; Hdisc.key = FieldOffset.key; Hdisc.size = 4; Hdisc.link = FieldOffset.externalHolder; Hdisc.makef = null; Hdisc.freef = null; Hdisc.comparf = xlabels__c.icompare; Hdisc.hashf = null; Hdisc.memoryf = null; Hdisc.eventf = null; Center.p.x = 0; Center.p.y = 0; Center.theta = -1; Center.bp = null; Center.defined = false; Center.constrained = false; Center.clip = true; Center.dyna = false; Center.order = 0; Center.side = 0; p_ellipse.regular = false; p_ellipse.peripheries = 1; p_ellipse.sides = 1; p_ellipse.orientation = 0.; p_ellipse.distortion = 0.; p_ellipse.skew = 0.; p_box.regular = false; p_box.peripheries = 1; p_box.sides = 4; p_box.orientation = 0.; p_box.distortion = 0.; p_box.skew = 0.; poly_fns.initfn = shapes__c.poly_init; poly_fns.freefn = shapes__c.poly_free; poly_fns.portfn = shapes__c.poly_port; poly_fns.insidefn = shapes__c.poly_inside; poly_fns.pboxfn = shapes__c.poly_path; poly_fns.codefn = shapes__c.poly_gencode; record_fns.initfn = shapes__c.record_init; record_fns.freefn = shapes__c.record_free; record_fns.portfn = shapes__c.record_port; record_fns.insidefn = shapes__c.record_inside; record_fns.pboxfn = shapes__c.record_path; record_fns.codefn = shapes__c.record_gencode; Ag_mainedge_id_disc.key = FieldOffset.zero; Ag_mainedge_id_disc.size = 0; Ag_mainedge_id_disc.link = FieldOffset.id_link; // id_link is the second // field in Agedge_t Ag_mainedge_id_disc.makef = null; Ag_mainedge_id_disc.freef = null; Ag_mainedge_id_disc.comparf = edge__c.agedgeidcmpf; Ag_mainedge_id_disc.hashf = null; Ag_mainedge_id_disc.memoryf = utils__c.agdictobjmem; Ag_mainedge_id_disc.eventf = null; Agdirected.directed = 1; Agdirected.strict = 0; Agdirected.no_loop = 0; Agdirected.maingraph = 1; sinfo.swapEnds = dotsplines__c.swap_ends_p; sinfo.splineMerge = dotsplines__c.spline_merge; ispline = null; isz = 0; } }
plantuml/plantuml
src/smetana/core/Globals.java
2,156
/* -*- 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
2,157
/* * Copyright 2010-2017 JetBrains s.r.o. * * 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.jetbrains.kotlin.resolve; import com.google.common.collect.Maps; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import kotlin.Unit; import kotlin.collections.CollectionsKt; import kotlin.jvm.functions.Function1; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.builtins.FunctionTypesKt; import org.jetbrains.kotlin.builtins.KotlinBuiltIns; import org.jetbrains.kotlin.config.LanguageFeature; import org.jetbrains.kotlin.config.LanguageVersionSettings; import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.impl.SyntheticFieldDescriptor; import org.jetbrains.kotlin.diagnostics.Errors; import org.jetbrains.kotlin.lexer.KtTokens; import org.jetbrains.kotlin.name.SpecialNames; import org.jetbrains.kotlin.psi.*; import org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt; import org.jetbrains.kotlin.resolve.calls.CallResolver; import org.jetbrains.kotlin.resolve.calls.components.InferenceSession; import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall; import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResults; import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo; import org.jetbrains.kotlin.resolve.calls.util.CallMaker; import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt; import org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil; import org.jetbrains.kotlin.resolve.multiplatform.ExpectedActualResolverKt; import org.jetbrains.kotlin.resolve.scopes.*; import org.jetbrains.kotlin.resolve.source.KotlinSourceElementKt; import org.jetbrains.kotlin.types.*; import org.jetbrains.kotlin.types.error.ErrorUtils; import org.jetbrains.kotlin.types.expressions.ExpressionTypingContext; import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices; import org.jetbrains.kotlin.types.expressions.PreliminaryDeclarationVisitor; import org.jetbrains.kotlin.types.expressions.ValueParameterResolver; import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryKt; import org.jetbrains.kotlin.util.Box; import org.jetbrains.kotlin.util.ReenteringLazyValueComputationException; import java.util.*; import static org.jetbrains.kotlin.config.LanguageFeature.AllowSealedInheritorsInDifferentFilesOfSamePackage; import static org.jetbrains.kotlin.config.LanguageFeature.TopLevelSealedInheritance; import static org.jetbrains.kotlin.diagnostics.Errors.*; import static org.jetbrains.kotlin.resolve.BindingContext.*; import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt.isEffectivelyExternal; import static org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE; public class BodyResolver { @NotNull private final Project project; @NotNull private final AnnotationChecker annotationChecker; @NotNull private final ExpressionTypingServices expressionTypingServices; @NotNull private final CallResolver callResolver; @NotNull private final ObservableBindingTrace trace; @NotNull private final ControlFlowAnalyzer controlFlowAnalyzer; @NotNull private final DeclarationsChecker declarationsChecker; @NotNull private final AnnotationResolver annotationResolver; @NotNull private final DelegatedPropertyResolver delegatedPropertyResolver; @NotNull private final AnalyzerExtensions analyzerExtensions; @NotNull private final ValueParameterResolver valueParameterResolver; @NotNull private final BodyResolveCache bodyResolveCache; @NotNull private final KotlinBuiltIns builtIns; @NotNull private final OverloadChecker overloadChecker; @NotNull private final LanguageVersionSettings languageVersionSettings; public BodyResolver( @NotNull Project project, @NotNull AnnotationResolver annotationResolver, @NotNull BodyResolveCache bodyResolveCache, @NotNull CallResolver callResolver, @NotNull ControlFlowAnalyzer controlFlowAnalyzer, @NotNull DeclarationsChecker declarationsChecker, @NotNull DelegatedPropertyResolver delegatedPropertyResolver, @NotNull ExpressionTypingServices expressionTypingServices, @NotNull AnalyzerExtensions analyzerExtensions, @NotNull BindingTrace trace, @NotNull ValueParameterResolver valueParameterResolver, @NotNull AnnotationChecker annotationChecker, @NotNull KotlinBuiltIns builtIns, @NotNull OverloadChecker overloadChecker, @NotNull LanguageVersionSettings languageVersionSettings ) { this.project = project; this.annotationResolver = annotationResolver; this.bodyResolveCache = bodyResolveCache; this.callResolver = callResolver; this.controlFlowAnalyzer = controlFlowAnalyzer; this.declarationsChecker = declarationsChecker; this.delegatedPropertyResolver = delegatedPropertyResolver; this.expressionTypingServices = expressionTypingServices; this.analyzerExtensions = analyzerExtensions; this.annotationChecker = annotationChecker; this.overloadChecker = overloadChecker; this.trace = new ObservableBindingTrace(trace); this.valueParameterResolver = valueParameterResolver; this.builtIns = builtIns; this.languageVersionSettings = languageVersionSettings; } private void resolveBehaviorDeclarationBodies(@NotNull BodiesResolveContext c) { resolveSuperTypeEntryLists(c); resolvePropertyDeclarationBodies(c); resolveAnonymousInitializers(c); resolvePrimaryConstructorParameters(c); resolveSecondaryConstructors(c); resolveFunctionBodies(c); if (!c.getTopDownAnalysisMode().isLocalDeclarations()) { computeDeferredTypes(); } } private void resolveSecondaryConstructors(@NotNull BodiesResolveContext c) { for (Map.Entry<KtSecondaryConstructor, ClassConstructorDescriptor> entry : c.getSecondaryConstructors().entrySet()) { LexicalScope declaringScope = c.getDeclaringScope(entry.getKey()); assert declaringScope != null : "Declaring scope should be registered before body resolve"; resolveSecondaryConstructorBody(c.getOuterDataFlowInfo(), trace, entry.getKey(), entry.getValue(), declaringScope, c.getLocalContext()); } if (c.getSecondaryConstructors().isEmpty()) return; Set<ConstructorDescriptor> visitedConstructors = new HashSet<>(); for (Map.Entry<KtSecondaryConstructor, ClassConstructorDescriptor> entry : c.getSecondaryConstructors().entrySet()) { checkCyclicConstructorDelegationCall(entry.getValue(), visitedConstructors); } } public void resolveSecondaryConstructorBody( @NotNull DataFlowInfo outerDataFlowInfo, @NotNull BindingTrace trace, @NotNull KtSecondaryConstructor constructor, @NotNull ClassConstructorDescriptor descriptor, @NotNull LexicalScope declaringScope, @Nullable ExpressionTypingContext localContext ) { ForceResolveUtil.forceResolveAllContents(descriptor.getAnnotations()); resolveFunctionBody( outerDataFlowInfo, trace, constructor, descriptor, declaringScope, headerInnerScope -> resolveSecondaryConstructorDelegationCall( outerDataFlowInfo, trace, headerInnerScope, constructor, descriptor, localContext != null ? localContext.inferenceSession : null ), scope -> new LexicalScopeImpl( scope, descriptor, scope.isOwnerDescriptorAccessibleByLabel(), scope.getImplicitReceiver(), scope.getContextReceiversGroup(), LexicalScopeKind.CONSTRUCTOR_HEADER ), localContext ); } @Nullable private DataFlowInfo resolveSecondaryConstructorDelegationCall( @NotNull DataFlowInfo outerDataFlowInfo, @NotNull BindingTrace trace, @NotNull LexicalScope scope, @NotNull KtSecondaryConstructor constructor, @NotNull ClassConstructorDescriptor descriptor, @Nullable InferenceSession inferenceSession ) { if (descriptor.isExpect() || isEffectivelyExternal(descriptor)) { // For expected and external classes, we do not resolve constructor delegation calls because they are prohibited return DataFlowInfo.Companion.getEMPTY(); } OverloadResolutionResults<?> results = callResolver.resolveConstructorDelegationCall( trace, scope, outerDataFlowInfo, descriptor, constructor.getDelegationCall(), inferenceSession); if (results != null && results.isSingleResult()) { ResolvedCall<? extends CallableDescriptor> resolvedCall = results.getResultingCall(); recordConstructorDelegationCall(trace, descriptor, resolvedCall); return resolvedCall.getDataFlowInfoForArguments().getResultInfo(); } return null; } private void checkCyclicConstructorDelegationCall( @NotNull ConstructorDescriptor constructorDescriptor, @NotNull Set<ConstructorDescriptor> visitedConstructors ) { if (visitedConstructors.contains(constructorDescriptor)) return; // if visit constructor that is already in current chain // such constructor is on cycle Set<ConstructorDescriptor> visitedInCurrentChain = new HashSet<>(); ConstructorDescriptor currentConstructorDescriptor = constructorDescriptor; while (true) { ProgressManager.checkCanceled(); visitedInCurrentChain.add(currentConstructorDescriptor); ConstructorDescriptor delegatedConstructorDescriptor = getDelegatedConstructor(currentConstructorDescriptor); if (delegatedConstructorDescriptor == null) break; // if next delegation call is super or primary constructor or already visited if (!constructorDescriptor.getContainingDeclaration().equals(delegatedConstructorDescriptor.getContainingDeclaration()) || delegatedConstructorDescriptor.isPrimary() || visitedConstructors.contains(delegatedConstructorDescriptor)) { break; } if (visitedInCurrentChain.contains(delegatedConstructorDescriptor)) { reportEachConstructorOnCycle(delegatedConstructorDescriptor); break; } currentConstructorDescriptor = delegatedConstructorDescriptor; } visitedConstructors.addAll(visitedInCurrentChain); } private void reportEachConstructorOnCycle(@NotNull ConstructorDescriptor startConstructor) { ConstructorDescriptor currentConstructor = startConstructor; do { PsiElement constructorToReport = DescriptorToSourceUtils.descriptorToDeclaration(currentConstructor); if (constructorToReport != null) { KtConstructorDelegationCall call = ((KtSecondaryConstructor) constructorToReport).getDelegationCall(); assert call.getCalleeExpression() != null : "Callee expression of delegation call should not be null on cycle as there should be explicit 'this' calls"; trace.report(CYCLIC_CONSTRUCTOR_DELEGATION_CALL.on(call.getCalleeExpression())); } currentConstructor = getDelegatedConstructor(currentConstructor); assert currentConstructor != null : "Delegated constructor should not be null in cycle"; } while (startConstructor != currentConstructor); } @Nullable private ConstructorDescriptor getDelegatedConstructor(@NotNull ConstructorDescriptor constructor) { ResolvedCall<ConstructorDescriptor> call = trace.get(CONSTRUCTOR_RESOLVED_DELEGATION_CALL, constructor); return call == null || !call.getStatus().isSuccess() ? null : call.getResultingDescriptor().getOriginal(); } public void resolveBodies(@NotNull BodiesResolveContext c) { resolveBehaviorDeclarationBodies(c); controlFlowAnalyzer.process(c); declarationsChecker.process(c); analyzerExtensions.process(c); } private void resolveSuperTypeEntryLists(@NotNull BodiesResolveContext c) { // TODO : Make sure the same thing is not initialized twice for (Map.Entry<KtClassOrObject, ClassDescriptorWithResolutionScopes> entry : c.getDeclaredClasses().entrySet()) { KtClassOrObject classOrObject = entry.getKey(); ClassDescriptorWithResolutionScopes descriptor = entry.getValue(); ExpressionTypingContext localContext = c.getLocalContext(); resolveSuperTypeEntryList(c.getOuterDataFlowInfo(), classOrObject, descriptor, descriptor.getUnsubstitutedPrimaryConstructor(), descriptor.getScopeForConstructorHeaderResolution(), descriptor.getScopeForMemberDeclarationResolution(), localContext != null ? localContext.inferenceSession : null); } } public void resolveSuperTypeEntryList( @NotNull DataFlowInfo outerDataFlowInfo, @NotNull KtClassOrObject ktClass, @NotNull ClassDescriptor descriptor, @Nullable ConstructorDescriptor primaryConstructor, @NotNull LexicalScope scopeForConstructorResolution, @NotNull LexicalScope scopeForMemberResolution, @Nullable InferenceSession inferenceSession ) { ProgressManager.checkCanceled(); LexicalScope scopeForConstructor = primaryConstructor == null ? null : FunctionDescriptorUtil.getFunctionInnerScope(scopeForConstructorResolution, primaryConstructor, trace, overloadChecker); if (primaryConstructor == null) { checkRedeclarationsInClassHeaderWithoutPrimaryConstructor(descriptor, scopeForConstructorResolution); } ExpressionTypingServices typeInferrer = expressionTypingServices; // TODO : flow Map<KtTypeReference, KotlinType> supertypes = Maps.newLinkedHashMap(); ResolvedCall<?>[] primaryConstructorDelegationCall = new ResolvedCall[1]; KtVisitorVoid visitor = new KtVisitorVoid() { private void recordSupertype(KtTypeReference typeReference, KotlinType supertype) { if (supertype == null) return; supertypes.put(typeReference, supertype); } @Override public void visitDelegatedSuperTypeEntry(@NotNull KtDelegatedSuperTypeEntry specifier) { if (descriptor.getKind() == ClassKind.INTERFACE) { trace.report(DELEGATION_IN_INTERFACE.on(specifier)); } KotlinType supertype = trace.getBindingContext().get(BindingContext.TYPE, specifier.getTypeReference()); recordSupertype(specifier.getTypeReference(), supertype); if (supertype != null) { DeclarationDescriptor declarationDescriptor = supertype.getConstructor().getDeclarationDescriptor(); if (declarationDescriptor instanceof ClassDescriptor) { ClassDescriptor classDescriptor = (ClassDescriptor) declarationDescriptor; if (classDescriptor.getKind() != ClassKind.INTERFACE) { trace.report(DELEGATION_NOT_TO_INTERFACE.on(specifier.getTypeReference())); } } } KtExpression delegateExpression = specifier.getDelegateExpression(); if (delegateExpression != null) { LexicalScope scope = scopeForConstructor == null ? scopeForMemberResolution : scopeForConstructor; KotlinType expectedType = supertype != null ? supertype : NO_EXPECTED_TYPE; typeInferrer.getType( scope, delegateExpression, expectedType, outerDataFlowInfo, inferenceSession != null ? inferenceSession : InferenceSession.Companion.getDefault(), trace ); } if (descriptor.isExpect()) { trace.report(IMPLEMENTATION_BY_DELEGATION_IN_EXPECT_CLASS.on(specifier)); } else if (primaryConstructor == null) { trace.report(UNSUPPORTED.on(specifier, "Delegation without primary constructor is not supported")); } } @Override public void visitSuperTypeCallEntry(@NotNull KtSuperTypeCallEntry call) { KtValueArgumentList valueArgumentList = call.getValueArgumentList(); PsiElement elementToMark = valueArgumentList == null ? call : valueArgumentList; if (descriptor.getKind() == ClassKind.INTERFACE) { trace.report(SUPERTYPE_INITIALIZED_IN_INTERFACE.on(elementToMark)); } if (descriptor.isExpect()) { trace.report(SUPERTYPE_INITIALIZED_IN_EXPECTED_CLASS.on(elementToMark)); } KtTypeReference typeReference = call.getTypeReference(); if (typeReference == null) return; if (primaryConstructor == null) { if (descriptor.getKind() != ClassKind.INTERFACE) { trace.report(SUPERTYPE_INITIALIZED_WITHOUT_PRIMARY_CONSTRUCTOR.on(call)); } recordSupertype(typeReference, trace.getBindingContext().get(BindingContext.TYPE, typeReference)); return; } OverloadResolutionResults<FunctionDescriptor> results = callResolver.resolveFunctionCall( trace, scopeForConstructor, CallMaker.makeConstructorCallWithoutTypeArguments(call), NO_EXPECTED_TYPE, outerDataFlowInfo, false, inferenceSession ); if (results.isSingleResult()) { KotlinType supertype = results.getResultingDescriptor().getReturnType(); recordSupertype(typeReference, supertype); ClassDescriptor classDescriptor = TypeUtils.getClassDescriptor(supertype); if (classDescriptor != null) { // allow only one delegating constructor if (primaryConstructorDelegationCall[0] == null) { primaryConstructorDelegationCall[0] = results.getResultingCall(); } else { primaryConstructorDelegationCall[0] = null; } } // Recording type info for callee to use later in JetObjectLiteralExpression trace.record(PROCESSED, call.getCalleeExpression(), true); trace.record(EXPRESSION_TYPE_INFO, call.getCalleeExpression(), TypeInfoFactoryKt.noTypeInfo(results.getResultingCall().getDataFlowInfoForArguments().getResultInfo())); } else { recordSupertype(typeReference, trace.getBindingContext().get(BindingContext.TYPE, typeReference)); } } @Override public void visitSuperTypeEntry(@NotNull KtSuperTypeEntry specifier) { KtTypeReference typeReference = specifier.getTypeReference(); KotlinType supertype = trace.getBindingContext().get(BindingContext.TYPE, typeReference); recordSupertype(typeReference, supertype); if (supertype == null) return; ClassDescriptor superClass = TypeUtils.getClassDescriptor(supertype); if (superClass == null) return; if (superClass.getKind().isSingleton()) { // A "singleton in supertype" diagnostic will be reported later return; } if (descriptor.getKind() != ClassKind.INTERFACE && descriptor.getUnsubstitutedPrimaryConstructor() != null && superClass.getKind() != ClassKind.INTERFACE && !descriptor.isExpect() && !isEffectivelyExternal(descriptor) && !ErrorUtils.isError(superClass) ) { trace.report(SUPERTYPE_NOT_INITIALIZED.on(specifier)); } } @Override public void visitKtElement(@NotNull KtElement element) { throw new UnsupportedOperationException(element.getText() + " : " + element); } }; if (ktClass instanceof KtEnumEntry && DescriptorUtils.isEnumEntry(descriptor) && ktClass.getSuperTypeListEntries().isEmpty()) { assert scopeForConstructor != null : "Scope for enum class constructor should be non-null: " + descriptor; resolveConstructorCallForEnumEntryWithoutInitializer( (KtEnumEntry) ktClass, descriptor, scopeForConstructor, outerDataFlowInfo, primaryConstructorDelegationCall, inferenceSession ); } for (KtSuperTypeListEntry delegationSpecifier : ktClass.getSuperTypeListEntries()) { ProgressManager.checkCanceled(); delegationSpecifier.accept(visitor); } if (DescriptorUtils.isAnnotationClass(descriptor) && ktClass.getSuperTypeList() != null) { trace.report(SUPERTYPES_FOR_ANNOTATION_CLASS.on(ktClass.getSuperTypeList())); } if (primaryConstructorDelegationCall[0] != null && primaryConstructor != null) { recordConstructorDelegationCall(trace, primaryConstructor, primaryConstructorDelegationCall[0]); } checkSupertypeList(descriptor, supertypes, ktClass); } private void checkRedeclarationsInClassHeaderWithoutPrimaryConstructor( @NotNull final ClassDescriptor descriptor, @NotNull LexicalScope scopeForConstructorResolution ) { // Initializing a scope will report errors if any. new LexicalScopeImpl( scopeForConstructorResolution, descriptor, true, null, Collections.emptyList(), LexicalScopeKind.CLASS_HEADER, new TraceBasedLocalRedeclarationChecker(trace, overloadChecker), new Function1<LexicalScopeImpl.InitializeHandler, Unit>() { @Override public Unit invoke(LexicalScopeImpl.InitializeHandler handler) { // If a class has no primary constructor, it still can have type parameters declared in header. for (TypeParameterDescriptor typeParameter : descriptor.getDeclaredTypeParameters()) { handler.addClassifierDescriptor(typeParameter); } return Unit.INSTANCE; } }); } private void resolveConstructorCallForEnumEntryWithoutInitializer( @NotNull KtEnumEntry ktEnumEntry, @NotNull ClassDescriptor enumEntryDescriptor, @NotNull LexicalScope scopeForConstructor, @NotNull DataFlowInfo outerDataFlowInfo, @NotNull ResolvedCall<?>[] primaryConstructorDelegationCall, @Nullable InferenceSession inferenceSession ) { assert enumEntryDescriptor.getKind() == ClassKind.ENUM_ENTRY : "Enum entry expected: " + enumEntryDescriptor; ClassDescriptor enumClassDescriptor = (ClassDescriptor) enumEntryDescriptor.getContainingDeclaration(); if (enumClassDescriptor.getKind() != ClassKind.ENUM_CLASS) return; if (enumClassDescriptor.isExpect()) return; List<ClassConstructorDescriptor> applicableConstructors = getConstructorForEmptyArgumentsList(enumClassDescriptor); if (applicableConstructors.size() != 1) { trace.report(ENUM_ENTRY_SHOULD_BE_INITIALIZED.on(ktEnumEntry)); return; } KtInitializerList ktInitializerList = new KtPsiFactory(project, false).createEnumEntryInitializerList(); KtSuperTypeCallEntry ktCallEntry = (KtSuperTypeCallEntry) ktInitializerList.getInitializers().get(0); Call call = CallMaker.makeConstructorCallWithoutTypeArguments(ktCallEntry); trace.record(BindingContext.TYPE, ktCallEntry.getTypeReference(), enumClassDescriptor.getDefaultType()); trace.record(BindingContext.CALL, ktEnumEntry, call); OverloadResolutionResults<FunctionDescriptor> results = callResolver.resolveFunctionCall( trace, scopeForConstructor, call, NO_EXPECTED_TYPE, outerDataFlowInfo, false, inferenceSession ); if (primaryConstructorDelegationCall[0] == null) { primaryConstructorDelegationCall[0] = results.getResultingCall(); } } @NotNull private static List<ClassConstructorDescriptor> getConstructorForEmptyArgumentsList(@NotNull ClassDescriptor descriptor) { return CollectionsKt.filter( descriptor.getConstructors(), (constructor) -> CollectionsKt.all( constructor.getValueParameters(), (parameter) -> parameter.declaresDefaultValue() || parameter.getVarargElementType() != null ) ); } // Returns a set of enum or sealed types of which supertypeOwner is an entry or a member @NotNull private Set<TypeConstructor> getAllowedFinalSupertypes( @NotNull ClassDescriptor descriptor, @NotNull Map<KtTypeReference, KotlinType> supertypes, @NotNull KtClassOrObject ktClassOrObject ) { Set<TypeConstructor> parentEnumOrSealed = Collections.emptySet(); if (ktClassOrObject instanceof KtEnumEntry) { parentEnumOrSealed = Collections.singleton(((ClassDescriptor) descriptor.getContainingDeclaration()).getTypeConstructor()); } else if (languageVersionSettings.supportsFeature(TopLevelSealedInheritance) && DescriptorUtils.isTopLevelDeclaration(descriptor)) { // TODO: improve diagnostic when top level sealed inheritance is disabled for (KotlinType supertype : supertypes.values()) { ClassifierDescriptor classifierDescriptor = supertype.getConstructor().getDeclarationDescriptor(); if (DescriptorUtils.isSealedClass(classifierDescriptor) && DescriptorUtils.isTopLevelDeclaration(classifierDescriptor)) { parentEnumOrSealed = Collections.singleton(classifierDescriptor.getTypeConstructor()); } } } else { ClassDescriptor currentDescriptor = descriptor; while (currentDescriptor.getContainingDeclaration() instanceof ClassDescriptor) { currentDescriptor = (ClassDescriptor) currentDescriptor.getContainingDeclaration(); if (DescriptorUtils.isSealedClass(currentDescriptor)) { if (parentEnumOrSealed.isEmpty()) { parentEnumOrSealed = new HashSet<>(); } parentEnumOrSealed.add(currentDescriptor.getTypeConstructor()); if (currentDescriptor.isExpect()) { List<MemberDescriptor> actualDescriptors = ExpectedActualResolverKt.findCompatibleActualsForExpected( currentDescriptor, DescriptorUtilsKt.getModule( currentDescriptor) ); for (MemberDescriptor actualDescriptor: actualDescriptors) { if (actualDescriptor instanceof TypeAliasDescriptor) { parentEnumOrSealed.add(((TypeAliasDescriptor) actualDescriptor).getExpandedType().getConstructor()); } } } } } } return parentEnumOrSealed; } @SuppressWarnings("unchecked") private static void recordConstructorDelegationCall( @NotNull BindingTrace trace, @NotNull ConstructorDescriptor constructor, @NotNull ResolvedCall<?> call ) { trace.record(CONSTRUCTOR_RESOLVED_DELEGATION_CALL, constructor, (ResolvedCall<ConstructorDescriptor>) call); } private void checkSupertypeList( @NotNull ClassDescriptor supertypeOwner, @NotNull Map<KtTypeReference, KotlinType> supertypes, @NotNull KtClassOrObject ktClassOrObject ) { Set<TypeConstructor> allowedFinalSupertypes = getAllowedFinalSupertypes(supertypeOwner, supertypes, ktClassOrObject); Set<TypeConstructor> typeConstructors = new HashSet<>(); boolean classAppeared = false; for (Map.Entry<KtTypeReference, KotlinType> entry : supertypes.entrySet()) { KtTypeReference typeReference = entry.getKey(); KotlinType supertype = entry.getValue(); KtTypeElement typeElement = typeReference.getTypeElement(); if (typeElement instanceof KtFunctionType) { for (KtParameter parameter : ((KtFunctionType) typeElement).getParameters()) { PsiElement nameIdentifier = parameter.getNameIdentifier(); if (nameIdentifier != null) { trace.report(Errors.UNSUPPORTED.on(nameIdentifier, "named parameter in function type in supertype position")); } } } boolean addSupertype = true; ClassDescriptor classDescriptor = TypeUtils.getClassDescriptor(supertype); if (classDescriptor != null) { if (ErrorUtils.isError(classDescriptor)) continue; if (FunctionTypesKt.isExtensionFunctionType(supertype) && !languageVersionSettings.supportsFeature(LanguageFeature.FunctionalTypeWithExtensionAsSupertype) ) { trace.report(SUPERTYPE_IS_EXTENSION_FUNCTION_TYPE.on(typeReference)); } else if (FunctionTypesKt.isSuspendExtensionFunctionType(supertype) && !languageVersionSettings.supportsFeature(LanguageFeature.FunctionalTypeWithExtensionAsSupertype) && languageVersionSettings.supportsFeature(LanguageFeature.SuspendFunctionAsSupertype)) { trace.report(SUPERTYPE_IS_SUSPEND_EXTENSION_FUNCTION_TYPE.on(typeReference)); } else if (FunctionTypesKt.isSuspendFunctionType(supertype) && !languageVersionSettings.supportsFeature(LanguageFeature.SuspendFunctionAsSupertype) ) { trace.report(SUPERTYPE_IS_SUSPEND_FUNCTION_TYPE.on(typeReference)); } else if (FunctionTypesKt.isKSuspendFunctionType(supertype) && !languageVersionSettings.supportsFeature(LanguageFeature.SuspendFunctionAsSupertype)) { trace.report(SUPERTYPE_IS_KSUSPEND_FUNCTION_TYPE.on(typeReference)); } if (classDescriptor.getKind() != ClassKind.INTERFACE) { if (supertypeOwner.getKind() == ClassKind.ENUM_CLASS) { trace.report(CLASS_IN_SUPERTYPE_FOR_ENUM.on(typeReference)); addSupertype = false; } else if (supertypeOwner.getKind() == ClassKind.INTERFACE && !classAppeared && !DynamicTypesKt.isDynamic(supertype) /* avoid duplicate diagnostics */) { trace.report(INTERFACE_WITH_SUPERCLASS.on(typeReference)); addSupertype = false; } else if (ktClassOrObject.hasModifier(KtTokens.DATA_KEYWORD) && !languageVersionSettings.supportsFeature(LanguageFeature.DataClassInheritance)) { trace.report(DATA_CLASS_CANNOT_HAVE_CLASS_SUPERTYPES.on(typeReference)); addSupertype = false; } else if (DescriptorUtils.isSubclass(classDescriptor, builtIns.getThrowable())) { if (!supertypeOwner.getDeclaredTypeParameters().isEmpty()) { trace.report(GENERIC_THROWABLE_SUBCLASS.on(ktClassOrObject.getTypeParameterList())); addSupertype = false; } else if (!supertypeOwner.getTypeConstructor().getParameters().isEmpty()) { if (languageVersionSettings .supportsFeature(LanguageFeature.ProhibitInnerClassesOfGenericClassExtendingThrowable)) { trace.report(INNER_CLASS_OF_GENERIC_THROWABLE_SUBCLASS.on(ktClassOrObject)); addSupertype = false; } else { trace.report(INNER_CLASS_OF_GENERIC_THROWABLE_SUBCLASS_WARNING.on(ktClassOrObject)); } } } if (classAppeared) { trace.report(MANY_CLASSES_IN_SUPERTYPE_LIST.on(typeReference)); } else { classAppeared = true; } } } else { trace.report(SUPERTYPE_NOT_A_CLASS_OR_INTERFACE.on(typeReference)); } TypeConstructor constructor = supertype.getConstructor(); if (addSupertype && !typeConstructors.add(constructor)) { trace.report(SUPERTYPE_APPEARS_TWICE.on(typeReference)); } if (classDescriptor == null) return; if (classDescriptor.getKind().isSingleton()) { if (!DescriptorUtils.isEnumEntry(classDescriptor)) { trace.report(SINGLETON_IN_SUPERTYPE.on(typeReference)); } } else if (!allowedFinalSupertypes.contains(constructor)) { if (DescriptorUtils.isSealedClass(classDescriptor)) { DeclarationDescriptor containingDescriptor = supertypeOwner.getContainingDeclaration(); while (containingDescriptor != null && containingDescriptor != classDescriptor) { containingDescriptor = containingDescriptor.getContainingDeclaration(); } if (containingDescriptor == null) { if ( !languageVersionSettings.supportsFeature(AllowSealedInheritorsInDifferentFilesOfSamePackage) || DescriptorUtils.isLocal(supertypeOwner) ) { trace.report(SEALED_SUPERTYPE.on(typeReference)); } } else { String declarationName; if (supertypeOwner.getName() == SpecialNames.NO_NAME_PROVIDED) { declarationName = "Anonymous object"; } else { declarationName = "Local class"; } trace.report(SEALED_SUPERTYPE_IN_LOCAL_CLASS.on(typeReference, declarationName, classDescriptor.getKind())); } } else if (ModalityUtilsKt.isFinalOrEnum(classDescriptor)) { trace.report(FINAL_SUPERTYPE.on(typeReference)); } else if (KotlinBuiltIns.isEnum(classDescriptor)) { trace.report(CLASS_CANNOT_BE_EXTENDED_DIRECTLY.on(typeReference, classDescriptor)); } } } } private void resolveAnonymousInitializers(@NotNull BodiesResolveContext c) { for (Map.Entry<KtAnonymousInitializer, ClassDescriptorWithResolutionScopes> entry : c.getAnonymousInitializers().entrySet()) { KtAnonymousInitializer initializer = entry.getKey(); ClassDescriptorWithResolutionScopes descriptor = entry.getValue(); ExpressionTypingContext context = c.getLocalContext(); resolveAnonymousInitializer(c.getOuterDataFlowInfo(), initializer, descriptor, context != null ? context.inferenceSession : null); } } public void resolveAnonymousInitializer( @NotNull DataFlowInfo outerDataFlowInfo, @NotNull KtAnonymousInitializer anonymousInitializer, @NotNull ClassDescriptorWithResolutionScopes classDescriptor, @Nullable InferenceSession inferenceSession ) { ProgressManager.checkCanceled(); LexicalScope scopeForInitializers = classDescriptor.getScopeForInitializerResolution(); KtExpression body = anonymousInitializer.getBody(); if (body != null) { PreliminaryDeclarationVisitor.Companion.createForDeclaration( (KtDeclaration) anonymousInitializer.getParent().getParent(), trace, languageVersionSettings); expressionTypingServices.getTypeInfo( scopeForInitializers, body, NO_EXPECTED_TYPE, outerDataFlowInfo, inferenceSession != null ? inferenceSession : InferenceSession.Companion.getDefault(), trace, /*isStatement = */true ); } processModifiersOnInitializer(anonymousInitializer, scopeForInitializers); if (classDescriptor.getConstructors().isEmpty()) { trace.report(ANONYMOUS_INITIALIZER_IN_INTERFACE.on(anonymousInitializer)); } if (classDescriptor.isExpect()) { trace.report(EXPECTED_DECLARATION_WITH_BODY.on(anonymousInitializer)); } } private void processModifiersOnInitializer(@NotNull KtModifierListOwner owner, @NotNull LexicalScope scope) { annotationChecker.check(owner, trace, null); ModifierCheckerCore.INSTANCE.check(owner, trace, null, languageVersionSettings); KtModifierList modifierList = owner.getModifierList(); if (modifierList == null) return; annotationResolver.resolveAnnotationsWithArguments(scope, modifierList, trace); } private void resolvePrimaryConstructorParameters(@NotNull BodiesResolveContext c) { for (Map.Entry<KtClassOrObject, ClassDescriptorWithResolutionScopes> entry : c.getDeclaredClasses().entrySet()) { KtClassOrObject klass = entry.getKey(); ClassDescriptorWithResolutionScopes classDescriptor = entry.getValue(); ConstructorDescriptor unsubstitutedPrimaryConstructor = classDescriptor.getUnsubstitutedPrimaryConstructor(); if (unsubstitutedPrimaryConstructor != null) { ForceResolveUtil.forceResolveAllContents(unsubstitutedPrimaryConstructor.getAnnotations()); ExpressionTypingContext localContext = c.getLocalContext(); LexicalScope parameterScope = getPrimaryConstructorParametersScope(classDescriptor.getScopeForConstructorHeaderResolution(), unsubstitutedPrimaryConstructor); valueParameterResolver.resolveValueParameters( klass.getPrimaryConstructorParameters(), unsubstitutedPrimaryConstructor.getValueParameters(), parameterScope, c.getOuterDataFlowInfo(), trace, localContext != null ? localContext.inferenceSession : null ); // Annotations on value parameter and constructor parameter could be splitted resolveConstructorPropertyDescriptors(klass); } } } private void resolveConstructorPropertyDescriptors(KtClassOrObject ktClassOrObject) { for (KtParameter parameter : ktClassOrObject.getPrimaryConstructorParameters()) { PropertyDescriptor descriptor = trace.getBindingContext().get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, parameter); if (descriptor != null) { ForceResolveUtil.forceResolveAllContents(descriptor.getAnnotations()); if (languageVersionSettings.supportsFeature(LanguageFeature.ProhibitErroneousExpressionsInAnnotationsWithUseSiteTargets)) { PropertyGetterDescriptor getterDescriptor = descriptor.getGetter(); if (getterDescriptor != null) { ForceResolveUtil.forceResolveAllContents(getterDescriptor.getAnnotations()); } PropertySetterDescriptor setterDescriptor = descriptor.getSetter(); if (setterDescriptor != null) { ForceResolveUtil.forceResolveAllContents(setterDescriptor.getAnnotations()); } } } } } private static LexicalScope getPrimaryConstructorParametersScope( LexicalScope originalScope, ConstructorDescriptor unsubstitutedPrimaryConstructor ) { return new LexicalScopeImpl(originalScope, unsubstitutedPrimaryConstructor, false, null, Collections.emptyList(), LexicalScopeKind.DEFAULT_VALUE, LocalRedeclarationChecker.DO_NOTHING.INSTANCE, handler -> { for (ValueParameterDescriptor valueParameter : unsubstitutedPrimaryConstructor.getValueParameters()) { handler.addVariableDescriptor(valueParameter); } return Unit.INSTANCE; }); } public void resolveProperty( @NotNull BodiesResolveContext c, @NotNull KtProperty property, @NotNull PropertyDescriptor propertyDescriptor ) { computeDeferredType(propertyDescriptor.getReturnType()); PreliminaryDeclarationVisitor.Companion.createForDeclaration(property, trace, languageVersionSettings); KtExpression initializer = property.getInitializer(); LexicalScope propertyHeaderScope = ScopeUtils.makeScopeForPropertyHeader(getScopeForProperty(c, property), propertyDescriptor); ExpressionTypingContext context = c.getLocalContext(); if (initializer != null) { resolvePropertyInitializer( c.getOuterDataFlowInfo(), property, propertyDescriptor, initializer, propertyHeaderScope, context != null ? context.inferenceSession : null ); } KtExpression delegateExpression = property.getDelegateExpression(); if (delegateExpression != null) { assert initializer == null : "Initializer should be null for delegated property : " + property.getText(); resolvePropertyDelegate( c.getOuterDataFlowInfo(), property, propertyDescriptor, delegateExpression, propertyHeaderScope, context != null ? context.inferenceSession : null ); } resolvePropertyAccessors(c, property, propertyDescriptor); ForceResolveUtil.forceResolveAllContents(propertyDescriptor.getAnnotations()); FieldDescriptor backingField = propertyDescriptor.getBackingField(); if (backingField != null) { ForceResolveUtil.forceResolveAllContents(backingField.getAnnotations()); } } private void resolvePropertyDeclarationBodies(@NotNull BodiesResolveContext c) { // Member properties Set<KtProperty> processed = new HashSet<>(); for (Map.Entry<KtClassOrObject, ClassDescriptorWithResolutionScopes> entry : c.getDeclaredClasses().entrySet()) { if (!(entry.getKey() instanceof KtClass)) continue; KtClass ktClass = (KtClass) entry.getKey(); ClassDescriptorWithResolutionScopes classDescriptor = entry.getValue(); for (KtProperty property : ktClass.getProperties()) { PropertyDescriptor propertyDescriptor = c.getProperties().get(property); assert propertyDescriptor != null; resolveProperty(c, property, propertyDescriptor); processed.add(property); } } // Top-level properties & properties of objects for (Map.Entry<KtProperty, PropertyDescriptor> entry : c.getProperties().entrySet()) { KtProperty property = entry.getKey(); if (processed.contains(property)) continue; PropertyDescriptor propertyDescriptor = entry.getValue(); resolveProperty(c, property, propertyDescriptor); } } private static LexicalScope makeScopeForPropertyAccessor( @NotNull BodiesResolveContext c, @NotNull KtPropertyAccessor accessor, @NotNull PropertyDescriptor descriptor ) { LexicalScope accessorDeclaringScope = c.getDeclaringScope(accessor); assert accessorDeclaringScope != null : "Scope for accessor " + accessor.getText() + " should exists"; LexicalScope headerScope = ScopeUtils.makeScopeForPropertyHeader(accessorDeclaringScope, descriptor); return new LexicalScopeImpl(headerScope, descriptor, true, descriptor.getExtensionReceiverParameter(), descriptor.getContextReceiverParameters(), LexicalScopeKind.PROPERTY_ACCESSOR_BODY); } private void resolvePropertyAccessors( @NotNull BodiesResolveContext c, @NotNull KtProperty property, @NotNull PropertyDescriptor propertyDescriptor ) { ObservableBindingTrace fieldAccessTrackingTrace = createFieldTrackingTrace(propertyDescriptor); KtPropertyAccessor getter = property.getGetter(); PropertyGetterDescriptor getterDescriptor = propertyDescriptor.getGetter(); boolean forceResolveAnnotations = languageVersionSettings.supportsFeature(LanguageFeature.ProhibitErroneousExpressionsInAnnotationsWithUseSiteTargets); if (getterDescriptor != null) { if (getter != null) { LexicalScope accessorScope = makeScopeForPropertyAccessor(c, getter, propertyDescriptor); resolveFunctionBody(c.getOuterDataFlowInfo(), fieldAccessTrackingTrace, getter, getterDescriptor, accessorScope, c.getLocalContext()); } if (getter != null || forceResolveAnnotations) { ForceResolveUtil.forceResolveAllContents(getterDescriptor.getAnnotations()); } } KtPropertyAccessor setter = property.getSetter(); PropertySetterDescriptor setterDescriptor = propertyDescriptor.getSetter(); if (setterDescriptor != null) { if (setter != null) { LexicalScope accessorScope = makeScopeForPropertyAccessor(c, setter, propertyDescriptor); resolveFunctionBody(c.getOuterDataFlowInfo(), fieldAccessTrackingTrace, setter, setterDescriptor, accessorScope, c.getLocalContext()); } if (setter != null || forceResolveAnnotations) { ForceResolveUtil.forceResolveAllContents(setterDescriptor.getAnnotations()); } } } private ObservableBindingTrace createFieldTrackingTrace(PropertyDescriptor propertyDescriptor) { return new ObservableBindingTrace(trace).addHandler( BindingContext.REFERENCE_TARGET, (slice, expression, descriptor) -> { if (expression instanceof KtSimpleNameExpression && descriptor instanceof SyntheticFieldDescriptor) { trace.record(BindingContext.BACKING_FIELD_REQUIRED, propertyDescriptor); } } ); } private void resolvePropertyDelegate( @NotNull DataFlowInfo outerDataFlowInfo, @NotNull KtProperty property, @NotNull PropertyDescriptor propertyDescriptor, @NotNull KtExpression delegateExpression, @NotNull LexicalScope propertyHeaderScope, @Nullable InferenceSession inferenceSession ) { delegatedPropertyResolver.resolvePropertyDelegate(outerDataFlowInfo, property, propertyDescriptor, delegateExpression, propertyHeaderScope, inferenceSession != null ? inferenceSession : InferenceSession.Companion.getDefault(), trace); } private void resolvePropertyInitializer( @NotNull DataFlowInfo outerDataFlowInfo, @NotNull KtProperty property, @NotNull PropertyDescriptor propertyDescriptor, @NotNull KtExpression initializer, @NotNull LexicalScope propertyHeader, @Nullable InferenceSession inferenceSession ) { LexicalScope propertyDeclarationInnerScope = ScopeUtils.makeScopeForPropertyInitializer(propertyHeader, propertyDescriptor); KotlinType expectedTypeForInitializer = property.getTypeReference() != null ? propertyDescriptor.getType() : NO_EXPECTED_TYPE; if (propertyDescriptor.getCompileTimeInitializer() == null) { expressionTypingServices.getType( propertyDeclarationInnerScope, initializer, expectedTypeForInitializer, outerDataFlowInfo, inferenceSession != null ? inferenceSession : InferenceSession.Companion.getDefault(), trace ); } } @NotNull private static LexicalScope getScopeForProperty(@NotNull BodiesResolveContext c, @NotNull KtProperty property) { LexicalScope scope = c.getDeclaringScope(property); assert scope != null : "Scope for property " + property.getText() + " should exists"; return scope; } private void resolveFunctionBodies(@NotNull BodiesResolveContext c) { for (Map.Entry<KtNamedFunction, SimpleFunctionDescriptor> entry : c.getFunctions().entrySet()) { KtNamedFunction declaration = entry.getKey(); LexicalScope scope = c.getDeclaringScope(declaration); assert scope != null : "Scope is null: " + PsiUtilsKt.getElementTextWithContext(declaration); if (!c.getTopDownAnalysisMode().isLocalDeclarations() && !(bodyResolveCache instanceof BodyResolveCache.ThrowException) && expressionTypingServices.getStatementFilter() != StatementFilter.NONE) { bodyResolveCache.resolveFunctionBody(declaration).addOwnDataTo(trace, true); } else { resolveFunctionBody(c.getOuterDataFlowInfo(), trace, declaration, entry.getValue(), scope, c.getLocalContext()); } } } public void resolveFunctionBody( @NotNull DataFlowInfo outerDataFlowInfo, @NotNull BindingTrace trace, @NotNull KtDeclarationWithBody function, @NotNull FunctionDescriptor functionDescriptor, @NotNull LexicalScope declaringScope, @Nullable ExpressionTypingContext localContext ) { computeDeferredType(functionDescriptor.getReturnType()); resolveFunctionBody(outerDataFlowInfo, trace, function, functionDescriptor, declaringScope, null, null, localContext); assert functionDescriptor.getReturnType() != null; } private void resolveFunctionBody( @NotNull DataFlowInfo outerDataFlowInfo, @NotNull BindingTrace trace, @NotNull KtDeclarationWithBody function, @NotNull FunctionDescriptor functionDescriptor, @NotNull LexicalScope scope, @Nullable Function1<LexicalScope, DataFlowInfo> beforeBlockBody, // Creates wrapper scope for header resolution if necessary (see resolveSecondaryConstructorBody) @Nullable Function1<LexicalScope, LexicalScope> headerScopeFactory, @Nullable ExpressionTypingContext localContext ) { ProgressManager.checkCanceled(); PreliminaryDeclarationVisitor.Companion.createForDeclaration(function, trace, languageVersionSettings); LexicalScope innerScope = FunctionDescriptorUtil.getFunctionInnerScope(scope, functionDescriptor, trace, overloadChecker); List<KtParameter> valueParameters = function.getValueParameters(); List<ValueParameterDescriptor> valueParameterDescriptors = functionDescriptor.getValueParameters(); LexicalScope headerScope = headerScopeFactory != null ? headerScopeFactory.invoke(innerScope) : innerScope; valueParameterResolver.resolveValueParameters( valueParameters, valueParameterDescriptors, headerScope, outerDataFlowInfo, trace, localContext != null ? localContext.inferenceSession : null ); // Synthetic "field" creation if (functionDescriptor instanceof PropertyAccessorDescriptor && functionDescriptor.getExtensionReceiverParameter() == null && functionDescriptor.getContextReceiverParameters().isEmpty()) { PropertyAccessorDescriptor accessorDescriptor = (PropertyAccessorDescriptor) functionDescriptor; KtProperty property = (KtProperty) function.getParent(); SourceElement propertySourceElement = KotlinSourceElementKt.toSourceElement(property); SyntheticFieldDescriptor fieldDescriptor = new SyntheticFieldDescriptor(accessorDescriptor, propertySourceElement); innerScope = new LexicalScopeImpl(innerScope, functionDescriptor, true, null, Collections.emptyList(), LexicalScopeKind.PROPERTY_ACCESSOR_BODY, LocalRedeclarationChecker.DO_NOTHING.INSTANCE, handler -> { handler.addVariableDescriptor(fieldDescriptor); return Unit.INSTANCE; }); // Check parameter name shadowing for (KtParameter parameter : function.getValueParameters()) { if (SyntheticFieldDescriptor.NAME.equals(parameter.getNameAsName())) { trace.report(Errors.ACCESSOR_PARAMETER_NAME_SHADOWING.on(parameter)); } } } DataFlowInfo dataFlowInfo = null; if (beforeBlockBody != null) { dataFlowInfo = beforeBlockBody.invoke(headerScope); } if (function.hasBody()) { expressionTypingServices.checkFunctionReturnType( innerScope, function, functionDescriptor, dataFlowInfo != null ? dataFlowInfo : outerDataFlowInfo, null, trace, localContext ); } assert functionDescriptor.getReturnType() != null; } public void resolveConstructorParameterDefaultValues( @NotNull DataFlowInfo outerDataFlowInfo, @NotNull BindingTrace trace, @NotNull KtPrimaryConstructor constructor, @NotNull ConstructorDescriptor constructorDescriptor, @NotNull LexicalScope declaringScope, @Nullable InferenceSession inferenceSession ) { List<KtParameter> valueParameters = constructor.getValueParameters(); List<ValueParameterDescriptor> valueParameterDescriptors = constructorDescriptor.getValueParameters(); LexicalScope scope = getPrimaryConstructorParametersScope(declaringScope, constructorDescriptor); valueParameterResolver.resolveValueParameters(valueParameters, valueParameterDescriptors, scope, outerDataFlowInfo, trace, inferenceSession); } public static void computeDeferredType(KotlinType type) { // handle type inference loop: function or property body contains a reference to itself // fun f() = { f() } // val x = x // type resolution must be started before body resolution if (type instanceof DeferredType) { DeferredType deferredType = (DeferredType) type; if (!deferredType.isComputed()) { deferredType.getDelegate(); } } } private void computeDeferredTypes() { Collection<Box<DeferredType>> deferredTypes = trace.getKeys(DEFERRED_TYPE); if (deferredTypes.isEmpty()) { return; } Deque<DeferredType> queue = new ArrayDeque<>(deferredTypes.size() + 1); trace.addHandler(DEFERRED_TYPE, (deferredTypeKeyDeferredTypeWritableSlice, key, value) -> queue.offerLast(key.getData())); for (Box<DeferredType> deferredType : deferredTypes) { queue.offerLast(deferredType.getData()); } while (!queue.isEmpty()) { DeferredType deferredType = queue.pollFirst(); if (!deferredType.isComputed()) { try { deferredType.getDelegate(); // to compute } catch (ReenteringLazyValueComputationException e) { // A problem should be reported while computing the type } } } } }
JetBrains/kotlin
compiler/frontend/src/org/jetbrains/kotlin/resolve/BodyResolver.java
2,158
/* * Copyright 2002-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.orm.jpa.support; import java.beans.PropertyDescriptor; import java.io.Serializable; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContextType; import jakarta.persistence.PersistenceProperty; import jakarta.persistence.PersistenceUnit; import jakarta.persistence.SynchronizationType; import org.springframework.aot.generate.GeneratedClass; import org.springframework.aot.generate.GeneratedMethod; import org.springframework.aot.generate.GeneratedMethods; import org.springframework.aot.generate.GenerationContext; import org.springframework.aot.generate.MethodReference.ArgumentCodeGenerator; import org.springframework.aot.hint.RuntimeHints; import org.springframework.beans.BeanUtils; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.InjectionMetadata; import org.springframework.beans.factory.annotation.InjectionMetadata.InjectedElement; import org.springframework.beans.factory.aot.BeanRegistrationAotContribution; import org.springframework.beans.factory.aot.BeanRegistrationAotProcessor; import org.springframework.beans.factory.aot.BeanRegistrationCode; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; import org.springframework.beans.factory.config.NamedBeanHolder; import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; import org.springframework.beans.factory.support.RegisteredBean; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.core.BridgeMethodResolver; import org.springframework.core.Ordered; import org.springframework.core.PriorityOrdered; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.javapoet.CodeBlock; import org.springframework.javapoet.MethodSpec; import org.springframework.jndi.JndiLocatorDelegate; import org.springframework.jndi.JndiTemplate; import org.springframework.lang.Nullable; import org.springframework.orm.jpa.EntityManagerFactoryInfo; import org.springframework.orm.jpa.EntityManagerFactoryUtils; import org.springframework.orm.jpa.EntityManagerProxy; import org.springframework.orm.jpa.ExtendedEntityManagerCreator; import org.springframework.orm.jpa.SharedEntityManagerCreator; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; /** * BeanPostProcessor that processes {@link jakarta.persistence.PersistenceUnit} * and {@link jakarta.persistence.PersistenceContext} annotations, for injection of * the corresponding JPA resources {@link jakarta.persistence.EntityManagerFactory} * and {@link jakarta.persistence.EntityManager}. Any such annotated fields or methods * in any Spring-managed object will automatically be injected. * * <p>This post-processor will inject sub-interfaces of {@code EntityManagerFactory} * and {@code EntityManager} if the annotated fields or methods are declared as such. * The actual type will be verified early, with the exception of a shared ("transactional") * {@code EntityManager} reference, where type mismatches might be detected as late * as on the first actual invocation. * * <p>Note: In the present implementation, PersistenceAnnotationBeanPostProcessor * only supports {@code @PersistenceUnit} and {@code @PersistenceContext} * with the "unitName" attribute, or no attribute at all (for the default unit). * If those annotations are present with the "name" attribute at the class level, * they will simply be ignored, since those only serve as deployment hint * (as per the Jakarta EE specification). * * <p>This post-processor can either obtain EntityManagerFactory beans defined * in the Spring application context (the default), or obtain EntityManagerFactory * references from JNDI ("persistence unit references"). In the bean case, * the persistence unit name will be matched against the actual deployed unit, * with the bean name used as fallback unit name if no deployed name found. * Typically, Spring's {@link org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean} * will be used for setting up such EntityManagerFactory beans. Alternatively, * such beans may also be obtained from JNDI, e.g. using the {@code jee:jndi-lookup} * XML configuration element (with the bean name matching the requested unit name). * In both cases, the post-processor definition will look as simple as this: * * <pre class="code"> * &lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/&gt;</pre> * * In the JNDI case, specify the corresponding JNDI names in this post-processor's * {@link #setPersistenceUnits "persistenceUnits" map}, typically with matching * {@code persistence-unit-ref} entries in the Jakarta EE deployment descriptor. * By default, those names are considered as resource references (according to the * Jakarta EE resource-ref convention), located underneath the "java:comp/env/" namespace. * For example: * * <pre class="code"> * &lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"&gt; * &lt;property name="persistenceUnits"&gt; * &lt;map/gt; * &lt;entry key="unit1" value="persistence/unit1"/&gt; * &lt;entry key="unit2" value="persistence/unit2"/&gt; * &lt;/map/gt; * &lt;/property&gt; * &lt;/bean&gt;</pre> * * In this case, the specified persistence units will always be resolved in JNDI * rather than as Spring-defined beans. The entire persistence unit deployment, * including the weaving of persistent classes, is then up to the Jakarta EE server. * Persistence contexts (i.e. EntityManager references) will be built based on * those server-provided EntityManagerFactory references, using Spring's own * transaction synchronization facilities for transactional EntityManager handling * (typically with Spring's {@code @Transactional} annotation for demarcation * and {@link org.springframework.transaction.jta.JtaTransactionManager} as backend). * * <p>If you prefer the Jakarta EE server's own EntityManager handling, specify entries * in this post-processor's {@link #setPersistenceContexts "persistenceContexts" map} * (or {@link #setExtendedPersistenceContexts "extendedPersistenceContexts" map}, * typically with matching {@code persistence-context-ref} entries in the * Jakarta EE deployment descriptor. For example: * * <pre class="code"> * &lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"&gt; * &lt;property name="persistenceContexts"&gt; * &lt;map/gt; * &lt;entry key="unit1" value="persistence/context1"/&gt; * &lt;entry key="unit2" value="persistence/context2"/&gt; * &lt;/map/gt; * &lt;/property&gt; * &lt;/bean&gt;</pre> * * If the application only obtains EntityManager references in the first place, * this is all you need to specify. If you need EntityManagerFactory references * as well, specify entries for both "persistenceUnits" and "persistenceContexts", * pointing to matching JNDI locations. * * <p><b>NOTE: In general, do not inject EXTENDED EntityManagers into STATELESS beans, * i.e. do not use {@code @PersistenceContext} with type {@code EXTENDED} in * Spring beans defined with scope 'singleton' (Spring's default scope).</b> * Extended EntityManagers are <i>not</i> thread-safe, hence they must not be used * in concurrently accessed beans (which Spring-managed singletons usually are). * * <p>Note: A default PersistenceAnnotationBeanPostProcessor will be registered * by the "context:annotation-config" and "context:component-scan" XML tags. * Remove or turn off the default annotation configuration there if you intend * to specify a custom PersistenceAnnotationBeanPostProcessor bean definition. * * @author Rod Johnson * @author Juergen Hoeller * @author Stephane Nicoll * @author Phillip Webb * @since 2.0 * @see jakarta.persistence.PersistenceUnit * @see jakarta.persistence.PersistenceContext */ @SuppressWarnings("serial") public class PersistenceAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, BeanRegistrationAotProcessor, PriorityOrdered, BeanFactoryAware, Serializable { @Nullable private Object jndiEnvironment; private boolean resourceRef = true; @Nullable private transient Map<String, String> persistenceUnits; @Nullable private transient Map<String, String> persistenceContexts; @Nullable private transient Map<String, String> extendedPersistenceContexts; private transient String defaultPersistenceUnitName = ""; private int order = Ordered.LOWEST_PRECEDENCE - 4; @Nullable private transient ListableBeanFactory beanFactory; private final transient Map<String, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap<>(256); private final Map<Object, EntityManager> extendedEntityManagersToClose = new ConcurrentHashMap<>(16); /** * Set the JNDI template to use for JNDI lookups. * @see org.springframework.jndi.JndiAccessor#setJndiTemplate */ public void setJndiTemplate(Object jndiTemplate) { this.jndiEnvironment = jndiTemplate; } /** * Set the JNDI environment to use for JNDI lookups. * @see org.springframework.jndi.JndiAccessor#setJndiEnvironment */ public void setJndiEnvironment(Properties jndiEnvironment) { this.jndiEnvironment = jndiEnvironment; } /** * Set whether the lookup occurs in a Jakarta EE container, i.e. if the prefix * "java:comp/env/" needs to be added if the JNDI name doesn't already * contain it. PersistenceAnnotationBeanPostProcessor's default is "true". * @see org.springframework.jndi.JndiLocatorSupport#setResourceRef */ public void setResourceRef(boolean resourceRef) { this.resourceRef = resourceRef; } /** * Specify the persistence units for EntityManagerFactory lookups, * as a Map from persistence unit name to persistence unit JNDI name * (which needs to resolve to an EntityManagerFactory instance). * <p>JNDI names specified here should refer to {@code persistence-unit-ref} * entries in the Jakarta EE deployment descriptor, matching the target persistence unit. * <p>In case of no unit name specified in the annotation, the specified value * for the {@link #setDefaultPersistenceUnitName default persistence unit} * will be taken (by default, the value mapped to the empty String), * or simply the single persistence unit if there is only one. * <p>This is mainly intended for use in a Jakarta EE environment, with all lookup * driven by the standard JPA annotations, and all EntityManagerFactory * references obtained from JNDI. No separate EntityManagerFactory bean * definitions are necessary in such a scenario. * <p>If no corresponding "persistenceContexts"/"extendedPersistenceContexts" * are specified, {@code @PersistenceContext} will be resolved to * EntityManagers built on top of the EntityManagerFactory defined here. * Note that those will be Spring-managed EntityManagers, which implement * transaction synchronization based on Spring's facilities. * If you prefer the Jakarta EE server's own EntityManager handling, * specify corresponding "persistenceContexts"/"extendedPersistenceContexts". */ public void setPersistenceUnits(Map<String, String> persistenceUnits) { this.persistenceUnits = persistenceUnits; } /** * Specify the <i>transactional</i> persistence contexts for EntityManager lookups, * as a Map from persistence unit name to persistence context JNDI name * (which needs to resolve to an EntityManager instance). * <p>JNDI names specified here should refer to {@code persistence-context-ref} * entries in the Jakarta EE deployment descriptors, matching the target persistence unit * and being set up with persistence context type {@code Transaction}. * <p>In case of no unit name specified in the annotation, the specified value * for the {@link #setDefaultPersistenceUnitName default persistence unit} * will be taken (by default, the value mapped to the empty String), * or simply the single persistence unit if there is only one. * <p>This is mainly intended for use in a Jakarta EE environment, with all * lookup driven by the standard JPA annotations, and all EntityManager * references obtained from JNDI. No separate EntityManagerFactory bean * definitions are necessary in such a scenario, and all EntityManager * handling is done by the Jakarta EE server itself. */ public void setPersistenceContexts(Map<String, String> persistenceContexts) { this.persistenceContexts = persistenceContexts; } /** * Specify the <i>extended</i> persistence contexts for EntityManager lookups, * as a Map from persistence unit name to persistence context JNDI name * (which needs to resolve to an EntityManager instance). * <p>JNDI names specified here should refer to {@code persistence-context-ref} * entries in the Jakarta EE deployment descriptors, matching the target persistence unit * and being set up with persistence context type {@code Extended}. * <p>In case of no unit name specified in the annotation, the specified value * for the {@link #setDefaultPersistenceUnitName default persistence unit} * will be taken (by default, the value mapped to the empty String), * or simply the single persistence unit if there is only one. * <p>This is mainly intended for use in a Jakarta EE environment, with all * lookup driven by the standard JPA annotations, and all EntityManager * references obtained from JNDI. No separate EntityManagerFactory bean * definitions are necessary in such a scenario, and all EntityManager * handling is done by the Jakarta EE server itself. */ public void setExtendedPersistenceContexts(Map<String, String> extendedPersistenceContexts) { this.extendedPersistenceContexts = extendedPersistenceContexts; } /** * Specify the default persistence unit name, to be used in case * of no unit name specified in an {@code @PersistenceUnit} / * {@code @PersistenceContext} annotation. * <p>This is mainly intended for lookups in the application context, * indicating the target persistence unit name (typically matching * the bean name), but also applies to lookups in the * {@link #setPersistenceUnits "persistenceUnits"} / * {@link #setPersistenceContexts "persistenceContexts"} / * {@link #setExtendedPersistenceContexts "extendedPersistenceContexts"} map, * avoiding the need for duplicated mappings for the empty String there. * <p>Default is to check for a single EntityManagerFactory bean * in the Spring application context, if any. If there are multiple * such factories, either specify this default persistence unit name * or explicitly refer to named persistence units in your annotations. */ public void setDefaultPersistenceUnitName(@Nullable String unitName) { this.defaultPersistenceUnitName = (unitName != null ? unitName : ""); } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } @Override public void setBeanFactory(BeanFactory beanFactory) { if (beanFactory instanceof ListableBeanFactory lbf) { this.beanFactory = lbf; } } @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { findInjectionMetadata(beanDefinition, beanType, beanName); } @Override public void resetBeanDefinition(String beanName) { this.injectionMetadataCache.remove(beanName); } @Override @Nullable public BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) { Class<?> beanClass = registeredBean.getBeanClass(); String beanName = registeredBean.getBeanName(); RootBeanDefinition beanDefinition = registeredBean.getMergedBeanDefinition(); InjectionMetadata metadata = findInjectionMetadata(beanDefinition, beanClass, beanName); Collection<InjectedElement> injectedElements = metadata.getInjectedElements( beanDefinition.getPropertyValues()); if (!CollectionUtils.isEmpty(injectedElements)) { return new AotContribution(beanClass, injectedElements); } return null; } private InjectionMetadata findInjectionMetadata(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { InjectionMetadata metadata = findPersistenceMetadata(beanName, beanType, null); metadata.checkConfigMembers(beanDefinition); return metadata; } @Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) { InjectionMetadata metadata = findPersistenceMetadata(beanName, bean.getClass(), pvs); try { metadata.inject(bean, beanName, pvs); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Injection of persistence dependencies failed", ex); } return pvs; } @Override public void postProcessBeforeDestruction(Object bean, String beanName) { EntityManager emToClose = this.extendedEntityManagersToClose.remove(bean); EntityManagerFactoryUtils.closeEntityManager(emToClose); } @Override public boolean requiresDestruction(Object bean) { return this.extendedEntityManagersToClose.containsKey(bean); } private InjectionMetadata findPersistenceMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) { // Fall back to class name as cache key, for backwards compatibility with custom callers. String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); // Quick check on the concurrent map first, with minimal locking. InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { synchronized (this.injectionMetadataCache) { metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { if (metadata != null) { metadata.clear(pvs); } metadata = buildPersistenceMetadata(clazz); this.injectionMetadataCache.put(cacheKey, metadata); } } } return metadata; } private InjectionMetadata buildPersistenceMetadata(Class<?> clazz) { if (!AnnotationUtils.isCandidateClass(clazz, Arrays.asList(PersistenceContext.class, PersistenceUnit.class))) { return InjectionMetadata.EMPTY; } List<InjectionMetadata.InjectedElement> elements = new ArrayList<>(); Class<?> targetClass = clazz; do { final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>(); ReflectionUtils.doWithLocalFields(targetClass, field -> { if (field.isAnnotationPresent(PersistenceContext.class) || field.isAnnotationPresent(PersistenceUnit.class)) { if (Modifier.isStatic(field.getModifiers())) { throw new IllegalStateException("Persistence annotations are not supported on static fields"); } currElements.add(new PersistenceElement(field, field, null)); } }); ReflectionUtils.doWithLocalMethods(targetClass, method -> { Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { return; } if ((bridgedMethod.isAnnotationPresent(PersistenceContext.class) || bridgedMethod.isAnnotationPresent(PersistenceUnit.class)) && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { if (Modifier.isStatic(method.getModifiers())) { throw new IllegalStateException("Persistence annotations are not supported on static methods"); } if (method.getParameterCount() != 1) { throw new IllegalStateException("Persistence annotation requires a single-arg method: " + method); } PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); currElements.add(new PersistenceElement(method, bridgedMethod, pd)); } }); elements.addAll(0, currElements); targetClass = targetClass.getSuperclass(); } while (targetClass != null && targetClass != Object.class); return InjectionMetadata.forElements(elements, clazz); } /** * Return a specified persistence unit for the given unit name, * as defined through the "persistenceUnits" map. * @param unitName the name of the persistence unit * @return the corresponding EntityManagerFactory, * or {@code null} if none found * @see #setPersistenceUnits */ @Nullable protected EntityManagerFactory getPersistenceUnit(@Nullable String unitName) { if (this.persistenceUnits != null) { String unitNameForLookup = (unitName != null ? unitName : ""); if (unitNameForLookup.isEmpty()) { unitNameForLookup = this.defaultPersistenceUnitName; } String jndiName = this.persistenceUnits.get(unitNameForLookup); if (jndiName == null && unitNameForLookup.isEmpty() && this.persistenceUnits.size() == 1) { jndiName = this.persistenceUnits.values().iterator().next(); } if (jndiName != null) { try { return lookup(jndiName, EntityManagerFactory.class); } catch (Exception ex) { throw new IllegalStateException("Could not obtain EntityManagerFactory [" + jndiName + "] from JNDI", ex); } } } return null; } /** * Return a specified persistence context for the given unit name, as defined * through the "persistenceContexts" (or "extendedPersistenceContexts") map. * @param unitName the name of the persistence unit * @param extended whether to obtain an extended persistence context * @return the corresponding EntityManager, or {@code null} if none found * @see #setPersistenceContexts * @see #setExtendedPersistenceContexts */ @Nullable protected EntityManager getPersistenceContext(@Nullable String unitName, boolean extended) { Map<String, String> contexts = (extended ? this.extendedPersistenceContexts : this.persistenceContexts); if (contexts != null) { String unitNameForLookup = (unitName != null ? unitName : ""); if (unitNameForLookup.isEmpty()) { unitNameForLookup = this.defaultPersistenceUnitName; } String jndiName = contexts.get(unitNameForLookup); if (jndiName == null && unitNameForLookup.isEmpty() && contexts.size() == 1) { jndiName = contexts.values().iterator().next(); } if (jndiName != null) { try { return lookup(jndiName, EntityManager.class); } catch (Exception ex) { throw new IllegalStateException("Could not obtain EntityManager [" + jndiName + "] from JNDI", ex); } } } return null; } /** * Find an EntityManagerFactory with the given name in the current Spring * application context, falling back to a single default EntityManagerFactory * (if any) in case of no unit name specified. * @param unitName the name of the persistence unit (may be {@code null} or empty) * @param requestingBeanName the name of the requesting bean * @return the EntityManagerFactory * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context */ protected EntityManagerFactory findEntityManagerFactory(@Nullable String unitName, @Nullable String requestingBeanName) throws NoSuchBeanDefinitionException { String unitNameForLookup = (unitName != null ? unitName : ""); if (unitNameForLookup.isEmpty()) { unitNameForLookup = this.defaultPersistenceUnitName; } if (!unitNameForLookup.isEmpty()) { return findNamedEntityManagerFactory(unitNameForLookup, requestingBeanName); } else { return findDefaultEntityManagerFactory(requestingBeanName); } } /** * Find an EntityManagerFactory with the given name in the current * Spring application context. * @param unitName the name of the persistence unit (never empty) * @param requestingBeanName the name of the requesting bean * @return the EntityManagerFactory * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context */ protected EntityManagerFactory findNamedEntityManagerFactory(String unitName, @Nullable String requestingBeanName) throws NoSuchBeanDefinitionException { Assert.state(this.beanFactory != null, "ListableBeanFactory required for EntityManagerFactory bean lookup"); EntityManagerFactory emf = EntityManagerFactoryUtils.findEntityManagerFactory(this.beanFactory, unitName); if (requestingBeanName != null && this.beanFactory instanceof ConfigurableBeanFactory cbf) { cbf.registerDependentBean(unitName, requestingBeanName); } return emf; } /** * Find a single default EntityManagerFactory in the Spring application context. * @return the default EntityManagerFactory * @throws NoSuchBeanDefinitionException if there is no single EntityManagerFactory in the context */ protected EntityManagerFactory findDefaultEntityManagerFactory(@Nullable String requestingBeanName) throws NoSuchBeanDefinitionException { Assert.state(this.beanFactory != null, "ListableBeanFactory required for EntityManagerFactory bean lookup"); if (this.beanFactory instanceof ConfigurableListableBeanFactory clbf) { // Fancy variant with dependency registration NamedBeanHolder<EntityManagerFactory> emfHolder = clbf.resolveNamedBean(EntityManagerFactory.class); if (requestingBeanName != null) { clbf.registerDependentBean(emfHolder.getBeanName(), requestingBeanName); } return emfHolder.getBeanInstance(); } else { // Plain variant: just find a default bean return this.beanFactory.getBean(EntityManagerFactory.class); } } /** * Perform a JNDI lookup for the given resource by name. * <p>Called for EntityManagerFactory and EntityManager lookup * when JNDI names are mapped for specific persistence units. * @param jndiName the JNDI name to look up * @param requiredType the required type of the object * @return the obtained object * @throws Exception if the JNDI lookup failed */ protected <T> T lookup(String jndiName, Class<T> requiredType) throws Exception { return new LocatorDelegate().lookup(jndiName, requiredType); } /** * Separate inner class to isolate the JNDI API dependency * (for compatibility with Google App Engine's API white list). */ private class LocatorDelegate { public <T> T lookup(String jndiName, Class<T> requiredType) throws Exception { JndiLocatorDelegate locator = new JndiLocatorDelegate(); if (jndiEnvironment instanceof JndiTemplate jndiTemplate) { locator.setJndiTemplate(jndiTemplate); } else if (jndiEnvironment instanceof Properties properties) { locator.setJndiEnvironment(properties); } else if (jndiEnvironment != null) { throw new IllegalStateException("Illegal 'jndiEnvironment' type: " + jndiEnvironment.getClass()); } locator.setResourceRef(resourceRef); return locator.lookup(jndiName, requiredType); } } /** * Class representing injection information about an annotated field * or setter method. */ private class PersistenceElement extends InjectionMetadata.InjectedElement { private final String unitName; @Nullable private PersistenceContextType type; private boolean synchronizedWithTransaction = false; @Nullable private Properties properties; public PersistenceElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) { super(member, pd); PersistenceContext pc = ae.getAnnotation(PersistenceContext.class); PersistenceUnit pu = ae.getAnnotation(PersistenceUnit.class); Class<?> resourceType = EntityManager.class; if (pc != null) { if (pu != null) { throw new IllegalStateException("Member may only be annotated with either " + "@PersistenceContext or @PersistenceUnit, not both: " + member); } Properties properties = null; PersistenceProperty[] pps = pc.properties(); if (!ObjectUtils.isEmpty(pps)) { properties = new Properties(); for (PersistenceProperty pp : pps) { properties.setProperty(pp.name(), pp.value()); } } this.unitName = pc.unitName(); this.type = pc.type(); this.synchronizedWithTransaction = SynchronizationType.SYNCHRONIZED.equals(pc.synchronization()); this.properties = properties; } else { resourceType = EntityManagerFactory.class; this.unitName = pu.unitName(); } checkResourceType(resourceType); } /** * Resolve the object against the application context. */ @Override protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) { // Resolves to EntityManagerFactory or EntityManager. if (this.type != null) { return (this.type == PersistenceContextType.EXTENDED ? resolveExtendedEntityManager(target, requestingBeanName) : resolveEntityManager(requestingBeanName)); } else { // OK, so we need an EntityManagerFactory... return resolveEntityManagerFactory(requestingBeanName); } } private EntityManagerFactory resolveEntityManagerFactory(@Nullable String requestingBeanName) { // Obtain EntityManagerFactory from JNDI? EntityManagerFactory emf = getPersistenceUnit(this.unitName); if (emf == null) { // Need to search for EntityManagerFactory beans. emf = findEntityManagerFactory(this.unitName, requestingBeanName); } return emf; } private EntityManager resolveEntityManager(@Nullable String requestingBeanName) { // Obtain EntityManager reference from JNDI? EntityManager em = getPersistenceContext(this.unitName, false); if (em == null) { // No pre-built EntityManager found -> build one based on factory. // Obtain EntityManagerFactory from JNDI? EntityManagerFactory emf = getPersistenceUnit(this.unitName); if (emf == null) { // Need to search for EntityManagerFactory beans. emf = findEntityManagerFactory(this.unitName, requestingBeanName); } // Inject a shared transactional EntityManager proxy. if (emf instanceof EntityManagerFactoryInfo emfInfo && emfInfo.getEntityManagerInterface() != null) { // Create EntityManager based on the info's vendor-specific type // (which might be more specific than the field's type). em = SharedEntityManagerCreator.createSharedEntityManager( emf, this.properties, this.synchronizedWithTransaction); } else { // Create EntityManager based on the field's type. em = SharedEntityManagerCreator.createSharedEntityManager( emf, this.properties, this.synchronizedWithTransaction, getResourceType()); } } return em; } private EntityManager resolveExtendedEntityManager(Object target, @Nullable String requestingBeanName) { // Obtain EntityManager reference from JNDI? EntityManager em = getPersistenceContext(this.unitName, true); if (em == null) { // No pre-built EntityManager found -> build one based on factory. // Obtain EntityManagerFactory from JNDI? EntityManagerFactory emf = getPersistenceUnit(this.unitName); if (emf == null) { // Need to search for EntityManagerFactory beans. emf = findEntityManagerFactory(this.unitName, requestingBeanName); } // Inject a container-managed extended EntityManager. em = ExtendedEntityManagerCreator.createContainerManagedEntityManager( emf, this.properties, this.synchronizedWithTransaction); } if (em instanceof EntityManagerProxy emp && beanFactory != null && requestingBeanName != null && beanFactory.containsBean(requestingBeanName) && !beanFactory.isPrototype(requestingBeanName)) { extendedEntityManagersToClose.put(target, emp.getTargetEntityManager()); } return em; } } private static class AotContribution implements BeanRegistrationAotContribution { private static final String REGISTERED_BEAN_PARAMETER = "registeredBean"; private static final String INSTANCE_PARAMETER = "instance"; private final Class<?> target; private final List<InjectedElement> injectedElements; AotContribution(Class<?> target, Collection<InjectedElement> injectedElements) { this.target = target; this.injectedElements = List.copyOf(injectedElements); } @Override public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) { GeneratedClass generatedClass = generationContext.getGeneratedClasses() .addForFeatureComponent("PersistenceInjection", this.target, type -> { type.addJavadoc("Persistence injection for {@link $T}.", this.target); type.addModifiers(javax.lang.model.element.Modifier.PUBLIC); }); GeneratedMethod generatedMethod = generatedClass.getMethods().add("apply", method -> { method.addJavadoc("Apply the persistence injection."); method.addModifiers(javax.lang.model.element.Modifier.PUBLIC, javax.lang.model.element.Modifier.STATIC); method.addParameter(RegisteredBean.class, REGISTERED_BEAN_PARAMETER); method.addParameter(this.target, INSTANCE_PARAMETER); method.returns(this.target); method.addCode(generateMethodCode(generationContext.getRuntimeHints(), generatedClass)); }); beanRegistrationCode.addInstancePostProcessor(generatedMethod.toMethodReference()); } private CodeBlock generateMethodCode(RuntimeHints hints, GeneratedClass generatedClass) { CodeBlock.Builder code = CodeBlock.builder(); if (this.injectedElements.size() == 1) { code.add(generateInjectedElementMethodCode(hints, generatedClass, this.injectedElements.get(0))); } else { for (InjectedElement injectedElement : this.injectedElements) { code.addStatement(applyInjectedElement(hints, generatedClass, injectedElement)); } } code.addStatement("return $L", INSTANCE_PARAMETER); return code.build(); } private CodeBlock applyInjectedElement(RuntimeHints hints, GeneratedClass generatedClass, InjectedElement injectedElement) { String injectedElementName = injectedElement.getMember().getName(); GeneratedMethod generatedMethod = generatedClass.getMethods().add(new String[] { "apply", injectedElementName }, method -> { method.addJavadoc("Apply the persistence injection for '$L'.", injectedElementName); method.addModifiers(javax.lang.model.element.Modifier.PRIVATE, javax.lang.model.element.Modifier.STATIC); method.addParameter(RegisteredBean.class, REGISTERED_BEAN_PARAMETER); method.addParameter(this.target, INSTANCE_PARAMETER); method.addCode(generateInjectedElementMethodCode(hints, generatedClass, injectedElement)); }); ArgumentCodeGenerator argumentCodeGenerator = ArgumentCodeGenerator .of(RegisteredBean.class, REGISTERED_BEAN_PARAMETER).and(this.target, INSTANCE_PARAMETER); return generatedMethod.toMethodReference().toInvokeCodeBlock(argumentCodeGenerator, generatedClass.getName()); } private CodeBlock generateInjectedElementMethodCode(RuntimeHints hints, GeneratedClass generatedClass, InjectedElement injectedElement) { CodeBlock.Builder code = CodeBlock.builder(); InjectionCodeGenerator injectionCodeGenerator = new InjectionCodeGenerator(generatedClass.getName(), hints); CodeBlock resourceToInject = generateResourceToInjectCode(generatedClass.getMethods(), (PersistenceElement) injectedElement); code.add(injectionCodeGenerator.generateInjectionCode( injectedElement.getMember(), INSTANCE_PARAMETER, resourceToInject)); return code.build(); } private CodeBlock generateResourceToInjectCode( GeneratedMethods generatedMethods, PersistenceElement injectedElement) { String unitName = injectedElement.unitName; boolean requireEntityManager = (injectedElement.type != null); if (!requireEntityManager) { return CodeBlock.of( "$T.findEntityManagerFactory(($T) $L.getBeanFactory(), $S)", EntityManagerFactoryUtils.class, ListableBeanFactory.class, REGISTERED_BEAN_PARAMETER, unitName); } String[] methodNameParts = { "get", unitName, "EntityManager" }; GeneratedMethod generatedMethod = generatedMethods.add(methodNameParts, method -> generateGetEntityManagerMethod(method, injectedElement)); return CodeBlock.of("$L($L)", generatedMethod.getName(), REGISTERED_BEAN_PARAMETER); } @SuppressWarnings("NullAway") private void generateGetEntityManagerMethod(MethodSpec.Builder method, PersistenceElement injectedElement) { String unitName = injectedElement.unitName; Properties properties = injectedElement.properties; method.addJavadoc("Get the '$L' {@link $T}.", (StringUtils.hasLength(unitName)) ? unitName : "default", EntityManager.class); method.addModifiers(javax.lang.model.element.Modifier.PUBLIC, javax.lang.model.element.Modifier.STATIC); method.returns(EntityManager.class); method.addParameter(RegisteredBean.class, REGISTERED_BEAN_PARAMETER); method.addStatement( "$T entityManagerFactory = $T.findEntityManagerFactory(($T) $L.getBeanFactory(), $S)", EntityManagerFactory.class, EntityManagerFactoryUtils.class, ListableBeanFactory.class, REGISTERED_BEAN_PARAMETER, unitName); boolean hasProperties = !CollectionUtils.isEmpty(properties); if (hasProperties) { method.addStatement("$T properties = new Properties()", Properties.class); for (String propertyName : new TreeSet<>(properties.stringPropertyNames())) { method.addStatement("properties.put($S, $S)", propertyName, properties.getProperty(propertyName)); } } method.addStatement( "return $T.createSharedEntityManager(entityManagerFactory, $L, $L)", SharedEntityManagerCreator.class, (hasProperties) ? "properties" : null, injectedElement.synchronizedWithTransaction); } } }
spring-projects/spring-framework
spring-orm/src/main/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.java
2,159
/* * 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.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import com.carrotsearch.randomizedtesting.Xoroshiro128PlusRandom; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Utilities { public static Pattern pattern = Pattern.compile("[\\-0-9]+"); public static SecureRandom random = new SecureRandom(); public static Random fastRandom = new Xoroshiro128PlusRandom(random.nextLong()); public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue"); public static volatile DispatchQueue globalQueue = new DispatchQueue("globalQueue"); public static volatile DispatchQueue cacheClearQueue = new DispatchQueue("cacheClearQueue"); public static volatile DispatchQueue searchQueue = new DispatchQueue("searchQueue"); public static volatile DispatchQueue phoneBookQueue = new DispatchQueue("phoneBookQueue"); public static volatile DispatchQueue themeQueue = new DispatchQueue("themeQueue"); public static volatile DispatchQueue externalNetworkQueue = new DispatchQueue("externalNetworkQueue"); public static volatile DispatchQueue videoPlayerQueue; private final static String RANDOM_STRING_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); static { try { File URANDOM_FILE = new File("/dev/urandom"); FileInputStream sUrandomIn = new FileInputStream(URANDOM_FILE); byte[] buffer = new byte[1024]; sUrandomIn.read(buffer); sUrandomIn.close(); random.setSeed(buffer); } catch (Exception e) { FileLog.e(e); } } public native static int pinBitmap(Bitmap bitmap); public native static void unpinBitmap(Bitmap bitmap); public native static void blurBitmap(Object bitmap, int radius, int unpin, int width, int height, int stride); public native static int needInvert(Object bitmap, int unpin, int width, int height, int stride); public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer, ByteBuffer calcBuffer); public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin); public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap); private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); private native static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); public native static void aesCtrDecryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length); public native static void aesCtrDecryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, long length, int n); private native static void aesCbcEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt); public native static void aesCbcEncryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length, int encrypt); public native static String readlink(String path); public native static String readlinkFd(int fd); public native static long getDirSize(String path, int docType, boolean subdirs); public native static long getLastUsageFileTime(String path); public native static void clearDir(String path, int docType, long time, boolean subdirs); private native static int pbkdf2(byte[] password, byte[] salt, byte[] dst, int iterations); public static native void stackBlurBitmap(Bitmap bitmap, int radius); public static native void drawDitheredGradient(Bitmap bitmap, int[] colors, int startX, int startY, int endX, int endY); public static native int saveProgressiveJpeg(Bitmap bitmap, int width, int height, int stride, int quality, String path); public static native void generateGradient(Bitmap bitmap, boolean unpin, int phase, float progress, int width, int height, int stride, int[] colors); public static native void setupNativeCrashesListener(String path); public static Bitmap stackBlurBitmapMax(Bitmap bitmap) { return stackBlurBitmapMax(bitmap, false); } public static Bitmap stackBlurBitmapMax(Bitmap bitmap, boolean round) { int w = AndroidUtilities.dp(20); int h = (int) (AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth()); Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(scaledBitmap); canvas.save(); canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight()); if (round) { Path path = new Path(); path.addCircle(bitmap.getWidth() / 2f, bitmap.getHeight() / 2f, Math.min(bitmap.getWidth(), bitmap.getHeight()) / 2f - 1, Path.Direction.CW); canvas.clipPath(path); } canvas.drawBitmap(bitmap, 0, 0, null); canvas.restore(); Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150)); return scaledBitmap; } public static Bitmap stackBlurBitmapWithScaleFactor(Bitmap bitmap, float scaleFactor) { int w = (int) Math.max(AndroidUtilities.dp(20), bitmap.getWidth() / scaleFactor); int h = (int) Math.max(AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth(), bitmap.getHeight() / scaleFactor); Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(scaledBitmap); canvas.save(); canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight()); canvas.drawBitmap(bitmap, 0, 0, null); canvas.restore(); Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150)); return scaledBitmap; } public static Bitmap blurWallpaper(Bitmap src) { if (src == null) { return null; } Bitmap b; if (src.getHeight() > src.getWidth()) { b = Bitmap.createBitmap(Math.round(450f * src.getWidth() / src.getHeight()), 450, Bitmap.Config.ARGB_8888); } else { b = Bitmap.createBitmap(450, Math.round(450f * src.getHeight() / src.getWidth()), Bitmap.Config.ARGB_8888); } Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); Rect rect = new Rect(0, 0, b.getWidth(), b.getHeight()); new Canvas(b).drawBitmap(src, null, rect, paint); stackBlurBitmap(b, 12); return b; } public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length); } public static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { aesIgeEncryptionByteArray(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length); } public static void aesCbcEncryptionByteArraySafe(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt) { aesCbcEncryptionByteArray(buffer, key, iv.clone(), offset, length, n, encrypt); } public static Integer parseInt(CharSequence value) { if (value == null) { return 0; } if (BuildConfig.BUILD_HOST_IS_WINDOWS) { Matcher matcher = pattern.matcher(value); if (matcher.find()) { return Integer.valueOf(matcher.group()); } } else { int val = 0; try { int start = -1, end; for (end = 0; end < value.length(); ++end) { char character = value.charAt(end); boolean allowedChar = character == '-' || character >= '0' && character <= '9'; if (allowedChar && start < 0) { start = end; } else if (!allowedChar && start >= 0) { end++; break; } } if (start >= 0) { String str = value.subSequence(start, end).toString(); // val = parseInt(str); val = Integer.parseInt(str); } } catch (Exception ignore) {} return val; } return 0; } private static int parseInt(final String s) { int num = 0; boolean negative = true; final int len = s.length(); final char ch = s.charAt(0); if (ch == '-') { negative = false; } else { num = '0' - ch; } int i = 1; while (i < len) { num = num * 10 + '0' - s.charAt(i++); } return negative ? -num : num; } public static Long parseLong(String value) { if (value == null) { return 0L; } long val = 0L; try { Matcher matcher = pattern.matcher(value); if (matcher.find()) { String num = matcher.group(0); val = Long.parseLong(num); } } catch (Exception ignore) { } return val; } public static String parseIntToString(String value) { Matcher matcher = pattern.matcher(value); if (matcher.find()) { return matcher.group(0); } return null; } public static String bytesToHex(byte[] bytes) { if (bytes == null) { return ""; } char[] hexChars = new char[bytes.length * 2]; int v; for (int j = 0; j < bytes.length; j++) { v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public static byte[] hexToBytes(String hex) { if (hex == null) { return null; } int len = hex.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16)); } return data; } public static boolean isGoodPrime(byte[] prime, int g) { if (!(g >= 2 && g <= 7)) { return false; } if (prime.length != 256 || prime[0] >= 0) { return false; } BigInteger dhBI = new BigInteger(1, prime); if (g == 2) { // p mod 8 = 7 for g = 2; BigInteger res = dhBI.mod(BigInteger.valueOf(8)); if (res.intValue() != 7) { return false; } } else if (g == 3) { // p mod 3 = 2 for g = 3; BigInteger res = dhBI.mod(BigInteger.valueOf(3)); if (res.intValue() != 2) { return false; } } else if (g == 5) { // p mod 5 = 1 or 4 for g = 5; BigInteger res = dhBI.mod(BigInteger.valueOf(5)); int val = res.intValue(); if (val != 1 && val != 4) { return false; } } else if (g == 6) { // p mod 24 = 19 or 23 for g = 6; BigInteger res = dhBI.mod(BigInteger.valueOf(24)); int val = res.intValue(); if (val != 19 && val != 23) { return false; } } else if (g == 7) { // p mod 7 = 3, 5 or 6 for g = 7. BigInteger res = dhBI.mod(BigInteger.valueOf(7)); int val = res.intValue(); if (val != 3 && val != 5 && val != 6) { return false; } } String hex = bytesToHex(prime); if (hex.equals("C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B")) { return true; } BigInteger dhBI2 = dhBI.subtract(BigInteger.valueOf(1)).divide(BigInteger.valueOf(2)); return !(!dhBI.isProbablePrime(30) || !dhBI2.isProbablePrime(30)); } public static boolean isGoodGaAndGb(BigInteger g_a, BigInteger p) { return !(g_a.compareTo(BigInteger.valueOf(1)) <= 0 || g_a.compareTo(p.subtract(BigInteger.valueOf(1))) >= 0); } public static boolean arraysEquals(byte[] arr1, int offset1, byte[] arr2, int offset2) { if (arr1 == null || arr2 == null || offset1 < 0 || offset2 < 0 || arr1.length - offset1 > arr2.length - offset2 || arr1.length - offset1 < 0 || arr2.length - offset2 < 0) { return false; } boolean result = true; for (int a = offset1; a < arr1.length; a++) { if (arr1[a + offset1] != arr2[a + offset2]) { result = false; } } return result; } public static byte[] computeSHA1(byte[] convertme, int offset, int len) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(convertme, offset, len); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[20]; } public static byte[] computeSHA1(ByteBuffer convertme, int offset, int len) { int oldp = convertme.position(); int oldl = convertme.limit(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); convertme.position(offset); convertme.limit(len); md.update(convertme); return md.digest(); } catch (Exception e) { FileLog.e(e); } finally { convertme.limit(oldl); convertme.position(oldp); } return new byte[20]; } public static byte[] computeSHA1(ByteBuffer convertme) { return computeSHA1(convertme, 0, convertme.limit()); } public static byte[] computeSHA1(byte[] convertme) { return computeSHA1(convertme, 0, convertme.length); } public static byte[] computeSHA256(byte[] convertme) { return computeSHA256(convertme, 0, convertme.length); } public static byte[] computeSHA256(byte[] convertme, int offset, long len) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(convertme, offset, (int) len); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[32]; } public static byte[] computeSHA256(byte[]... args) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); for (int a = 0; a < args.length; a++) { md.update(args[a], 0, args[a].length); } return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[32]; } public static byte[] computeSHA512(byte[] convertme) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computeSHA512(byte[] convertme, byte[] convertme2) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); md.update(convertme2, 0, convertme2.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computePBKDF2(byte[] password, byte[] salt) { byte[] dst = new byte[64]; Utilities.pbkdf2(password, salt, dst, 100000); return dst; } public static byte[] computeSHA512(byte[] convertme, byte[] convertme2, byte[] convertme3) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); md.update(convertme2, 0, convertme2.length); md.update(convertme3, 0, convertme3.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computeSHA256(byte[] b1, int o1, int l1, ByteBuffer b2, int o2, int l2) { int oldp = b2.position(); int oldl = b2.limit(); try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(b1, o1, l1); b2.position(o2); b2.limit(l2); md.update(b2); return md.digest(); } catch (Exception e) { FileLog.e(e); } finally { b2.limit(oldl); b2.position(oldp); } return new byte[32]; } public static long bytesToLong(byte[] bytes) { return ((long) bytes[7] << 56) + (((long) bytes[6] & 0xFF) << 48) + (((long) bytes[5] & 0xFF) << 40) + (((long) bytes[4] & 0xFF) << 32) + (((long) bytes[3] & 0xFF) << 24) + (((long) bytes[2] & 0xFF) << 16) + (((long) bytes[1] & 0xFF) << 8) + ((long) bytes[0] & 0xFF); } public static int bytesToInt(byte[] bytes) { return (((int) bytes[3] & 0xFF) << 24) + (((int) bytes[2] & 0xFF) << 16) + (((int) bytes[1] & 0xFF) << 8) + ((int) bytes[0] & 0xFF); } public static byte[] intToBytes(int value) { return new byte[]{ (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value}; } public static String MD5(String md5) { if (md5 == null) { return null; } try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(AndroidUtilities.getStringBytes(md5)); StringBuilder sb = new StringBuilder(); for (int a = 0; a < array.length; a++) { sb.append(Integer.toHexString((array[a] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { FileLog.e(e); } return null; } public static int clamp(int value, int maxValue, int minValue) { return Math.max(Math.min(value, maxValue), minValue); } public static long clamp(long value, long maxValue, long minValue) { return Math.max(Math.min(value, maxValue), minValue); } public static float clamp(float value, float maxValue, float minValue) { if (Float.isNaN(value)) { return minValue; } if (Float.isInfinite(value)) { return maxValue; } return Math.max(Math.min(value, maxValue), minValue); } public static double clamp(double value, double maxValue, double minValue) { if (Double.isNaN(value)) { return minValue; } if (Double.isInfinite(value)) { return maxValue; } return Math.max(Math.min(value, maxValue), minValue); } public static String generateRandomString() { return generateRandomString(16); } public static String generateRandomString(int chars) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < chars; i++) { sb.append(RANDOM_STRING_CHARS.charAt(fastRandom.nextInt(RANDOM_STRING_CHARS.length()))); } return sb.toString(); } public static String getExtension(String fileName) { int idx = fileName.lastIndexOf('.'); String ext = null; if (idx != -1) { ext = fileName.substring(idx + 1); } if (ext == null) { return null; } ext = ext.toUpperCase(); return ext; } public static interface Callback<T> { public void run(T arg); } public static interface CallbackVoidReturn<ReturnType> { public ReturnType run(); } public static interface Callback0Return<ReturnType> { public ReturnType run(); } public static interface CallbackReturn<Arg, ReturnType> { public ReturnType run(Arg arg); } public static interface Callback2Return<T1, T2, ReturnType> { public ReturnType run(T1 arg, T2 arg2); } public static interface Callback3Return<T1, T2, T3, ReturnType> { public ReturnType run(T1 arg, T2 arg2, T3 arg3); } public static interface Callback2<T, T2> { public void run(T arg, T2 arg2); } public static interface Callback3<T, T2, T3> { public void run(T arg, T2 arg2, T3 arg3); } public static interface Callback4<T, T2, T3, T4> { public void run(T arg, T2 arg2, T3 arg3, T4 arg4); } public static interface Callback4Return<T, T2, T3, T4, ReturnType> { public ReturnType run(T arg, T2 arg2, T3 arg3, T4 arg4); } public static interface Callback5<T, T2, T3, T4, T5> { public void run(T arg, T2 arg2, T3 arg3, T4 arg4, T5 arg5); } public static interface Callback5Return<T, T2, T3, T4, T5, ReturnType> { public ReturnType run(T arg, T2 arg2, T3 arg3, T4 arg4, T5 arg5); } public static interface IndexedConsumer<T> { void accept(T t, int index); } public static <Key, Value> Value getOrDefault(HashMap<Key, Value> map, Key key, Value defaultValue) { Value v = map.get(key); if (v == null) { return defaultValue; } return v; } public static void doCallbacks(Utilities.Callback<Runnable> ...actions) { doCallbacks(0, actions); } private static void doCallbacks(int i, Utilities.Callback<Runnable> ...actions) { if (actions != null && actions.length > i) { actions[i].run(() -> doCallbacks(i + 1, actions)); } } public static void raceCallbacks(Runnable onFinish, Utilities.Callback<Runnable> ...actions) { if (actions == null || actions.length == 0) { if (onFinish != null) { onFinish.run(); } return; } final int[] finished = new int[] { 0 }; Runnable checkFinish = () -> { finished[0]++; if (finished[0] == actions.length) { if (onFinish != null) { onFinish.run(); } } }; for (int i = 0; i < actions.length; ++i) { actions[i].run(checkFinish); } } public static DispatchQueue getOrCreatePlayerQueue() { if (videoPlayerQueue == null) { videoPlayerQueue = new DispatchQueue("playerQueue"); } return videoPlayerQueue; } public static boolean isNullOrEmpty(final Collection<?> list) { return list == null || list.isEmpty(); } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java
2,160
/* * This is the source code of Telegram for Android v. 7.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-2021. */ package org.telegram.ui; import android.app.Activity; import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ChatsWidgetProvider; import org.telegram.messenger.ContactsController; import org.telegram.messenger.ContactsWidgetProvider; import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.R; import org.telegram.messenger.SharedConfig; 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.AlertDialog; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; import org.telegram.ui.Cells.ChatActionCell; import org.telegram.ui.Cells.GroupCreateUserCell; import org.telegram.ui.Cells.TextCell; import org.telegram.ui.Cells.TextInfoPrivacyCell; import org.telegram.ui.Components.AvatarDrawable; import org.telegram.ui.Components.BackgroundGradientDrawable; import org.telegram.ui.Components.CombinedDrawable; import org.telegram.ui.Components.ForegroundColorSpanThemable; import org.telegram.ui.Components.InviteMembersBottomSheet; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.MotionBackgroundDrawable; import org.telegram.ui.Components.RecyclerListView; import java.io.File; import java.util.ArrayList; public class EditWidgetActivity extends BaseFragment { private ListAdapter listAdapter; private RecyclerListView listView; private ItemTouchHelper itemTouchHelper; private FrameLayout widgetPreview; private ImageView previewImageView; private ArrayList<Long> selectedDialogs = new ArrayList<>(); private WidgetPreviewCell widgetPreviewCell; private int previewRow; private int selectChatsRow; private int chatsStartRow; private int chatsEndRow; private int infoRow; private int rowCount; private int widgetType; private int currentWidgetId; private EditWidgetActivityDelegate delegate; public final static int TYPE_CHATS = 0; public final static int TYPE_CONTACTS = 1; private final static int done_item = 1; public interface EditWidgetActivityDelegate { void didSelectDialogs(ArrayList<Long> dialogs); } public class TouchHelperCallback extends ItemTouchHelper.Callback { private boolean moved; @Override public boolean isLongPressDragEnabled() { return false; } @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { if (viewHolder.getItemViewType() != 3) { return makeMovementFlags(0, 0); } return makeMovementFlags(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0); } @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) { if (source.getItemViewType() != target.getItemViewType()) { return false; } int p1 = source.getAdapterPosition(); int p2 = target.getAdapterPosition(); if (listAdapter.swapElements(p1, p2)) { ((GroupCreateUserCell) source.itemView).setDrawDivider(p2 != chatsEndRow - 1); ((GroupCreateUserCell) target.itemView).setDrawDivider(p1 != chatsEndRow - 1); moved = true; } return true; } @Override public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); } @Override public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) { listView.cancelClickRunnables(false); viewHolder.itemView.setPressed(true); } else if (moved) { if (widgetPreviewCell != null) { widgetPreviewCell.updateDialogs(); } moved = false; } super.onSelectedChanged(viewHolder, actionState); } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { } @Override public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { super.clearView(recyclerView, viewHolder); viewHolder.itemView.setPressed(false); } } public class WidgetPreviewCell extends FrameLayout { private BackgroundGradientDrawable.Disposable backgroundGradientDisposable; private BackgroundGradientDrawable.Disposable oldBackgroundGradientDisposable; private Drawable backgroundDrawable; private Drawable oldBackgroundDrawable; private Drawable shadowDrawable; private Paint roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private RectF bitmapRect = new RectF(); private ViewGroup[] cells = new ViewGroup[2]; public WidgetPreviewCell(Context context) { super(context); setWillNotDraw(false); setPadding(0, AndroidUtilities.dp(24), 0, AndroidUtilities.dp(24)); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); ChatActionCell chatActionCell = new ChatActionCell(context); chatActionCell.setCustomText(LocaleController.getString("WidgetPreview", R.string.WidgetPreview)); linearLayout.addView(chatActionCell, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 0, 0, 4)); LinearLayout widgetPreview = new LinearLayout(context); widgetPreview.setOrientation(LinearLayout.VERTICAL); widgetPreview.setBackgroundResource(R.drawable.widget_bg); linearLayout.addView(widgetPreview, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 10, 0, 10, 0)); previewImageView = new ImageView(context); if (widgetType == TYPE_CHATS) { for (int a = 0; a < 2; a++) { cells[a] = (ViewGroup) getParentActivity().getLayoutInflater().inflate(R.layout.shortcut_widget_item, null); widgetPreview.addView(cells[a], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); } widgetPreview.addView(previewImageView, LayoutHelper.createLinear(218, 160, Gravity.CENTER)); previewImageView.setImageResource(R.drawable.chats_widget_preview); } else if (widgetType == TYPE_CONTACTS) { for (int a = 0; a < 2; a++) { cells[a] = (ViewGroup) getParentActivity().getLayoutInflater().inflate(R.layout.contacts_widget_item, null); widgetPreview.addView(cells[a], LayoutHelper.createLinear(160, LayoutHelper.WRAP_CONTENT)); } widgetPreview.addView(previewImageView, LayoutHelper.createLinear(160, 160, Gravity.CENTER)); previewImageView.setImageResource(R.drawable.contacts_widget_preview); } updateDialogs(); shadowDrawable = Theme.getThemedDrawableByKey(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow); } public void updateDialogs() { if (widgetType == TYPE_CHATS) { for (int a = 0; a < 2; a++) { TLRPC.Dialog dialog; if (selectedDialogs.isEmpty()) { dialog = a < getMessagesController().dialogsServerOnly.size() ? getMessagesController().dialogsServerOnly.get(a) : null; } else { if (a < selectedDialogs.size()) { dialog = getMessagesController().dialogs_dict.get(selectedDialogs.get(a)); if (dialog == null) { dialog = new TLRPC.TL_dialog(); dialog.id = selectedDialogs.get(a); } } else { dialog = null; } } if (dialog == null) { cells[a].setVisibility(GONE); continue; } cells[a].setVisibility(VISIBLE); String name = ""; TLRPC.FileLocation photoPath = null; TLRPC.User user = null; TLRPC.Chat chat = null; if (DialogObject.isUserDialog(dialog.id)) { user = getMessagesController().getUser(dialog.id); if (user != null) { if (UserObject.isUserSelf(user)) { name = LocaleController.getString("SavedMessages", R.string.SavedMessages); } else if (UserObject.isReplyUser(user)) { name = LocaleController.getString("RepliesTitle", R.string.RepliesTitle); } else if (UserObject.isDeleted(user)) { name = LocaleController.getString("HiddenName", R.string.HiddenName); } else { name = ContactsController.formatName(user.first_name, user.last_name); } if (!UserObject.isReplyUser(user) && !UserObject.isUserSelf(user) && user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { photoPath = user.photo.photo_small; } } } else { chat = getMessagesController().getChat(-dialog.id); if (chat != null) { name = chat.title; if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { photoPath = chat.photo.photo_small; } } } ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_text)).setText(name); try { Bitmap bitmap = null; if (photoPath != null) { File path = getFileLoader().getPathToAttach(photoPath, true); bitmap = BitmapFactory.decodeFile(path.toString()); } int size = AndroidUtilities.dp(48); Bitmap result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); result.eraseColor(Color.TRANSPARENT); Canvas canvas = new Canvas(result); if (bitmap == null) { AvatarDrawable avatarDrawable; if (user != null) { avatarDrawable = new AvatarDrawable(user); if (UserObject.isReplyUser(user)) { avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_REPLIES); } else if (UserObject.isUserSelf(user)) { avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_SAVED); } } else { avatarDrawable = new AvatarDrawable(chat); } avatarDrawable.setBounds(0, 0, size, size); avatarDrawable.draw(canvas); } else { BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); if (roundPaint == null) { roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); bitmapRect = new RectF(); } float scale = size / (float) bitmap.getWidth(); canvas.save(); canvas.scale(scale, scale); roundPaint.setShader(shader); bitmapRect.set(0, 0, bitmap.getWidth(), bitmap.getHeight()); canvas.drawRoundRect(bitmapRect, bitmap.getWidth(), bitmap.getHeight(), roundPaint); canvas.restore(); } canvas.setBitmap(null); ((ImageView) cells[a].findViewById(R.id.shortcut_widget_item_avatar)).setImageBitmap(result); } catch (Throwable e) { FileLog.e(e); } ArrayList<MessageObject> messages = getMessagesController().dialogMessage.get(dialog.id); MessageObject message = messages != null && messages.size() > 0 ? messages.get(0) : null; if (message != null) { TLRPC.User fromUser = null; TLRPC.Chat fromChat = null; long fromId = message.getFromChatId(); if (fromId > 0) { fromUser = getMessagesController().getUser(fromId); } else { fromChat = getMessagesController().getChat(-fromId); } CharSequence messageString; CharSequence messageNameString; int textColor = getContext().getResources().getColor(R.color.widget_text); if (message.messageOwner instanceof TLRPC.TL_messageService) { if (ChatObject.isChannel(chat) && (message.messageOwner.action instanceof TLRPC.TL_messageActionHistoryClear || message.messageOwner.action instanceof TLRPC.TL_messageActionChannelMigrateFrom)) { messageString = ""; } else { messageString = message.messageText; } textColor = getContext().getResources().getColor(R.color.widget_action_text); } else { boolean needEmoji = true; if (chat != null && chat.id > 0 && fromChat == null && (!ChatObject.isChannel(chat) || ChatObject.isMegagroup(chat))) { if (message.isOutOwner()) { messageNameString = LocaleController.getString("FromYou", R.string.FromYou); } else if (fromUser != null) { messageNameString = UserObject.getFirstName(fromUser).replace("\n", ""); } else { messageNameString = "DELETED"; } SpannableStringBuilder stringBuilder; String messageFormat = "%2$s: \u2068%1$s\u2069"; if (message.caption != null) { String mess = message.caption.toString(); if (mess.length() > 150) { mess = mess.substring(0, 150); } String emoji; if (message.isVideo()) { emoji = "\uD83D\uDCF9 "; } else if (message.isVoice()) { emoji = "\uD83C\uDFA4 "; } else if (message.isMusic()) { emoji = "\uD83C\uDFA7 "; } else if (message.isPhoto()) { emoji = "\uD83D\uDDBC "; } else { emoji = "\uD83D\uDCCE "; } stringBuilder = SpannableStringBuilder.valueOf(String.format(messageFormat, emoji + mess.replace('\n', ' '), messageNameString)); } else if (message.messageOwner.media != null && !message.isMediaEmpty()) { textColor = getContext().getResources().getColor(R.color.widget_action_text); String innerMessage; if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media; if (Build.VERSION.SDK_INT >= 18) { innerMessage = String.format("\uD83D\uDCCA \u2068%s\u2069", mediaPoll.poll.question.text); } else { innerMessage = String.format("\uD83D\uDCCA %s", mediaPoll.poll.question.text); } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) { if (Build.VERSION.SDK_INT >= 18) { innerMessage = String.format("\uD83C\uDFAE \u2068%s\u2069", message.messageOwner.media.game.title); } else { innerMessage = String.format("\uD83C\uDFAE %s", message.messageOwner.media.game.title); } } else if (message.type == MessageObject.TYPE_MUSIC) { if (Build.VERSION.SDK_INT >= 18) { innerMessage = String.format("\uD83C\uDFA7 \u2068%s - %s\u2069", message.getMusicAuthor(), message.getMusicTitle()); } else { innerMessage = String.format("\uD83C\uDFA7 %s - %s", message.getMusicAuthor(), message.getMusicTitle()); } } else { innerMessage = message.messageText.toString(); } innerMessage = innerMessage.replace('\n', ' '); stringBuilder = SpannableStringBuilder.valueOf(String.format(messageFormat, innerMessage, messageNameString)); try { stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_attachMessage), messageNameString.length() + 2, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Exception e) { FileLog.e(e); } } else if (message.messageOwner.message != null) { String mess = message.messageOwner.message; if (mess.length() > 150) { mess = mess.substring(0, 150); } mess = mess.replace('\n', ' ').trim(); stringBuilder = SpannableStringBuilder.valueOf(String.format(messageFormat, mess, messageNameString)); } else { stringBuilder = SpannableStringBuilder.valueOf(""); } try { stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_nameMessage), 0, messageNameString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Exception e) { FileLog.e(e); } messageString = stringBuilder; } else { if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && message.messageOwner.media.photo instanceof TLRPC.TL_photoEmpty && message.messageOwner.media.ttl_seconds != 0) { messageString = LocaleController.getString("AttachPhotoExpired", R.string.AttachPhotoExpired); } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaDocument && message.messageOwner.media.document instanceof TLRPC.TL_documentEmpty && message.messageOwner.media.ttl_seconds != 0) { messageString = LocaleController.getString("AttachVideoExpired", R.string.AttachVideoExpired); } else if (message.caption != null) { String emoji; if (message.isVideo()) { emoji = "\uD83D\uDCF9 "; } else if (message.isVoice()) { emoji = "\uD83C\uDFA4 "; } else if (message.isMusic()) { emoji = "\uD83C\uDFA7 "; } else if (message.isPhoto()) { emoji = "\uD83D\uDDBC "; } else { emoji = "\uD83D\uDCCE "; } messageString = emoji + message.caption; } else { if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media; messageString = "\uD83D\uDCCA " + mediaPoll.poll.question.text; } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) { messageString = "\uD83C\uDFAE " + message.messageOwner.media.game.title; } else if (message.type == MessageObject.TYPE_MUSIC) { messageString = String.format("\uD83C\uDFA7 %s - %s", message.getMusicAuthor(), message.getMusicTitle()); } else { messageString = message.messageText; AndroidUtilities.highlightText(messageString, message.highlightedWords, null); } if (message.messageOwner.media != null && !message.isMediaEmpty()) { textColor = getContext().getResources().getColor(R.color.widget_action_text); } } } } ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_time)).setText(LocaleController.stringForMessageListDate(message.messageOwner.date)); ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_message)).setText(messageString.toString()); ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_message)).setTextColor(textColor); } else { if (dialog.last_message_date != 0) { ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_time)).setText(LocaleController.stringForMessageListDate(dialog.last_message_date)); } else { ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_time)).setText(""); } ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_message)).setText(""); } if (dialog.unread_count > 0) { ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_badge)).setText(String.format("%d", dialog.unread_count)); cells[a].findViewById(R.id.shortcut_widget_item_badge).setVisibility(VISIBLE); if (getMessagesController().isDialogMuted(dialog.id, 0)) { cells[a].findViewById(R.id.shortcut_widget_item_badge).setBackgroundResource(R.drawable.widget_counter_muted); } else { cells[a].findViewById(R.id.shortcut_widget_item_badge).setBackgroundResource(R.drawable.widget_counter); } } else { cells[a].findViewById(R.id.shortcut_widget_item_badge).setVisibility(GONE); } } cells[0].findViewById(R.id.shortcut_widget_item_divider).setVisibility(cells[1].getVisibility()); cells[1].findViewById(R.id.shortcut_widget_item_divider).setVisibility(GONE); } else if (widgetType == TYPE_CONTACTS) { for (int position = 0; position < 2; position++) { for (int a = 0; a < 2; a++) { int num = position * 2 + a; TLRPC.Dialog dialog; if (selectedDialogs.isEmpty()) { if (num < getMediaDataController().hints.size()) { long userId = getMediaDataController().hints.get(num).peer.user_id; dialog = getMessagesController().dialogs_dict.get(userId); if (dialog == null) { dialog = new TLRPC.TL_dialog(); dialog.id = userId; } } else { dialog = null; } } else { if (num < selectedDialogs.size()) { dialog = getMessagesController().dialogs_dict.get(selectedDialogs.get(num)); if (dialog == null) { dialog = new TLRPC.TL_dialog(); dialog.id = selectedDialogs.get(num); } } else { dialog = null; } } if (dialog == null) { cells[position].findViewById(a == 0 ? R.id.contacts_widget_item1 : R.id.contacts_widget_item2).setVisibility(INVISIBLE); if (num == 0 || num == 2) { cells[position].setVisibility(GONE); } continue; } cells[position].findViewById(a == 0 ? R.id.contacts_widget_item1 : R.id.contacts_widget_item2).setVisibility(VISIBLE); if (num == 0 || num == 2) { cells[position].setVisibility(VISIBLE); } String name; TLRPC.FileLocation photoPath = null; TLRPC.User user = null; TLRPC.Chat chat = null; if (DialogObject.isUserDialog(dialog.id)) { user = getMessagesController().getUser(dialog.id); if (UserObject.isUserSelf(user)) { name = LocaleController.getString("SavedMessages", R.string.SavedMessages); } else if (UserObject.isReplyUser(user)) { name = LocaleController.getString("RepliesTitle", R.string.RepliesTitle); } else if (UserObject.isDeleted(user)) { name = LocaleController.getString("HiddenName", R.string.HiddenName); } else { name = UserObject.getFirstName(user); } if (!UserObject.isReplyUser(user) && !UserObject.isUserSelf(user) && user != null && user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { photoPath = user.photo.photo_small; } } else { chat = getMessagesController().getChat(-dialog.id); name = chat.title; if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { photoPath = chat.photo.photo_small; } } ((TextView) cells[position].findViewById(a == 0 ? R.id.contacts_widget_item_text1 : R.id.contacts_widget_item_text2)).setText(name); try { Bitmap bitmap = null; if (photoPath != null) { File path = getFileLoader().getPathToAttach(photoPath, true); bitmap = BitmapFactory.decodeFile(path.toString()); } int size = AndroidUtilities.dp(48); Bitmap result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); result.eraseColor(Color.TRANSPARENT); Canvas canvas = new Canvas(result); if (bitmap == null) { AvatarDrawable avatarDrawable; if (user != null) { avatarDrawable = new AvatarDrawable(user); if (UserObject.isReplyUser(user)) { avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_REPLIES); } else if (UserObject.isUserSelf(user)) { avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_SAVED); } } else { avatarDrawable = new AvatarDrawable(chat); } avatarDrawable.setBounds(0, 0, size, size); avatarDrawable.draw(canvas); } else { BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); float scale = size / (float) bitmap.getWidth(); canvas.save(); canvas.scale(scale, scale); roundPaint.setShader(shader); bitmapRect.set(0, 0, bitmap.getWidth(), bitmap.getHeight()); canvas.drawRoundRect(bitmapRect, bitmap.getWidth(), bitmap.getHeight(), roundPaint); canvas.restore(); } canvas.setBitmap(null); ((ImageView) cells[position].findViewById(a == 0 ? R.id.contacts_widget_item_avatar1 : R.id.contacts_widget_item_avatar2)).setImageBitmap(result); } catch (Throwable e) { FileLog.e(e); } if (dialog.unread_count > 0) { String count; if (dialog.unread_count > 99) { count = String.format("%d+", 99); } else { count = String.format("%d", dialog.unread_count); } ((TextView) cells[position].findViewById(a == 0 ? R.id.contacts_widget_item_badge1 : R.id.contacts_widget_item_badge2)).setText(count); cells[position].findViewById(a == 0 ? R.id.contacts_widget_item_badge_bg1 : R.id.contacts_widget_item_badge_bg2).setVisibility(VISIBLE); } else { cells[position].findViewById(a == 0 ? R.id.contacts_widget_item_badge_bg1 : R.id.contacts_widget_item_badge_bg2).setVisibility(GONE); } } } } if (cells[0].getVisibility() == VISIBLE) { previewImageView.setVisibility(GONE); } else { previewImageView.setVisibility(VISIBLE); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(264), MeasureSpec.EXACTLY)); } @Override protected void onDraw(Canvas canvas) { Drawable newDrawable = Theme.getCachedWallpaperNonBlocking(); if (newDrawable != backgroundDrawable && newDrawable != null) { if (Theme.isAnimatingColor()) { oldBackgroundDrawable = backgroundDrawable; oldBackgroundGradientDisposable = backgroundGradientDisposable; } else if (backgroundGradientDisposable != null) { backgroundGradientDisposable.dispose(); backgroundGradientDisposable = null; } backgroundDrawable = newDrawable; } float themeAnimationValue = parentLayout.getThemeAnimationValue(); for (int a = 0; a < 2; a++) { Drawable drawable = a == 0 ? oldBackgroundDrawable : backgroundDrawable; if (drawable == null) { continue; } if (a == 1 && oldBackgroundDrawable != null && parentLayout != null) { drawable.setAlpha((int) (255 * themeAnimationValue)); } else { drawable.setAlpha(255); } if (drawable instanceof ColorDrawable || drawable instanceof GradientDrawable || drawable instanceof MotionBackgroundDrawable) { drawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight()); if (drawable instanceof BackgroundGradientDrawable) { final BackgroundGradientDrawable backgroundGradientDrawable = (BackgroundGradientDrawable) drawable; backgroundGradientDisposable = backgroundGradientDrawable.drawExactBoundsSize(canvas, this); } else { drawable.draw(canvas); } } else if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; if (bitmapDrawable.getTileModeX() == Shader.TileMode.REPEAT) { canvas.save(); float scale = 2.0f / AndroidUtilities.density; canvas.scale(scale, scale); drawable.setBounds(0, 0, (int) Math.ceil(getMeasuredWidth() / scale), (int) Math.ceil(getMeasuredHeight() / scale)); } else { int viewHeight = getMeasuredHeight(); float scaleX = (float) getMeasuredWidth() / (float) drawable.getIntrinsicWidth(); float scaleY = (float) (viewHeight) / (float) drawable.getIntrinsicHeight(); float scale = Math.max(scaleX, scaleY); int width = (int) Math.ceil(drawable.getIntrinsicWidth() * scale); int height = (int) Math.ceil(drawable.getIntrinsicHeight() * scale); int x = (getMeasuredWidth() - width) / 2; int y = (viewHeight - height) / 2; canvas.save(); canvas.clipRect(0, 0, width, getMeasuredHeight()); drawable.setBounds(x, y, x + width, y + height); } drawable.draw(canvas); canvas.restore(); } if (a == 0 && oldBackgroundDrawable != null && themeAnimationValue >= 1.0f) { if (oldBackgroundGradientDisposable != null) { oldBackgroundGradientDisposable.dispose(); oldBackgroundGradientDisposable = null; } oldBackgroundDrawable = null; invalidate(); } } shadowDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight()); shadowDrawable.draw(canvas); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (backgroundGradientDisposable != null) { backgroundGradientDisposable.dispose(); backgroundGradientDisposable = null; } if (oldBackgroundGradientDisposable != null) { oldBackgroundGradientDisposable.dispose(); oldBackgroundGradientDisposable = null; } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return false; } @Override public boolean dispatchTouchEvent(MotionEvent ev) { return false; } @Override protected void dispatchSetPressed(boolean pressed) { } @Override public boolean onTouchEvent(MotionEvent event) { return false; } } public EditWidgetActivity(int type, int widgetId) { super(); widgetType = type; currentWidgetId = widgetId; ArrayList<TLRPC.User> users = new ArrayList<>(); ArrayList<TLRPC.Chat> chats = new ArrayList<>(); getMessagesStorage().getWidgetDialogIds(currentWidgetId, widgetType, selectedDialogs, users, chats, true); getMessagesController().putUsers(users, true); getMessagesController().putChats(chats, true); updateRows(); } @Override public boolean onFragmentCreate() { DialogsActivity.loadDialogs(AccountInstance.getInstance(currentAccount)); getMediaDataController().loadHints(true); return super.onFragmentCreate(); } private void updateRows() { rowCount = 0; previewRow = rowCount++; selectChatsRow = rowCount++; if (selectedDialogs.isEmpty()) { chatsStartRow = -1; chatsEndRow = -1; } else { chatsStartRow = rowCount; rowCount += selectedDialogs.size(); chatsEndRow = rowCount; } infoRow = rowCount++; if (listAdapter != null) { listAdapter.notifyDataSetChanged(); } } public void setDelegate(EditWidgetActivityDelegate editWidgetActivityDelegate) { delegate = editWidgetActivityDelegate; } @Override public View createView(Context context) { actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(false); if (AndroidUtilities.isTablet()) { actionBar.setOccupyStatusBar(false); } if (widgetType == TYPE_CHATS) { actionBar.setTitle(LocaleController.getString("WidgetChats", R.string.WidgetChats)); } else { actionBar.setTitle(LocaleController.getString("WidgetShortcuts", R.string.WidgetShortcuts)); } ActionBarMenu menu = actionBar.createMenu(); menu.addItem(done_item, LocaleController.getString("Done", R.string.Done).toUpperCase()); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { if (delegate == null) { finishActivity(); return; } finishFragment(); } else if (id == done_item) { if (getParentActivity() == null) { return; } ArrayList<MessagesStorage.TopicKey> topicKeys = new ArrayList<>(); for (int i = 0; i < selectedDialogs.size(); i++) { topicKeys.add(MessagesStorage.TopicKey.of(selectedDialogs.get(i), 0)); } getMessagesStorage().putWidgetDialogs(currentWidgetId, topicKeys); SharedPreferences preferences = getParentActivity().getSharedPreferences("shortcut_widget", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("account" + currentWidgetId, currentAccount); editor.putInt("type" + currentWidgetId, widgetType); editor.commit(); AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getParentActivity()); if (widgetType == TYPE_CHATS) { ChatsWidgetProvider.updateWidget(getParentActivity(), appWidgetManager, currentWidgetId); } else { ContactsWidgetProvider.updateWidget(getParentActivity(), appWidgetManager, currentWidgetId); } if (delegate != null) { delegate.didSelectDialogs(selectedDialogs); } else { finishActivity(); } } } }); listAdapter = new ListAdapter(context); FrameLayout frameLayout = new FrameLayout(context); frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray)); fragmentView = frameLayout; listView = new RecyclerListView(context); listView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)); listView.setVerticalScrollBarEnabled(false); listView.setAdapter(listAdapter); ((DefaultItemAnimator) listView.getItemAnimator()).setDelayAnimations(false); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); itemTouchHelper = new ItemTouchHelper(new TouchHelperCallback()); itemTouchHelper.attachToRecyclerView(listView); listView.setOnItemClickListener((view, position) -> { if (position == selectChatsRow) { InviteMembersBottomSheet bottomSheet = new InviteMembersBottomSheet(context, currentAccount, null, 0, EditWidgetActivity.this, null); bottomSheet.setDelegate(dids -> { selectedDialogs.clear(); selectedDialogs.addAll(dids); updateRows(); if (widgetPreviewCell != null) { widgetPreviewCell.updateDialogs(); } }, selectedDialogs); bottomSheet.setSelectedContacts(selectedDialogs); showDialog(bottomSheet); } }); listView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListenerExtended() { private Rect rect = new Rect(); @Override public boolean onItemClick(View view, int position, float x, float y) { if (getParentActivity() == null || !(view instanceof GroupCreateUserCell)) { return false; } ImageView imageView = (ImageView) view.getTag(R.id.object_tag); imageView.getHitRect(rect); if (!rect.contains((int) x, (int) y)) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); CharSequence[] items = new CharSequence[]{LocaleController.getString("Delete", R.string.Delete)}; builder.setItems(items, (dialogInterface, i) -> { if (i == 0) { selectedDialogs.remove(position - chatsStartRow); updateRows(); if (widgetPreviewCell != null) { widgetPreviewCell.updateDialogs(); } } }); showDialog(builder.create()); return true; } return false; } @Override public void onMove(float dx, float dy) { } @Override public void onLongClickRelease() { } }); return fragmentView; } private void finishActivity() { if (getParentActivity() == null) { return; } getParentActivity().finish(); AndroidUtilities.runOnUIThread(this::removeSelfFromStack, 1000); } private class ListAdapter extends RecyclerListView.SelectionAdapter { private Context mContext; public ListAdapter(Context context) { mContext = context; } @Override public int getItemCount() { return rowCount; } @Override public boolean isEnabled(RecyclerView.ViewHolder holder) { int type = holder.getItemViewType(); return type == 1 || type == 3; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; switch (viewType) { case 0: view = new TextInfoPrivacyCell(mContext); view.setBackgroundDrawable(Theme.getThemedDrawableByKey(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); break; case 1: view = new TextCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case 2: view = widgetPreviewCell = new WidgetPreviewCell(mContext); break; case 3: default: GroupCreateUserCell cell = new GroupCreateUserCell(mContext, 0, 0, false); ImageView sortImageView = new ImageView(mContext); sortImageView.setImageResource(R.drawable.list_reorder); sortImageView.setScaleType(ImageView.ScaleType.CENTER); cell.setTag(R.id.object_tag, sortImageView); cell.addView(sortImageView, LayoutHelper.createFrame(40, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT), 10, 0, 10, 0)); sortImageView.setOnTouchListener((v, event) -> { if (event.getAction() == MotionEvent.ACTION_DOWN) { itemTouchHelper.startDrag(listView.getChildViewHolder(cell)); } return false; }); sortImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chats_pinnedIcon), PorterDuff.Mode.MULTIPLY)); view = cell; break; } return new RecyclerListView.Holder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { switch (holder.getItemViewType()) { case 0: { TextInfoPrivacyCell cell = (TextInfoPrivacyCell) holder.itemView; if (position == infoRow) { SpannableStringBuilder builder = new SpannableStringBuilder(); if (widgetType == TYPE_CHATS) { builder.append(LocaleController.getString("EditWidgetChatsInfo", R.string.EditWidgetChatsInfo)); } else if (widgetType == TYPE_CONTACTS) { builder.append(LocaleController.getString("EditWidgetContactsInfo", R.string.EditWidgetContactsInfo)); } if (SharedConfig.passcodeHash.length() > 0) { builder.append("\n\n").append(AndroidUtilities.replaceTags(LocaleController.getString("WidgetPasscode2", R.string.WidgetPasscode2))); } cell.setText(builder); } break; } case 1: { TextCell cell = (TextCell) holder.itemView; cell.setColors(-1, Theme.key_windowBackgroundWhiteBlueText4); Drawable drawable1 = mContext.getResources().getDrawable(R.drawable.poll_add_circle); Drawable drawable2 = mContext.getResources().getDrawable(R.drawable.poll_add_plus); drawable1.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_switchTrackChecked), PorterDuff.Mode.MULTIPLY)); drawable2.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_checkboxCheck), PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(drawable1, drawable2); cell.setTextAndIcon(LocaleController.getString("SelectChats", R.string.SelectChats), combinedDrawable, chatsStartRow != -1); cell.getImageView().setPadding(0, AndroidUtilities.dp(7), 0, 0); break; } case 3: { GroupCreateUserCell cell = (GroupCreateUserCell) holder.itemView; long did = selectedDialogs.get(position - chatsStartRow); if (DialogObject.isUserDialog(did)) { TLRPC.User user = getMessagesController().getUser(did); cell.setObject(user, null, null, position != chatsEndRow - 1); } else { TLRPC.Chat chat = getMessagesController().getChat(-did); cell.setObject(chat, null, null, position != chatsEndRow - 1); } } } } @Override public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) { int type = holder.getItemViewType(); if (type == 3 || type == 1) { holder.itemView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); } } @Override public int getItemViewType(int position) { if (position == previewRow) { return 2; } else if (position == selectChatsRow) { return 1; } else if (position == infoRow) { return 0; } return 3; } public boolean swapElements(int fromIndex, int toIndex) { int idx1 = fromIndex - chatsStartRow; int idx2 = toIndex - chatsStartRow; int count = chatsEndRow - chatsStartRow; if (idx1 < 0 || idx2 < 0 || idx1 >= count || idx2 >= count) { return false; } Long did1 = selectedDialogs.get(idx1); Long did2 = selectedDialogs.get(idx2); selectedDialogs.set(idx1, did2); selectedDialogs.set(idx2, did1); notifyItemMoved(fromIndex, toIndex); return true; } } @Override public boolean isSwipeBackEnabled(MotionEvent event) { return false; } @Override public boolean onBackPressed() { if (delegate == null) { finishActivity(); return false; } else { return super.onBackPressed(); } } @Override public ArrayList<ThemeDescription> getThemeDescriptions() { ArrayList<ThemeDescription> themeDescriptions = new ArrayList<>(); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_CELLBACKGROUNDCOLOR, new Class[]{TextCell.class}, null, null, null, Theme.key_windowBackgroundWhite)); themeDescriptions.add(new ThemeDescription(fragmentView, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_windowBackgroundGray)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault)); themeDescriptions.add(new ThemeDescription(listView, 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_TITLECOLOR, null, null, null, null, Theme.key_actionBarDefaultTitle)); 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(listView, ThemeDescription.FLAG_SELECTOR, null, null, null, null, Theme.key_listSelector)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{View.class}, Theme.dividerPaint, null, null, Theme.key_divider)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_BACKGROUNDFILTER, new Class[]{TextInfoPrivacyCell.class}, null, null, null, Theme.key_windowBackgroundGrayShadow)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{TextInfoPrivacyCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText4)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{TextCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlueText4)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{TextCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_windowBackgroundWhiteBlueText4)); return themeDescriptions; } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/EditWidgetActivity.java
2,161
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
2,162
// Copyright 2011 Hakan Kjellerstrand [email protected] // 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.ortools.contrib; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.*; import com.google.ortools.constraintsolver.DecisionBuilder; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.Solver; import java.io.*; import java.text.*; import java.util.*; public class Diet { /** Solves the Diet problem. See http://www.hakank.org/google_or_tools/diet1.py */ private static void solve() { Solver solver = new Solver("Diet"); int n = 4; int[] price = {50, 20, 30, 80}; // in cents // requirements for each nutrition type int[] limits = {500, 6, 10, 8}; // nutritions for each product int[] calories = {400, 200, 150, 500}; int[] chocolate = {3, 2, 0, 0}; int[] sugar = {2, 2, 4, 4}; int[] fat = {2, 4, 1, 5}; // // Variables // IntVar[] x = solver.makeIntVarArray(n, 0, 100, "x"); IntVar cost = solver.makeScalProd(x, price).var(); // // Constraints // solver.addConstraint(solver.makeScalProdGreaterOrEqual(x, calories, limits[0])); solver.addConstraint(solver.makeScalProdGreaterOrEqual(x, chocolate, limits[1])); solver.addConstraint(solver.makeScalProdGreaterOrEqual(x, sugar, limits[2])); solver.addConstraint(solver.makeScalProdGreaterOrEqual(x, fat, limits[3])); // // Objective // OptimizeVar obj = solver.makeMinimize(cost, 1); // // Search // DecisionBuilder db = solver.makePhase(x, solver.CHOOSE_PATH, solver.ASSIGN_MIN_VALUE); solver.newSearch(db, obj); while (solver.nextSolution()) { System.out.println("cost: " + cost.value()); System.out.print("x: "); for (int i = 0; i < n; i++) { System.out.print(x[i].value() + " "); } System.out.println(); } solver.endSearch(); // Statistics System.out.println(); System.out.println("Solutions: " + solver.solutions()); System.out.println("Failures: " + solver.failures()); System.out.println("Branches: " + solver.branches()); System.out.println("Wall time: " + solver.wallTime() + "ms"); } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); Diet.solve(); } }
ahlfors/or-tools
examples/contrib/Diet.java
2,163
package org.telegram.ui.Components; import android.content.Context; import android.graphics.Canvas; import android.graphics.CornerPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.drawable.Drawable; import android.text.Editable; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextWatcher; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.OvershootInterpolator; import android.widget.FrameLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.Emoji; import org.telegram.messenger.LocaleController; 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.SharedConfig; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ChatActivity; import org.telegram.ui.ContentPreviewViewer; import java.util.ArrayList; import java.util.Arrays; public class SuggestEmojiView extends FrameLayout implements NotificationCenter.NotificationCenterDelegate { public final static int DIRECTION_TO_BOTTOM = 0; public final static int DIRECTION_TO_TOP = 1; private final int currentAccount; private final Theme.ResourcesProvider resourcesProvider; private AnchorViewDelegate enterView; @Nullable private FrameLayout containerView; @Nullable private RecyclerListView listView; @Nullable private Adapter adapter; private int direction = DIRECTION_TO_BOTTOM; private int horizontalPadding = AndroidUtilities.dp(10); public interface AnchorViewDelegate { BaseFragment getParentFragment(); void setFieldText(CharSequence text); void addTextChangedListener(TextWatcher watcher); int getVisibility(); EditTextBoldCursor getEditField(); CharSequence getFieldText(); Editable getEditText(); } private ContentPreviewViewer.ContentPreviewViewerDelegate previewDelegate; private ContentPreviewViewer.ContentPreviewViewerDelegate getPreviewDelegate() { if (previewDelegate == null) { previewDelegate = new ContentPreviewViewer.ContentPreviewViewerDelegate() { @Override public boolean can() { return true; } @Override public boolean needSend(int contentType) { if (enterView == null) { return false; } BaseFragment fragment = enterView.getParentFragment(); if (fragment instanceof ChatActivity) { ChatActivity chatActivity = (ChatActivity) fragment; return chatActivity.canSendMessage() && (UserConfig.getInstance(UserConfig.selectedAccount).isPremium() || chatActivity.getCurrentUser() != null && UserObject.isUserSelf(chatActivity.getCurrentUser())); } return false; } @Override public void sendEmoji(TLRPC.Document emoji) { if (enterView == null) { return; } BaseFragment fragment = enterView.getParentFragment(); if (fragment instanceof ChatActivity) { ChatActivity chatActivity = (ChatActivity) fragment; chatActivity.sendAnimatedEmoji(emoji, true, 0); enterView.setFieldText(""); } } @Override public boolean needCopy(TLRPC.Document document) { if (isCopyForbidden) { return false; } return UserConfig.getInstance(UserConfig.selectedAccount).isPremium(); } @Override public void copyEmoji(TLRPC.Document document) { Spannable spannable = SpannableStringBuilder.valueOf(MessageObject.findAnimatedEmojiEmoticon(document)); spannable.setSpan(new AnimatedEmojiSpan(document, null), 0, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); if (AndroidUtilities.addToClipboard(spannable) && enterView != null) { BulletinFactory.of(enterView.getParentFragment()).createCopyBulletin(LocaleController.getString("EmojiCopied", R.string.EmojiCopied)).show(); } } @Override public Boolean canSetAsStatus(TLRPC.Document document) { if (isSetAsStatusForbidden) { return null; } if (!UserConfig.getInstance(UserConfig.selectedAccount).isPremium()) { return null; } TLRPC.User user = UserConfig.getInstance(UserConfig.selectedAccount).getCurrentUser(); if (user == null) { return null; } Long emojiStatusId = UserObject.getEmojiStatusDocumentId(user); return document != null && (emojiStatusId == null || emojiStatusId != document.id); } @Override public void setAsEmojiStatus(TLRPC.Document document, Integer until) { TLRPC.EmojiStatus status; if (document == null) { status = new TLRPC.TL_emojiStatusEmpty(); } else if (until != null) { status = new TLRPC.TL_emojiStatusUntil(); ((TLRPC.TL_emojiStatusUntil) status).document_id = document.id; ((TLRPC.TL_emojiStatusUntil) status).until = until; } else { status = new TLRPC.TL_emojiStatus(); ((TLRPC.TL_emojiStatus) status).document_id = document.id; } TLRPC.User user = UserConfig.getInstance(UserConfig.selectedAccount).getCurrentUser(); final TLRPC.EmojiStatus previousEmojiStatus = user == null ? new TLRPC.TL_emojiStatusEmpty() : user.emoji_status; MessagesController.getInstance(currentAccount).updateEmojiStatus(status); Runnable undoAction = () -> MessagesController.getInstance(currentAccount).updateEmojiStatus(previousEmojiStatus); BaseFragment fragment = enterView == null ? null : enterView.getParentFragment(); if (fragment != null) { if (document == null) { final Bulletin.SimpleLayout layout = new Bulletin.SimpleLayout(getContext(), resourcesProvider); layout.textView.setText(LocaleController.getString("RemoveStatusInfo", R.string.RemoveStatusInfo)); layout.imageView.setImageResource(R.drawable.msg_settings_premium); Bulletin.UndoButton undoButton = new Bulletin.UndoButton(getContext(), true, resourcesProvider); undoButton.setUndoAction(undoAction); layout.setButton(undoButton); Bulletin.make(fragment, layout, Bulletin.DURATION_SHORT).show(); } else { BulletinFactory.of(fragment).createEmojiBulletin(document, LocaleController.getString("SetAsEmojiStatusInfo", R.string.SetAsEmojiStatusInfo), LocaleController.getString("Undo", R.string.Undo), undoAction).show(); } } } @Override public boolean canSchedule() { return false; } @Override public boolean isInScheduleMode() { if (enterView == null) { return false; } BaseFragment fragment = enterView.getParentFragment(); if (fragment instanceof ChatActivity) { ChatActivity chatActivity = (ChatActivity) fragment; return chatActivity.isInScheduleMode(); } else { return false; } } @Override public void openSet(TLRPC.InputStickerSet set, boolean clearsInputField) {} @Override public long getDialogId() { return 0; } }; } return previewDelegate; } private boolean show, forceClose; @Nullable private ArrayList<MediaDataController.KeywordResult> keywordResults; private boolean clear; private boolean isCopyForbidden; private boolean isSetAsStatusForbidden; public SuggestEmojiView(Context context, int currentAccount, AnchorViewDelegate enterView, Theme.ResourcesProvider resourcesProvider) { super(context); this.currentAccount = currentAccount; this.enterView = enterView; this.resourcesProvider = resourcesProvider; postDelayed(() -> MediaDataController.getInstance(currentAccount).checkStickers(MediaDataController.TYPE_EMOJIPACKS), 260); } public void forbidCopy() { isCopyForbidden = true; } public void forbidSetAsStatus() { isSetAsStatusForbidden = true; } private void createListView() { if (listView != null) { return; } path = new Path(); circlePath = new Path(); containerView = new FrameLayout(getContext()) { @Override protected void dispatchDraw(Canvas canvas) { SuggestEmojiView.this.drawContainerBegin(canvas); super.dispatchDraw(canvas); SuggestEmojiView.this.drawContainerEnd(canvas); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { this.setPadding(horizontalPadding, direction == DIRECTION_TO_BOTTOM ? AndroidUtilities.dp(8) : AndroidUtilities.dp(6.66f), horizontalPadding, direction == DIRECTION_TO_BOTTOM ? AndroidUtilities.dp(6.66f) : AndroidUtilities.dp(8)); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override public void setVisibility(int visibility) { boolean same = getVisibility() == visibility; super.setVisibility(visibility); if (!same) { boolean visible = visibility == View.VISIBLE; if (listView != null) { for (int i = 0; i < listView.getChildCount(); ++i) { if (visible) { ((EmojiImageView) listView.getChildAt(i)).attach(); } else { ((EmojiImageView) listView.getChildAt(i)).detach(); } } } } } }; showFloat1 = new AnimatedFloat(containerView, 120, 350, CubicBezierInterpolator.EASE_OUT_QUINT); showFloat2 = new AnimatedFloat(containerView, 150, 600, CubicBezierInterpolator.EASE_OUT_QUINT); overshootInterpolator = new OvershootInterpolator(.4f); leftGradientAlpha = new AnimatedFloat(containerView, 300, CubicBezierInterpolator.EASE_OUT_QUINT); rightGradientAlpha = new AnimatedFloat(containerView, 300, CubicBezierInterpolator.EASE_OUT_QUINT); arrowXAnimated = new AnimatedFloat(containerView, 200, CubicBezierInterpolator.EASE_OUT_QUINT); listViewCenterAnimated = new AnimatedFloat(containerView, 350, CubicBezierInterpolator.EASE_OUT_QUINT); listViewWidthAnimated = new AnimatedFloat(containerView, 350, CubicBezierInterpolator.EASE_OUT_QUINT); listView = new RecyclerListView(getContext()) { private boolean left, right; @Override public void onScrolled(int dx, int dy) { super.onScrolled(dx, dy); boolean left = canScrollHorizontally(-1); boolean right = canScrollHorizontally(1); if (this.left != left || this.right != right) { if (containerView != null) { containerView.invalidate(); } this.left = left; this.right = right; } } @Override public boolean onInterceptTouchEvent(MotionEvent event) { boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, listView, 0, getPreviewDelegate(), resourcesProvider); return super.onInterceptTouchEvent(event) || result; } }; listView.setAdapter(adapter = new Adapter(this)); LinearLayoutManager layout = new LinearLayoutManager(getContext()); layout.setOrientation(RecyclerView.HORIZONTAL); listView.setLayoutManager(layout); DefaultItemAnimator itemAnimator = new DefaultItemAnimator(); itemAnimator.setDurations(45); itemAnimator.setTranslationInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); listView.setItemAnimator(itemAnimator); listView.setSelectorDrawableColor(Theme.getColor(Theme.key_listSelector, resourcesProvider)); RecyclerListView.OnItemClickListener onItemClickListener; listView.setOnItemClickListener(onItemClickListener = (view, position) -> { onClick(((EmojiImageView) view).emoji); }); listView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, listView, 0, onItemClickListener, getPreviewDelegate(), resourcesProvider)); containerView.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 44 + 8)); addView(containerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 8 + 44 + 8 + 6.66f, Gravity.BOTTOM)); if (enterView != null) { enterView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { if (enterView != null && enterView.getVisibility() == View.VISIBLE) { fireUpdate(); } } }); } } public void setDelegate(AnchorViewDelegate delegate) { this.enterView = delegate; } public void setHorizontalPadding(int padding) { this.horizontalPadding = padding; } public AnchorViewDelegate getDelegate() { return enterView; } public void onTextSelectionChanged(int start, int end) { fireUpdate(); } public boolean isShown() { return show; } public int getDirection() { return direction; } public void setDirection(int direction) { if (this.direction != direction) { this.direction = direction; requestLayout(); } } public void updateColors() { if (backgroundPaint != null) { backgroundPaint.setColor(Theme.getColor(Theme.key_chat_stickersHintPanel, resourcesProvider)); } Theme.chat_gradientLeftDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_stickersHintPanel, resourcesProvider), PorterDuff.Mode.MULTIPLY)); Theme.chat_gradientRightDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_stickersHintPanel, resourcesProvider), PorterDuff.Mode.MULTIPLY)); } public void forceClose() { if (updateRunnable != null) { AndroidUtilities.cancelRunOnUIThread(updateRunnable); updateRunnable = null; } show = false; forceClose = true; if (containerView != null) { containerView.invalidate(); } } private Runnable updateRunnable; public void fireUpdate() { if (updateRunnable != null) { AndroidUtilities.cancelRunOnUIThread(updateRunnable); } AndroidUtilities.runOnUIThread(updateRunnable = this::update, 16); } private void update() { updateRunnable = null; if (enterView == null || enterView.getEditField() == null || enterView.getFieldText() == null) { show = false; forceClose = true; if (containerView != null) { containerView.invalidate(); } return; } int selectionStart = enterView.getEditField().getSelectionStart(); int selectionEnd = enterView.getEditField().getSelectionEnd(); if (selectionStart != selectionEnd) { show = false; if (containerView != null) { containerView.invalidate(); } return; } CharSequence text = enterView.getFieldText(); Emoji.EmojiSpan[] emojiSpans = (text instanceof Spanned) ? ((Spanned) text).getSpans(Math.max(0, selectionEnd - 24), selectionEnd, Emoji.EmojiSpan.class) : null; if (emojiSpans != null && emojiSpans.length > 0 && SharedConfig.suggestAnimatedEmoji && UserConfig.getInstance(currentAccount).isPremium()) { Emoji.EmojiSpan lastEmoji = emojiSpans[emojiSpans.length - 1]; if (lastEmoji != null) { int emojiStart = ((Spanned) text).getSpanStart(lastEmoji); int emojiEnd = ((Spanned) text).getSpanEnd(lastEmoji); if (selectionStart == emojiEnd) { String emoji = text.toString().substring(emojiStart, emojiEnd); show = true; createListView(); // containerView.setVisibility(View.VISIBLE); arrowToSpan = lastEmoji; arrowToStart = arrowToEnd = null; searchAnimated(emoji); if (containerView != null) { containerView.invalidate(); } return; } } } else { AnimatedEmojiSpan[] aspans = (text instanceof Spanned) ? ((Spanned) text).getSpans(Math.max(0, selectionEnd), selectionEnd, AnimatedEmojiSpan.class) : null; if ((aspans == null || aspans.length == 0) && selectionEnd < 52) { show = true; createListView(); // containerView.setVisibility(View.VISIBLE); arrowToSpan = null; searchKeywords(text.toString().substring(0, selectionEnd)); if (containerView != null) { containerView.invalidate(); } return; } } if (searchRunnable != null) { AndroidUtilities.cancelRunOnUIThread(searchRunnable); searchRunnable = null; } show = false; if (containerView != null) { containerView.invalidate(); } } private int lastQueryType; private String lastQuery; private int lastQueryId; private String[] lastLang; private Runnable searchRunnable; private long lastLangChangedTime = 0; /** * The user needs time to change the locale. We estimate this time to be at least 360 ms. */ private String[] detectKeyboardLangThrottleFirstWithDelay() { long currentTime = System.currentTimeMillis(); int delay = 360; if (lastLang == null || Math.abs(currentTime - lastLangChangedTime) > delay) { lastLangChangedTime = currentTime; return AndroidUtilities.getCurrentKeyboardLanguage(); } else { lastLangChangedTime = currentTime; } return lastLang; } private void searchKeywords(String query) { if (query == null) { return; } if (lastQuery != null && lastQueryType == 1 && lastQuery.equals(query) && !clear && keywordResults != null && !keywordResults.isEmpty()) { forceClose = false; createListView(); containerView.setVisibility(View.VISIBLE); lastSpanY = AndroidUtilities.dp(10); containerView.invalidate(); return; } final int id = ++lastQueryId; String[] lang = detectKeyboardLangThrottleFirstWithDelay(); if (lastLang == null || !Arrays.equals(lang, lastLang)) { MediaDataController.getInstance(currentAccount).fetchNewEmojiKeywords(lang); } lastLang = lang; if (searchRunnable != null) { AndroidUtilities.cancelRunOnUIThread(searchRunnable); searchRunnable = null; } searchRunnable = () -> { MediaDataController.getInstance(currentAccount).getEmojiSuggestions(lang, query, true, (param, alias) -> { if (id == lastQueryId) { lastQueryType = 1; lastQuery = query; if (param != null && !param.isEmpty()) { clear = false; forceClose = false; createListView(); if (containerView != null) { containerView.setVisibility(View.VISIBLE); } lastSpanY = AndroidUtilities.dp(10); keywordResults = param; arrowToStart = 0; arrowToEnd = query.length(); if (containerView != null) { containerView.invalidate(); } if (adapter != null) { adapter.notifyDataSetChanged(); } } else { keywordResults = null; clear = true; forceClose(); } } }, SharedConfig.suggestAnimatedEmoji && UserConfig.getInstance(currentAccount).isPremium()); }; if (keywordResults == null || keywordResults.isEmpty()) { AndroidUtilities.runOnUIThread(searchRunnable, 600); } else { searchRunnable.run(); } } private void searchAnimated(String emoji) { if (emoji == null) { return; } if (lastQuery != null && lastQueryType == 2 && lastQuery.equals(emoji) && !clear && keywordResults != null && !keywordResults.isEmpty()) { forceClose = false; createListView(); if (containerView != null) { containerView.setVisibility(View.VISIBLE); containerView.invalidate(); } return; } final int id = ++lastQueryId; if (searchRunnable != null) { AndroidUtilities.cancelRunOnUIThread(searchRunnable); } searchRunnable = () -> { ArrayList<MediaDataController.KeywordResult> standard = new ArrayList<>(1); standard.add(new MediaDataController.KeywordResult(emoji, null)); MediaDataController.getInstance(currentAccount).fillWithAnimatedEmoji(standard, 15, false, false, false, () -> { if (id == lastQueryId) { lastQuery = emoji; lastQueryType = 2; standard.remove(standard.size() - 1); if (!standard.isEmpty()) { clear = false; forceClose = false; createListView(); if (containerView != null) { containerView.setVisibility(View.VISIBLE); containerView.invalidate(); } keywordResults = standard; if (adapter != null) { adapter.notifyDataSetChanged(); } } else { clear = true; forceClose(); } } }); }; if (keywordResults == null || keywordResults.isEmpty()) { AndroidUtilities.runOnUIThread(searchRunnable, 600); } else { searchRunnable.run(); } } private CharSequence makeEmoji(String emojiSource) { Paint.FontMetricsInt fontMetricsInt = null; if (enterView.getEditField() != null) { fontMetricsInt = enterView.getEditField().getPaint().getFontMetricsInt(); } if (fontMetricsInt == null) { Paint paint = new Paint(); paint.setTextSize(AndroidUtilities.dp(18)); fontMetricsInt = paint.getFontMetricsInt(); } CharSequence emoji; if (emojiSource != null && emojiSource.startsWith("animated_")) { try { long documentId = Long.parseLong(emojiSource.substring(9)); TLRPC.Document document = AnimatedEmojiDrawable.findDocument(currentAccount, documentId); emoji = new SpannableString(MessageObject.findAnimatedEmojiEmoticon(document)); AnimatedEmojiSpan span; if (document == null) { span = new AnimatedEmojiSpan(documentId, fontMetricsInt); } else { span = new AnimatedEmojiSpan(document, fontMetricsInt); } ((SpannableString) emoji).setSpan(span, 0, emoji.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Exception ignore) { return null; } } else { emoji = emojiSource; emoji = Emoji.replaceEmoji(emoji, fontMetricsInt, AndroidUtilities.dp(20), true); } return emoji; } private void onClick(String emojiSource) { if (!show || enterView == null || !(enterView.getFieldText() instanceof Spanned)) { return; } int start, end; if (arrowToSpan != null) { start = ((Spanned) enterView.getFieldText()).getSpanStart(arrowToSpan); end = ((Spanned) enterView.getFieldText()).getSpanEnd(arrowToSpan); } else if (arrowToStart != null && arrowToEnd != null) { start = arrowToStart; end = arrowToEnd; arrowToStart = arrowToEnd = null; } else { return; } Editable editable = enterView.getEditText(); if (editable == null || start < 0 || end < 0 || start > editable.length() || end > editable.length()) { return; } if (arrowToSpan != null) { if (enterView.getFieldText() instanceof Spannable) { ((Spannable) enterView.getFieldText()).removeSpan(arrowToSpan); } arrowToSpan = null; } String fromString = editable.toString(); String replacing = fromString.substring(start, end); int replacingLength = replacing.length(); for (int i = end - replacingLength; i >= 0; i -= replacingLength) { if (fromString.substring(i, i + replacingLength).equals(replacing)) { CharSequence emoji = makeEmoji(emojiSource); if (emoji != null) { AnimatedEmojiSpan[] animatedEmojiSpans = editable.getSpans(i, i + replacingLength, AnimatedEmojiSpan.class); if (animatedEmojiSpans != null && animatedEmojiSpans.length > 0) { break; } Emoji.EmojiSpan[] emojiSpans = editable.getSpans(i, i + replacingLength, Emoji.EmojiSpan.class); if (emojiSpans != null) { for (int j = 0; j < emojiSpans.length; ++j) { editable.removeSpan(emojiSpans[j]); } } editable.replace(i, i + replacingLength, emoji); } else { break; } } else { break; } } try { performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); } catch (Exception ignore) {} Emoji.addRecentEmoji(emojiSource); show = false; forceClose = true; lastQueryType = 0; if (containerView != null) { containerView.invalidate(); } } private Path path, circlePath; private Paint backgroundPaint; private AnimatedFloat showFloat1; private AnimatedFloat showFloat2; private OvershootInterpolator overshootInterpolator; private AnimatedFloat leftGradientAlpha; private AnimatedFloat rightGradientAlpha; private Emoji.EmojiSpan arrowToSpan; private float lastSpanY; private Integer arrowToStart, arrowToEnd; private float arrowX; private AnimatedFloat arrowXAnimated; private AnimatedFloat listViewCenterAnimated; private AnimatedFloat listViewWidthAnimated; private void drawContainerBegin(Canvas canvas) { if (enterView != null && enterView.getEditField() != null) { if (arrowToSpan != null && arrowToSpan.drawn) { arrowX = enterView.getEditField().getX() + enterView.getEditField().getPaddingLeft() + arrowToSpan.lastDrawX; lastSpanY = arrowToSpan.lastDrawY; } else if (arrowToStart != null && arrowToEnd != null) { arrowX = enterView.getEditField().getX() + enterView.getEditField().getPaddingLeft() + AndroidUtilities.dp(12); } } final boolean show = this.show && !forceClose && keywordResults != null && !keywordResults.isEmpty() && !clear; final float showT1 = showFloat1.set(show ? 1f : 0f); final float showT2 = showFloat2.set(show ? 1f : 0f); final float arrowX = arrowXAnimated.set(this.arrowX); if (showT1 <= 0 && showT2 <= 0 && !show) { containerView.setVisibility(View.GONE); } path.rewind(); float listViewLeft = listView.getLeft(); float listViewRight = listView.getLeft() + (keywordResults == null ? 0 : keywordResults.size()) * AndroidUtilities.dp(44); boolean force = listViewWidthAnimated.get() <= 0; float width = listViewRight - listViewLeft <= 0 ? listViewWidthAnimated.get() : listViewWidthAnimated.set(listViewRight - listViewLeft, force); float center = listViewCenterAnimated.set((listViewLeft + listViewRight) / 2f, force); if (enterView != null && enterView.getEditField() != null) { if (direction == DIRECTION_TO_BOTTOM) { containerView.setTranslationY(-enterView.getEditField().getHeight() - enterView.getEditField().getScrollY() + lastSpanY + AndroidUtilities.dp(5)); } else if (direction == DIRECTION_TO_TOP) { containerView.setTranslationY(-getMeasuredHeight() - enterView.getEditField().getScrollY() + lastSpanY + AndroidUtilities.dp(20) + containerView.getHeight()); } } int listViewPaddingLeft = (int) Math.max(this.arrowX - Math.max(width / 4f, Math.min(width / 2f, AndroidUtilities.dp(66))) - listView.getLeft(), 0); if (listView.getPaddingLeft() != listViewPaddingLeft) { int dx = listView.getPaddingLeft() - listViewPaddingLeft; listView.setPadding(listViewPaddingLeft, 0, 0, 0); listView.scrollBy(dx, 0); } int listViewPaddingLeftI = (int) Math.max(arrowX - Math.max(width / 4f, Math.min(width / 2f, AndroidUtilities.dp(66))) - listView.getLeft(), 0); listView.setTranslationX(listViewPaddingLeftI - listViewPaddingLeft); float left = center - width / 2f + listView.getPaddingLeft() + listView.getTranslationX(); float top = listView.getTop() + listView.getTranslationY() + listView.getPaddingTop() + (direction == DIRECTION_TO_BOTTOM ? 0: AndroidUtilities.dp(6.66f)); float right = Math.min(center + width / 2f + listView.getPaddingLeft() + listView.getTranslationX(), getWidth() - containerView.getPaddingRight()); float bottom = listView.getBottom() + listView.getTranslationY() - (direction == DIRECTION_TO_BOTTOM ? AndroidUtilities.dp(6.66f) : 0); float R = Math.min(AndroidUtilities.dp(9), width / 2f), D = R * 2; if (direction == DIRECTION_TO_BOTTOM) { AndroidUtilities.rectTmp.set(left, bottom - D, left + D, bottom); path.arcTo(AndroidUtilities.rectTmp, 90, 90); AndroidUtilities.rectTmp.set(left, top, left + D, top + D); path.arcTo(AndroidUtilities.rectTmp, -180, 90); AndroidUtilities.rectTmp.set(right - D, top, right, top + D); path.arcTo(AndroidUtilities.rectTmp, -90, 90); AndroidUtilities.rectTmp.set(right - D, bottom - D, right, bottom); path.arcTo(AndroidUtilities.rectTmp, 0, 90); path.lineTo(arrowX + AndroidUtilities.dp(8.66f), bottom); path.lineTo(arrowX, bottom + AndroidUtilities.dp(6.66f)); path.lineTo(arrowX - AndroidUtilities.dp(8.66f), bottom); } else if (direction == DIRECTION_TO_TOP) { AndroidUtilities.rectTmp.set(right - D, top, right, top + D); path.arcTo(AndroidUtilities.rectTmp, -90, 90); AndroidUtilities.rectTmp.set(right - D, bottom - D, right, bottom); path.arcTo(AndroidUtilities.rectTmp, 0, 90); AndroidUtilities.rectTmp.set(left, bottom - D, left + D, bottom); path.arcTo(AndroidUtilities.rectTmp, 90, 90); AndroidUtilities.rectTmp.set(left, top, left + D, top + D); path.arcTo(AndroidUtilities.rectTmp, -180, 90); path.lineTo(arrowX - AndroidUtilities.dp(8.66f), top); path.lineTo(arrowX, top - AndroidUtilities.dp(6.66f)); path.lineTo(arrowX + AndroidUtilities.dp(8.66f), top); } path.close(); if (backgroundPaint == null) { backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); backgroundPaint.setPathEffect(new CornerPathEffect(AndroidUtilities.dp(2))); backgroundPaint.setShadowLayer(AndroidUtilities.dp(4.33f), 0, AndroidUtilities.dp(1 / 3f), 0x33000000); backgroundPaint.setColor(Theme.getColor(Theme.key_chat_stickersHintPanel, resourcesProvider)); } if (showT1 < 1) { circlePath.rewind(); float cx = arrowX, cy = (direction == DIRECTION_TO_BOTTOM) ? bottom + AndroidUtilities.dp(6.66f) : top - AndroidUtilities.dp(6.66f); float toRadius = (float) Math.sqrt(Math.max( Math.max( Math.pow(cx - left, 2) + Math.pow(cy - top, 2), Math.pow(cx - right, 2) + Math.pow(cy - top, 2) ), Math.max( Math.pow(cx - left, 2) + Math.pow(cy - bottom, 2), Math.pow(cx - right, 2) + Math.pow(cy - bottom, 2) ) )); circlePath.addCircle(cx, cy, toRadius * showT1, Path.Direction.CW); canvas.save(); canvas.clipPath(circlePath); canvas.saveLayerAlpha(0, 0, getWidth(), getHeight(), (int) (255 * showT1), Canvas.ALL_SAVE_FLAG); } canvas.drawPath(path, backgroundPaint); canvas.save(); canvas.clipPath(path); } public void drawContainerEnd(Canvas canvas) { final float width = listViewWidthAnimated.get(); final float center = listViewCenterAnimated.get(); float left = center - width / 2f + listView.getPaddingLeft() + listView.getTranslationX(); float top = listView.getTop() + listView.getPaddingTop(); float right = Math.min(center + width / 2f + listView.getPaddingLeft() + listView.getTranslationX(), getWidth() - containerView.getPaddingRight()); float bottom = listView.getBottom(); float leftAlpha = leftGradientAlpha.set(listView.canScrollHorizontally(-1) ? 1f : 0f); if (leftAlpha > 0) { Theme.chat_gradientRightDrawable.setBounds((int) left, (int) top, (int) left + AndroidUtilities.dp(32), (int) bottom); Theme.chat_gradientRightDrawable.setAlpha((int) (255 * leftAlpha)); Theme.chat_gradientRightDrawable.draw(canvas); } float rightAlpha = rightGradientAlpha.set(listView.canScrollHorizontally(1) ? 1f : 0f); if (rightAlpha > 0) { Theme.chat_gradientLeftDrawable.setBounds((int) right - AndroidUtilities.dp(32), (int) top, (int) right, (int) bottom); Theme.chat_gradientLeftDrawable.setAlpha((int) (255 * rightAlpha)); Theme.chat_gradientLeftDrawable.draw(canvas); } canvas.restore(); if (showFloat1.get() < 1) { canvas.restore(); canvas.restore(); } } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (listView == null) { return super.dispatchTouchEvent(ev); } final float width = listViewWidthAnimated.get(); final float center = listViewCenterAnimated.get(); AndroidUtilities.rectTmp.set( center - width / 2f + listView.getPaddingLeft() + listView.getTranslationX(), listView.getTop() + listView.getPaddingTop(), Math.min(center + width / 2f + listView.getPaddingLeft() + listView.getTranslationX(), getWidth() - containerView.getPaddingRight()), listView.getBottom() ); AndroidUtilities.rectTmp.offset(containerView.getX(), containerView.getY()); if (show && AndroidUtilities.rectTmp.contains(ev.getX(), ev.getY())) { return super.dispatchTouchEvent(ev); } else { if (ev.getAction() == MotionEvent.ACTION_DOWN) { return false; } else { if (ev.getAction() == MotionEvent.ACTION_DOWN) { ev.setAction(MotionEvent.ACTION_CANCEL); } return super.dispatchTouchEvent(ev); } } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.newEmojiSuggestionsAvailable); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.emojiLoaded); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.newEmojiSuggestionsAvailable); } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.newEmojiSuggestionsAvailable) { if (keywordResults != null && !keywordResults.isEmpty()) { fireUpdate(); } } else if (id == NotificationCenter.emojiLoaded) { if (listView != null) { for (int i = 0; i < listView.getChildCount(); ++i) { listView.getChildAt(i).invalidate(); } } } } protected int emojiCacheType() { return AnimatedEmojiDrawable.CACHE_TYPE_KEYBOARD; } public void invalidateContent() { if (containerView != null) { containerView.invalidate(); } } public class EmojiImageView extends View { private String emoji; public Drawable drawable; private boolean attached; private int direction = DIRECTION_TO_BOTTOM; private AnimatedFloat pressed = new AnimatedFloat(this, 350, new OvershootInterpolator(5.0f)); public EmojiImageView(Context context) { super(context); } private final int paddingDp = 3; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setPadding(AndroidUtilities.dp(paddingDp), AndroidUtilities.dp(paddingDp + (direction == DIRECTION_TO_BOTTOM ? 0 : 6.66f)), AndroidUtilities.dp(paddingDp), AndroidUtilities.dp(paddingDp + (direction == DIRECTION_TO_BOTTOM ? 6.66f : 0))); super.onMeasure( MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(44), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(44 + 8), MeasureSpec.EXACTLY) ); } private void setEmoji(String emoji, int direction) { this.emoji = emoji; if (emoji != null && emoji.startsWith("animated_")) { try { long documentId = Long.parseLong(emoji.substring(9)); if (!(drawable instanceof AnimatedEmojiDrawable) || ((AnimatedEmojiDrawable) drawable).getDocumentId() != documentId) { setImageDrawable(AnimatedEmojiDrawable.make(UserConfig.selectedAccount, emojiCacheType(), documentId)); } } catch (Exception ignore) { setImageDrawable(null); } } else { setImageDrawable(Emoji.getEmojiBigDrawable(emoji)); } if (this.direction != direction) { this.direction = direction; requestLayout(); } } public void setImageDrawable(@Nullable Drawable drawable) { if (this.drawable instanceof AnimatedEmojiDrawable) { ((AnimatedEmojiDrawable) this.drawable).removeView(this); } this.drawable = drawable; if (drawable instanceof AnimatedEmojiDrawable && attached) { ((AnimatedEmojiDrawable) drawable).addView(this); } } public void setDirection(int direction) { this.direction = direction; invalidate(); } @Override public void setPressed(boolean pressed) { super.setPressed(pressed); invalidate(); } @Override protected void dispatchDraw(Canvas canvas) { float scale = 0.8f + 0.2f * (1f - pressed.set(isPressed() ? 1f : 0f)); if (drawable != null) { int cx = getWidth() / 2; int cy = (getHeight() - getPaddingBottom() + getPaddingTop()) / 2; drawable.setBounds(getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); canvas.scale(scale, scale, cx, cy); if (drawable instanceof AnimatedEmojiDrawable) { ((AnimatedEmojiDrawable) drawable).setTime(System.currentTimeMillis()); } drawable.draw(canvas); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); attach(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); detach(); } public void detach() { if (drawable instanceof AnimatedEmojiDrawable) { ((AnimatedEmojiDrawable) drawable).removeView(this); } attached = false; } public void attach() { if (drawable instanceof AnimatedEmojiDrawable) { ((AnimatedEmojiDrawable) drawable).addView(this); } attached = true; } } private class Adapter extends RecyclerListView.SelectionAdapter { SuggestEmojiView suggestEmojiView; public Adapter(SuggestEmojiView suggestEmojiView) { this.suggestEmojiView = suggestEmojiView; } @Override public long getItemId(int position) { return suggestEmojiView.keywordResults == null ? 0 : suggestEmojiView.keywordResults.get(position).emoji.hashCode(); } @Override public boolean isEnabled(RecyclerView.ViewHolder holder) { return true; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new RecyclerListView.Holder(new EmojiImageView(suggestEmojiView.getContext())); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { ((EmojiImageView) holder.itemView).setEmoji(suggestEmojiView.keywordResults == null ? null : suggestEmojiView.keywordResults.get(position).emoji, suggestEmojiView.getDirection()); } @Override public int getItemCount() { return suggestEmojiView.keywordResults == null ? 0 : suggestEmojiView.keywordResults.size(); } } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Components/SuggestEmojiView.java
2,164
package org.telegram.ui.Components; import static org.telegram.messenger.AndroidUtilities.lerp; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.TimeInterpolator; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.util.Log; import android.util.Pair; import android.view.Gravity; import android.view.View; import android.view.accessibility.AccessibilityNodeInfo; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.graphics.ColorUtils; import org.checkerframework.checker.units.qual.A; import org.checkerframework.checker.units.qual.C; import org.telegram.messenger.AndroidUtilities; import org.telegram.ui.ActionBar.Theme; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.IntStream; public class AnimatedTextView extends View { public static class AnimatedTextDrawable extends Drawable { private final TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); private int gravity = 0; private boolean isRTL = false; private float currentWidth, currentHeight; private Part[] currentParts; private CharSequence currentText; private float oldWidth, oldHeight; private Part[] oldParts; private CharSequence oldText; public void setSplitByWords(boolean b) { splitByWords = b; } private class Part { AnimatedEmojiSpan.EmojiGroupedSpans emoji; StaticLayout layout; float offset; int toOppositeIndex; float left, width; public Part(StaticLayout layout, float offset, int toOppositeIndex) { this.layout = layout; this.toOppositeIndex = toOppositeIndex; layout(offset); if (getCallback() instanceof View) { View view = (View) getCallback(); emoji = AnimatedEmojiSpan.update(emojiCacheType, view, emoji, layout); } } public void detach() { if (getCallback() instanceof View) { View view = (View) getCallback(); AnimatedEmojiSpan.release(view, emoji); } } public void layout(float offset) { this.offset = offset; this.left = layout == null || layout.getLineCount() <= 0 ? 0 : layout.getLineLeft(0); this.width = layout == null || layout.getLineCount() <= 0 ? 0 : layout.getLineWidth(0); } public void draw(Canvas canvas, float alpha) { layout.draw(canvas); AnimatedEmojiSpan.drawAnimatedEmojis(canvas, layout, emoji, 0, null, 0, 0, 0, alpha, emojiColorFilter); } } private int emojiCacheType = AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES; public void setEmojiCacheType(int cacheType) { this.emojiCacheType = cacheType; } private float t = 0; private boolean moveDown = true; private ValueAnimator animator; private CharSequence toSetText; private boolean toSetTextMoveDown; private long animateDelay = 0; private long animateDuration = 320; private TimeInterpolator animateInterpolator = CubicBezierInterpolator.EASE_OUT_QUINT; private float moveAmplitude = .3f; private float scaleAmplitude = 0; private int alpha = 255; private final Rect bounds = new Rect(); private boolean splitByWords; private boolean preserveIndex; private boolean startFromEnd; public void setHacks(boolean splitByWords, boolean preserveIndex, boolean startFromEnd) { this.splitByWords = splitByWords; this.preserveIndex = preserveIndex; this.startFromEnd = startFromEnd; } private Runnable onAnimationFinishListener; private boolean allowCancel; public boolean ignoreRTL; public boolean updateAll; private int overrideFullWidth; public void setOverrideFullWidth(int value) { overrideFullWidth = value; } private float rightPadding; private boolean ellipsizeByGradient; private LinearGradient ellipsizeGradient; private Matrix ellipsizeGradientMatrix; private Paint ellipsizePaint; private boolean includeFontPadding = true; public AnimatedTextDrawable() { this(false, false, false); } public AnimatedTextDrawable(boolean splitByWords, boolean preserveIndex, boolean startFromEnd) { this.splitByWords = splitByWords; this.preserveIndex = preserveIndex; this.startFromEnd = startFromEnd; } public void setAllowCancel(boolean allowCancel) { this.allowCancel = allowCancel; } public void setEllipsizeByGradient(boolean enabled) { ellipsizeByGradient = enabled; invalidateSelf(); } public void setOnAnimationFinishListener(Runnable listener) { onAnimationFinishListener = listener; } private void applyAlphaInternal(float t) { textPaint.setAlpha((int) (alpha * t)); if (shadowed) { textPaint.setShadowLayer(shadowRadius, shadowDx, shadowDy, Theme.multAlpha(shadowColor, t)); } } @Override public void draw(@NonNull Canvas canvas) { if (ellipsizeByGradient) { AndroidUtilities.rectTmp.set(bounds); AndroidUtilities.rectTmp.right -= rightPadding; canvas.saveLayerAlpha(AndroidUtilities.rectTmp, 255, Canvas.ALL_SAVE_FLAG); } canvas.save(); canvas.translate(bounds.left, bounds.top); int fullWidth = bounds.width(); int fullHeight = bounds.height(); if (currentParts != null && oldParts != null && t != 1) { float width = lerp(oldWidth, currentWidth, t); float height = lerp(oldHeight, currentHeight, t); canvas.translate(0, (fullHeight - height) / 2f); for (int i = 0; i < currentParts.length; ++i) { Part current = currentParts[i]; int j = current.toOppositeIndex; float x = current.offset, y = 0; if (isRTL && !ignoreRTL) { x = currentWidth - (x + current.width); } if (j >= 0) { Part old = oldParts[j]; float oldX = old.offset; if (isRTL && !ignoreRTL) { oldX = oldWidth - (oldX + old.width); } x = lerp(oldX - old.left, x - current.left, t); applyAlphaInternal(1f); } else { x -= current.left; y = -textPaint.getTextSize() * moveAmplitude * (1f - t) * (moveDown ? 1f : -1f); applyAlphaInternal(t); } canvas.save(); float lwidth = j >= 0 ? width : currentWidth; if ((gravity | ~Gravity.LEFT) != ~0) { if ((gravity | ~Gravity.RIGHT) == ~0) { x += fullWidth - lwidth; } else if ((gravity | ~Gravity.CENTER_HORIZONTAL) == ~0) { x += (fullWidth - lwidth) / 2f; } else if (isRTL && !ignoreRTL) { x += fullWidth - lwidth; } } canvas.translate(x, y); if (j < 0 && scaleAmplitude > 0) { final float s = lerp(1f - scaleAmplitude, 1f, t); canvas.scale(s, s, current.width / 2f, current.layout.getHeight() / 2f); } current.draw(canvas, j >= 0 ? 1f : t); canvas.restore(); } for (int i = 0; i < oldParts.length; ++i) { Part old = oldParts[i]; int j = old.toOppositeIndex; if (j >= 0) { continue; } float x = old.offset; float y = textPaint.getTextSize() * moveAmplitude * t * (moveDown ? 1f : -1f); applyAlphaInternal(1f - t); canvas.save(); if (isRTL && !ignoreRTL) { x = oldWidth - (x + old.width); } x -= old.left; if ((gravity | ~Gravity.LEFT) != ~0) { if ((gravity | ~Gravity.RIGHT) == ~0) { x += fullWidth - oldWidth; } else if ((gravity | ~Gravity.CENTER_HORIZONTAL) == ~0) { x += (fullWidth - oldWidth) / 2f; } else if (isRTL && !ignoreRTL) { x += fullWidth - oldWidth; } } canvas.translate(x, y); if (scaleAmplitude > 0) { final float s = lerp(1f, 1f - scaleAmplitude, t); canvas.scale(s, s, old.width / 2f, old.layout.getHeight() / 2f); } old.draw(canvas, 1f - t); canvas.restore(); } } else { canvas.translate(0, (fullHeight - currentHeight) / 2f); if (currentParts != null) { applyAlphaInternal(1f); for (int i = 0; i < currentParts.length; ++i) { canvas.save(); Part current = currentParts[i]; float x = current.offset; if (isRTL && !ignoreRTL) { x = currentWidth - (x + current.width); } x -= current.left; if ((gravity | ~Gravity.LEFT) != ~0) { if ((gravity | ~Gravity.RIGHT) == ~0) { x += fullWidth - currentWidth; } else if ((gravity | ~Gravity.CENTER_HORIZONTAL) == ~0) { x += (fullWidth - currentWidth) / 2f; } else if (isRTL && !ignoreRTL) { x += fullWidth - currentWidth; } } canvas.translate(x, 0); current.draw(canvas, 1f); canvas.restore(); } } } canvas.restore(); if (ellipsizeByGradient) { final float w = AndroidUtilities.dp(16); if (ellipsizeGradient == null) { ellipsizeGradient = new LinearGradient(0, 0, w, 0, new int[] {0x00ff0000, 0xffff0000}, new float[] {0, 1}, Shader.TileMode.CLAMP); ellipsizeGradientMatrix = new Matrix(); ellipsizePaint = new Paint(Paint.ANTI_ALIAS_FLAG); ellipsizePaint.setShader(ellipsizeGradient); ellipsizePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); } ellipsizeGradientMatrix.reset(); ellipsizeGradientMatrix.postTranslate(bounds.right - rightPadding - w, 0); ellipsizeGradient.setLocalMatrix(ellipsizeGradientMatrix); canvas.save(); canvas.drawRect(bounds.right - rightPadding - w, bounds.top, bounds.right - rightPadding + AndroidUtilities.dp(1), bounds.bottom, ellipsizePaint); canvas.restore(); canvas.restore(); } } public void setRightPadding(float rightPadding) { this.rightPadding = rightPadding; invalidateSelf(); } public float getRightPadding() { return this.rightPadding; } public void cancelAnimation() { if (animator != null) { animator.cancel(); } } public boolean isAnimating() { return animator != null && animator.isRunning(); } public void setText(CharSequence text) { setText(text, true); } public void setText(CharSequence text, boolean animated) { setText(text, animated, true); } public void setText(CharSequence text, boolean animated, boolean moveDown) { if (this.currentText == null || text == null) { animated = false; } if (text == null) { text = ""; } final int width = overrideFullWidth > 0 ? overrideFullWidth : bounds.width(); if (animated) { if (allowCancel) { if (animator != null) { animator.cancel(); animator = null; } } else if (isAnimating()) { toSetText = text; toSetTextMoveDown = moveDown; return; } if (text.equals(currentText)) { return; } oldText = currentText; currentText = text; ArrayList<Part> currentParts = new ArrayList<>(); ArrayList<Part> oldParts = new ArrayList<>(); currentWidth = currentHeight = 0; oldWidth = oldHeight = 0; isRTL = AndroidUtilities.isRTL(currentText); // order execution matters RegionCallback onEqualRegion = (part, from, to) -> { StaticLayout layout = makeLayout(part, width - (int) Math.ceil(Math.min(currentWidth, oldWidth))); final Part currentPart = new Part(layout, currentWidth, oldParts.size()); final Part oldPart = new Part(layout, oldWidth, oldParts.size()); currentParts.add(currentPart); oldParts.add(oldPart); float partWidth = currentPart.width; currentWidth += partWidth; oldWidth += partWidth; currentHeight = Math.max(currentHeight, layout.getHeight()); oldHeight = Math.max(oldHeight, layout.getHeight()); }; RegionCallback onNewPart = (part, from, to) -> { StaticLayout layout = makeLayout(part, width - (int) Math.ceil(currentWidth)); final Part currentPart = new Part(layout, currentWidth, -1); currentParts.add(currentPart); currentWidth += currentPart.width; currentHeight = Math.max(currentHeight, layout.getHeight()); }; RegionCallback onOldPart = (part, from, to) -> { StaticLayout layout = makeLayout(part, width - (int) Math.ceil(oldWidth)); final Part oldPart = new Part(layout, oldWidth, -1); oldParts.add(oldPart); oldWidth += oldPart.width; oldHeight = Math.max(oldHeight, layout.getHeight()); }; CharSequence from = splitByWords ? new WordSequence(oldText) : oldText; CharSequence to = splitByWords ? new WordSequence(currentText) : currentText; diff(from, to, onEqualRegion, onNewPart, onOldPart); // betterDiff(from, to, onEqualRegion, onNewPart, onOldPart); clearCurrentParts(); if (this.currentParts == null || this.currentParts.length != currentParts.size()) { this.currentParts = new Part[currentParts.size()]; } currentParts.toArray(this.currentParts); clearOldParts(); if (this.oldParts == null || this.oldParts.length != oldParts.size()) { this.oldParts = new Part[oldParts.size()]; } oldParts.toArray(this.oldParts); if (animator != null) { animator.cancel(); } this.moveDown = moveDown; animator = ValueAnimator.ofFloat(t = 0f, 1f); if (widthUpdatedListener != null) { widthUpdatedListener.run(); } animator.addUpdateListener(anm -> { t = (float) anm.getAnimatedValue(); invalidateSelf(); if (widthUpdatedListener != null) { widthUpdatedListener.run(); } }); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); clearOldParts(); oldText = null; oldWidth = 0; t = 0; invalidateSelf(); if (widthUpdatedListener != null) { widthUpdatedListener.run(); } animator = null; if (toSetText != null) { setText(toSetText, true, toSetTextMoveDown); toSetText = null; toSetTextMoveDown = false; } else if (onAnimationFinishListener != null) { onAnimationFinishListener.run(); } } }); animator.setStartDelay(animateDelay); animator.setDuration(animateDuration); animator.setInterpolator(animateInterpolator); animator.start(); } else { if (animator != null) { animator.cancel(); } animator = null; toSetText = null; toSetTextMoveDown = false; t = 0; if (!text.equals(currentText)) { clearCurrentParts(); currentParts = new Part[1]; currentParts[0] = new Part(makeLayout(currentText = text, width), 0, -1); currentWidth = currentParts[0].width; currentHeight = currentParts[0].layout.getHeight(); isRTL = AndroidUtilities.isRTL(currentText); } clearOldParts(); oldText = null; oldWidth = 0; oldHeight = 0; invalidateSelf(); if (widthUpdatedListener != null) { widthUpdatedListener.run(); } } } private void clearOldParts() { if (oldParts != null) { for (int i = 0; i < oldParts.length; ++i) { oldParts[i].detach(); } } oldParts = null; } private void clearCurrentParts() { if (oldParts != null) { for (int i = 0; i < oldParts.length; ++i) { oldParts[i].detach(); } } oldParts = null; } public CharSequence getText() { return currentText; } public float getWidth() { return Math.max(currentWidth, oldWidth); } public float getCurrentWidth() { if (currentParts != null && oldParts != null) { return lerp(oldWidth, currentWidth, t); } return currentWidth; } public float getAnimateToWidth() { return currentWidth; } public float getMaxWidth(AnimatedTextDrawable otherTextDrawable) { if (oldParts == null || otherTextDrawable.oldParts == null) { return Math.max(getCurrentWidth(), otherTextDrawable.getCurrentWidth()); } return lerp( Math.max(oldWidth, otherTextDrawable.oldWidth), Math.max(currentWidth, otherTextDrawable.currentWidth), Math.max(t, otherTextDrawable.t) ); } public float getHeight() { return currentHeight; } private StaticLayout makeLayout(CharSequence textPart, int width) { if (width <= 0) { width = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return StaticLayout.Builder.obtain(textPart, 0, textPart.length(), textPaint, width) .setMaxLines(1) .setLineSpacing(0, 1) .setAlignment(Layout.Alignment.ALIGN_NORMAL) .setEllipsize(TextUtils.TruncateAt.END) .setEllipsizedWidth(width) .setIncludePad(includeFontPadding) .build(); } else { return new StaticLayout( textPart, 0, textPart.length(), textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1, 0, includeFontPadding, TextUtils.TruncateAt.END, width ); } } private static class WordSequence implements CharSequence { private static final char SPACE = ' '; private final CharSequence[] words; private final int length; public WordSequence(CharSequence text) { if (text == null) { words = new CharSequence[0]; length = 0; return; } length = text.length(); int spacesCount = 0; for (int i = 0; i < length; ++i) { if (text.charAt(i) == SPACE) { spacesCount++; } } int j = 0; words = new CharSequence[spacesCount + 1]; int start = 0; for (int i = 0; i <= length; ++i) { if (i == length || text.charAt(i) == SPACE) { words[j++] = text.subSequence(start, i + (i < length ? 1 : 0)); start = i + 1; } } } public WordSequence(CharSequence[] words) { if (words == null) { this.words = new CharSequence[0]; length = 0; return; } this.words = words; int length = 0; for (int i = 0; i < this.words.length; ++i) { if (this.words[i] != null) { length += this.words[i].length(); } } this.length = length; } public CharSequence wordAt(int i) { if (i < 0 || i >= words.length) { return null; } return words[i]; } @Override public int length() { return words.length; } @Override public char charAt(int i) { for (int j = 0; j < words.length; ++j) { if (i < words[j].length()) return words[j].charAt(i); i -= words[j].length(); } return 0; } @NonNull @Override public CharSequence subSequence(int from, int to) { return TextUtils.concat(Arrays.copyOfRange(words, from, to)); } @Override @NonNull public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < words.length; ++i) { sb.append(words[i]); } return sb.toString(); } public CharSequence toCharSequence() { return TextUtils.concat(words); } @Override public IntStream chars() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return toCharSequence().chars(); } return null; } @Override public IntStream codePoints() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return toCharSequence().codePoints(); } return null; } } public static boolean partEquals(CharSequence a, CharSequence b, int aIndex, int bIndex) { if (a instanceof WordSequence && b instanceof WordSequence) { CharSequence wordA = ((WordSequence) a).wordAt(aIndex); CharSequence wordB = ((WordSequence) b).wordAt(bIndex); return wordA == null && wordB == null || wordA != null && wordA.equals(wordB); } return (a == null && b == null || a != null && b != null && a.charAt(aIndex) == b.charAt(bIndex)); } private void betterDiff(final CharSequence oldText, final CharSequence newText, RegionCallback onEqualPart, RegionCallback onNewPart, RegionCallback onOldPart) { int m = oldText.length(); int n = newText.length(); int[][] dp = new int[m+1][n+1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) dp[i][j] = 0; else if (partEquals(oldText, newText, i - 1, j - 1)) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } List<Runnable> parts = new ArrayList<>(); int i = m, j = n; while (i > 0 && j > 0) { if (partEquals(oldText, newText, i - 1, j - 1)) { int start = i-1; while (i > 1 && j > 1 && partEquals(oldText, newText, i - 2, j - 2)) { i--; j--; } final int end = i - 1; parts.add(() -> onEqualPart.run(oldText.subSequence(end, start + 1), end, start + 1)); i--; j--; } else if (dp[i - 1][j] > dp[i][j - 1]) { int start = i-1; while (i > 1 && dp[i - 2][j] > dp[i - 1][j - 1]) { i--; } final int end = i - 1; parts.add(() -> onOldPart.run(oldText.subSequence(end, start + 1), end, start + 1)); i--; } else { int start = j - 1; while (j > 1 && dp[i][j - 2] > dp[i - 1][j - 1]) { j--; } final int end = j - 1; parts.add(() -> onNewPart.run(newText.subSequence(end, start + 1), end, start + 1)); j--; } } while (i > 0) { final int start = i - 1; while (i > 1 && dp[i - 2][j] >= dp[i - 1][j]) { i--; } final int end = i - 1; parts.add(() -> onOldPart.run(oldText.subSequence(end, start + 1), end, start + 1)); i--; } while (j > 0) { final int start = j - 1; while (j > 1 && dp[i][j - 2] >= dp[i][j - 1]) { j--; } final int end = j - 1; parts.add(() -> onNewPart.run(newText.subSequence(end, start + 1), end, start + 1)); j--; } Collections.reverse(parts); for (Runnable part : parts) { part.run(); } } private void diff(final CharSequence oldText, final CharSequence newText, RegionCallback onEqualPart, RegionCallback onNewPart, RegionCallback onOldPart) { if (updateAll) { onOldPart.run(oldText, 0, oldText.length()); onNewPart.run(newText, 0, newText.length()); return; } if (preserveIndex) { boolean equal = true; int start = 0; int minLength = Math.min(newText.length(), oldText.length()); if (startFromEnd) { ArrayList<Integer> indexes = new ArrayList<>(); boolean eq = true; for (int i = 0; i <= minLength; ++i) { int a = newText.length() - i - 1; int b = oldText.length() - i - 1; boolean thisEqual = a >= 0 && b >= 0 && partEquals(newText, oldText, a, b); if (equal != thisEqual || i == minLength) { if (i - start > 0) { if (indexes.size() == 0) { eq = equal; } indexes.add(i - start); } equal = thisEqual; start = i; } } int a = newText.length() - minLength; int b = oldText.length() - minLength; if (a > 0) { onNewPart.run(newText.subSequence(0, a), 0, a); } if (b > 0) { onOldPart.run(oldText.subSequence(0, b), 0, b); } for (int i = indexes.size() - 1; i >= 0; --i) { int count = indexes.get(i); if ((i % 2 == 0) == eq) { if (newText.length() > oldText.length()) { onEqualPart.run(newText.subSequence(a, a + count), a, a + count); } else { onEqualPart.run(oldText.subSequence(b, b + count), b, b + count); } } else { onNewPart.run(newText.subSequence(a, a + count), a, a + count); onOldPart.run(oldText.subSequence(b, b + count), b, b + count); } a += count; b += count; } } else { for (int i = 0; i <= minLength; ++i) { boolean thisEqual = i < minLength && partEquals(newText, oldText, i, i); if (equal != thisEqual || i == minLength) { if (i - start > 0) { if (equal) { onEqualPart.run(newText.subSequence(start, i), start, i); } else { onNewPart.run(newText.subSequence(start, i), start, i); onOldPart.run(oldText.subSequence(start, i), start, i); } } equal = thisEqual; start = i; } } if (newText.length() - minLength > 0) { onNewPart.run(newText.subSequence(minLength, newText.length()), minLength, newText.length()); } if (oldText.length() - minLength > 0) { onOldPart.run(oldText.subSequence(minLength, oldText.length()), minLength, oldText.length()); } } } else { int astart = 0, bstart = 0; boolean equal = true; int a = 0, b = 0; int minLength = Math.min(newText.length(), oldText.length()); for (; a <= minLength; ++a) { boolean thisEqual = a < minLength && partEquals(newText, oldText, a, b); if (equal != thisEqual || a == minLength) { if (a == minLength) { a = newText.length(); b = oldText.length(); } int alen = a - astart, blen = b - bstart; if (alen > 0 || blen > 0) { if (alen == blen && equal) { // equal part on [astart, a) onEqualPart.run(newText.subSequence(astart, a), astart, a); } else { if (alen > 0) { // new part on [astart, a) onNewPart.run(newText.subSequence(astart, a), astart, a); } if (blen > 0) { // old part on [bstart, b) onOldPart.run(oldText.subSequence(bstart, b), bstart, b); } } } equal = thisEqual; astart = a; bstart = b; } if (thisEqual) { b++; } } } } public void setTextSize(float textSizePx) { final float lastTextPaint = textPaint.getTextSize(); textPaint.setTextSize(textSizePx); if (Math.abs(lastTextPaint - textSizePx) > 0.5f) { final int width = overrideFullWidth > 0 ? overrideFullWidth : bounds.width(); if (currentParts != null) { // relayout parts: currentWidth = 0; currentHeight = 0; for (int i = 0; i < currentParts.length; ++i) { StaticLayout layout = makeLayout(currentParts[i].layout.getText(), width - (int) Math.ceil(Math.min(currentWidth, oldWidth))); currentParts[i] = new Part(layout, currentParts[i].offset, currentParts[i].toOppositeIndex); currentWidth += currentParts[i].width; currentHeight = Math.max(currentHeight, currentParts[i].layout.getHeight()); } } if (oldParts != null) { oldWidth = 0; oldHeight = 0; for (int i = 0; i < oldParts.length; ++i) { StaticLayout layout = makeLayout(oldParts[i].layout.getText(), width - (int) Math.ceil(Math.min(currentWidth, oldWidth))); oldParts[i] = new Part(layout, oldParts[i].offset, oldParts[i].toOppositeIndex); oldWidth += oldParts[i].width; oldHeight = Math.max(oldHeight, oldParts[i].layout.getHeight()); } } invalidateSelf(); } } public float getTextSize() { return textPaint.getTextSize(); } public void setTextColor(int color) { textPaint.setColor(color); alpha = Color.alpha(color); } private boolean shadowed = false; private float shadowRadius, shadowDx, shadowDy; private int shadowColor; public void setShadowLayer(float radius, float dx, float dy, int shadowColor) { shadowed = true; textPaint.setShadowLayer(shadowRadius = radius, shadowDx = dx, shadowDy = dy, this.shadowColor = shadowColor); } public int getTextColor() { return textPaint.getColor(); } private ValueAnimator colorAnimator; public void setTextColor(int color, boolean animated) { if (colorAnimator != null) { colorAnimator.cancel(); colorAnimator = null; } if (!animated) { setTextColor(color); } else { final int from = getTextColor(); final int to = color; colorAnimator = ValueAnimator.ofFloat(0, 1); colorAnimator.addUpdateListener(anm -> { setTextColor(ColorUtils.blendARGB(from, to, (float) anm.getAnimatedValue())); invalidateSelf(); }); colorAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { setTextColor(to); } }); colorAnimator.setDuration(240); colorAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); colorAnimator.start(); } } private int emojiColor; private ColorFilter emojiColorFilter; public void setEmojiColorFilter(ColorFilter colorFilter) { emojiColorFilter = colorFilter; } public void setEmojiColor(int emojiColor) { if (this.emojiColor != emojiColor) { emojiColorFilter = new PorterDuffColorFilter(this.emojiColor = emojiColor, PorterDuff.Mode.MULTIPLY); } } private ValueAnimator emojiColorAnimator; public void setEmojiColor(int color, boolean animated) { if (emojiColorAnimator != null) { emojiColorAnimator.cancel(); emojiColorAnimator = null; } if (!animated) { setEmojiColor(color); } else if (emojiColor != color) { final int from = getTextColor(); final int to = color; emojiColorAnimator = ValueAnimator.ofFloat(0, 1); emojiColorAnimator.addUpdateListener(anm -> { setEmojiColor(ColorUtils.blendARGB(from, to, (float) anm.getAnimatedValue())); invalidateSelf(); }); emojiColorAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { setTextColor(to); } }); emojiColorAnimator.setDuration(240); emojiColorAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); emojiColorAnimator.start(); } } public void setTypeface(Typeface typeface) { textPaint.setTypeface(typeface); } public void setGravity(int gravity) { this.gravity = gravity; } public int getGravity() { return this.gravity; } public void setAnimationProperties(float moveAmplitude, long startDelay, long duration, TimeInterpolator interpolator) { this.moveAmplitude = moveAmplitude; animateDelay = startDelay; animateDuration = duration; animateInterpolator = interpolator; } public void setScaleProperty(float scale) { this.scaleAmplitude = scale; } public void copyStylesFrom(TextPaint paint) { setTextColor(paint.getColor()); setTextSize(paint.getTextSize()); setTypeface(paint.getTypeface()); } public TextPaint getPaint() { return textPaint; } private interface RegionCallback { void run(CharSequence part, int start, int end); } @Override public void setAlpha(int alpha) { this.alpha = alpha; } @Override public void setColorFilter(@Nullable ColorFilter colorFilter) { textPaint.setColorFilter(colorFilter); } @Deprecated @Override public int getOpacity() { return PixelFormat.TRANSPARENT; } @Override public void setBounds(@NonNull Rect bounds) { super.setBounds(bounds); this.bounds.set(bounds); } @Override public void setBounds(int left, int top, int right, int bottom) { super.setBounds(left, top, right, bottom); this.bounds.set(left, top, right, bottom); } @NonNull @Override public Rect getDirtyBounds() { return this.bounds; } public float isNotEmpty() { return lerp( oldText == null || oldText.length() <= 0 ? 0f : 1f, currentText == null || currentText.length() <= 0 ? 0f : 1f, oldText == null ? 1f : t ); } private Runnable widthUpdatedListener; public void setOnWidthUpdatedListener(Runnable listener) { widthUpdatedListener = listener; } public void setIncludeFontPadding(boolean includeFontPadding) { this.includeFontPadding = includeFontPadding; } } private final AnimatedTextDrawable drawable; private int lastMaxWidth, maxWidth; private CharSequence toSetText; private boolean toSetMoveDown; public boolean adaptWidth = true; public AnimatedTextView(Context context) { this(context, false, false, false); } public AnimatedTextView(Context context, boolean splitByWords, boolean preserveIndex, boolean startFromEnd) { super(context); drawable = new AnimatedTextDrawable(splitByWords, preserveIndex, startFromEnd); drawable.setCallback(this); drawable.setOnAnimationFinishListener(() -> { if (toSetText != null) { // wrapped toSetText here to do requestLayout() AnimatedTextView.this.setText(toSetText, toSetMoveDown, true); toSetText = null; toSetMoveDown = false; } }); } public void setMaxWidth(int width) { maxWidth = width; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); if (maxWidth > 0) { width = Math.min(width, maxWidth); } if (lastMaxWidth != width && getLayoutParams().width != 0) { drawable.setBounds(getPaddingLeft(), getPaddingTop(), width - getPaddingRight(), height - getPaddingBottom()); drawable.setText(drawable.getText(), false, true); } lastMaxWidth = width; if (adaptWidth && MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST) { width = getPaddingLeft() + (int) Math.ceil(drawable.getWidth()) + getPaddingRight(); } setMeasuredDimension(width, height); } @Override protected void onDraw(Canvas canvas) { drawable.setBounds(getPaddingLeft(), getPaddingTop(), getMeasuredWidth() - getPaddingRight(), getMeasuredHeight() - getPaddingBottom()); drawable.draw(canvas); } public void setText(CharSequence text) { setText(text, true, true); } public void setText(CharSequence text, boolean animated) { setText(text, animated, true); } public void cancelAnimation() { drawable.cancelAnimation(); } public boolean isAnimating() { return drawable.isAnimating(); } public void setIgnoreRTL(boolean value) { drawable.ignoreRTL = value; } private boolean first = true; public void setText(CharSequence text, boolean animated, boolean moveDown) { animated = !first && animated; first = false; if (animated) { if (drawable.allowCancel) { if (drawable.animator != null) { drawable.animator.cancel(); drawable.animator = null; } } else if (drawable.isAnimating()) { toSetText = text; toSetMoveDown = moveDown; return; } } int wasWidth = (int) drawable.getWidth(); drawable.setBounds(getPaddingLeft(), getPaddingTop(), lastMaxWidth - getPaddingRight(), getMeasuredHeight() - getPaddingBottom()); drawable.setText(text, animated, moveDown); if (wasWidth < drawable.getWidth() || !animated && wasWidth != drawable.getWidth()) { requestLayout(); } } public int width() { return getPaddingLeft() + (int) Math.ceil(drawable.getCurrentWidth()) + getPaddingRight(); } public CharSequence getText() { return drawable.getText(); } public int getTextHeight() { return getPaint().getFontMetricsInt().descent - getPaint().getFontMetricsInt().ascent; } public void setTextSize(float textSizePx) { drawable.setTextSize(textSizePx); } public void setTextColor(int color) { drawable.setTextColor(color); invalidate(); } public void setTextColor(int color, boolean animated) { drawable.setTextColor(color, animated); invalidate(); } public void setEmojiCacheType(int cacheType) { drawable.setEmojiCacheType(cacheType); } public void setEmojiColor(int color) { drawable.setEmojiColor(color); invalidate(); } public void setEmojiColor(int color, boolean animated) { drawable.setEmojiColor(color, animated); invalidate(); } public void setEmojiColorFilter(ColorFilter emojiColorFilter) { drawable.setEmojiColorFilter(emojiColorFilter); invalidate(); } public int getTextColor() { return drawable.getTextColor(); } public void setTypeface(Typeface typeface) { drawable.setTypeface(typeface); } public void setGravity(int gravity) { drawable.setGravity(gravity); } public void setAnimationProperties(float moveAmplitude, long startDelay, long duration, TimeInterpolator interpolator) { drawable.setAnimationProperties(moveAmplitude, startDelay, duration, interpolator); } public void setScaleProperty(float scale) { drawable.setScaleProperty(scale); } public AnimatedTextDrawable getDrawable() { return drawable; } public TextPaint getPaint() { return drawable.getPaint(); } @Override public void invalidateDrawable(@NonNull Drawable drawable) { super.invalidateDrawable(drawable); invalidate(); } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName("android.widget.TextView"); info.setText(getText()); } public void setEllipsizeByGradient(boolean enabled) { drawable.setEllipsizeByGradient(enabled); } public void setRightPadding(float rightPadding) { drawable.setRightPadding(rightPadding); } public float getRightPadding() { return drawable.getRightPadding(); } private Runnable widthUpdatedListener; public void setOnWidthUpdatedListener(Runnable listener) { drawable.setOnWidthUpdatedListener(listener); } public void setIncludeFontPadding(boolean includeFontPadding) { this.drawable.setIncludeFontPadding(includeFontPadding); } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Components/AnimatedTextView.java
2,165
package org.telegram.ui.Components; import static java.lang.annotation.RetentionPolicy.SOURCE; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; 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.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.util.Property; import android.util.TypedValue; import android.view.GestureDetector; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowInsets; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.CallSuper; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.util.Consumer; import androidx.core.view.ViewCompat; import androidx.dynamicanimation.animation.DynamicAnimation; import androidx.dynamicanimation.animation.FloatPropertyCompat; import androidx.dynamicanimation.animation.FloatValueHolder; import androidx.dynamicanimation.animation.SpringAnimation; import androidx.dynamicanimation.animation.SpringForce; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.Emoji; import org.telegram.messenger.LocaleController; 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.support.SparseLongArray; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ChatActivity; import org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble; import org.telegram.ui.DialogsActivity; import org.telegram.ui.LaunchActivity; import java.lang.annotation.Retention; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class Bulletin { public static final int DURATION_SHORT = 1500; public static final int DURATION_LONG = 2750; public static final int DURATION_PROLONG = 5000; public static final int TYPE_STICKER = 0; public static final int TYPE_ERROR = 1; public static final int TYPE_BIO_CHANGED = 2; public static final int TYPE_NAME_CHANGED = 3; public static final int TYPE_ERROR_SUBTITLE = 4; public static final int TYPE_APP_ICON = 5; public static final int TYPE_SUCCESS = 6; public int tag; public int hash; private View.OnLayoutChangeListener containerLayoutListener; private SpringAnimation bottomOffsetSpring; public static Bulletin make(@NonNull FrameLayout containerLayout, @NonNull Layout contentLayout, int duration) { return new Bulletin(null, containerLayout, contentLayout, duration); } public Bulletin setOnClickListener(View.OnClickListener onClickListener) { if (layout != null) { layout.setOnClickListener(onClickListener); } return this; } @SuppressLint("RtlHardcoded") public static Bulletin make(@NonNull BaseFragment fragment, @NonNull Layout contentLayout, int duration) { if (fragment instanceof ChatActivity) { contentLayout.setWideScreenParams(ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL); } else if (fragment instanceof DialogsActivity) { contentLayout.setWideScreenParams(ViewGroup.LayoutParams.MATCH_PARENT, Gravity.NO_GRAVITY); } return new Bulletin(fragment, fragment.getLayoutContainer(), contentLayout, duration); } public static Bulletin find(@NonNull FrameLayout containerLayout) { for (int i = 0, size = containerLayout.getChildCount(); i < size; i++) { final View view = containerLayout.getChildAt(i); if (view instanceof Layout) { return ((Layout) view).bulletin; } } return null; } public static void hide(@NonNull FrameLayout containerLayout) { hide(containerLayout, true); } public static void hide(@NonNull FrameLayout containerLayout, boolean animated) { final Bulletin bulletin = find(containerLayout); if (bulletin != null) { bulletin.hide(animated && isTransitionsEnabled(), 0); } } private static final HashMap<FrameLayout, Delegate> delegates = new HashMap<>(); private static final HashMap<BaseFragment, Delegate> fragmentDelegates = new HashMap<>(); @SuppressLint("StaticFieldLeak") private static Bulletin visibleBulletin; private final Layout layout; private final ParentLayout parentLayout; private final BaseFragment containerFragment; private final FrameLayout containerLayout; private final Runnable hideRunnable = this::hide; private int duration; private boolean showing; private boolean canHide; private boolean loaded = true; public int currentBottomOffset; public int lastBottomOffset; private Delegate currentDelegate; private Layout.Transition layoutTransition; public boolean hideAfterBottomSheet = true; private Bulletin() { layout = null; parentLayout = null; containerFragment = null; containerLayout = null; } private Bulletin(BaseFragment fragment, @NonNull FrameLayout containerLayout, @NonNull Layout layout, int duration) { this.layout = layout; this.loaded = !(this.layout instanceof LoadingLayout); this.parentLayout = new ParentLayout(layout) { @Override protected void onPressedStateChanged(boolean pressed) { setCanHide(!pressed); if (containerLayout.getParent() != null) { containerLayout.getParent().requestDisallowInterceptTouchEvent(pressed); } } @Override protected void onHide() { hide(); } }; this.containerFragment = fragment; this.containerLayout = containerLayout; this.duration = duration; } public static Bulletin getVisibleBulletin() { return visibleBulletin; } public static void hideVisible() { if (visibleBulletin != null) { visibleBulletin.hide(); } } public static void hideVisible(ViewGroup container) { if (visibleBulletin != null && visibleBulletin.containerLayout == container) { visibleBulletin.hide(); } } public Bulletin setDuration(int duration) { this.duration = duration; return this; } public Bulletin hideAfterBottomSheet(boolean hide) { this.hideAfterBottomSheet = hide; return this; } public Bulletin setTag(int tag) { this.tag = tag; return this; } public Bulletin show() { return show(false); } public Bulletin show(boolean top) { if (!showing && containerLayout != null) { showing = true; layout.setTop(top); CharSequence text = layout.getAccessibilityText(); if (text != null) { AndroidUtilities.makeAccessibilityAnnouncement(text); } if (layout.getParent() != parentLayout) { throw new IllegalStateException("Layout has incorrect parent"); } if (visibleBulletin != null) { visibleBulletin.hide(); } visibleBulletin = this; layout.onAttach(this); containerLayout.addOnLayoutChangeListener(containerLayoutListener = (v, left, top1, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> { if (currentDelegate != null && !currentDelegate.allowLayoutChanges()) { return; } if (!top) { int newOffset = currentDelegate != null ? currentDelegate.getBottomOffset(tag) : 0; if (lastBottomOffset != newOffset) { if (bottomOffsetSpring == null || !bottomOffsetSpring.isRunning()) { bottomOffsetSpring = new SpringAnimation(new FloatValueHolder(lastBottomOffset)) .setSpring(new SpringForce() .setFinalPosition(newOffset) .setStiffness(900f) .setDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY)); bottomOffsetSpring.addUpdateListener((animation, value, velocity) -> { lastBottomOffset = (int) value; updatePosition(); }); bottomOffsetSpring.addEndListener((animation, canceled, value, velocity) -> { if (bottomOffsetSpring == animation) { bottomOffsetSpring = null; } }); } else { bottomOffsetSpring.getSpring().setFinalPosition(newOffset); } bottomOffsetSpring.start(); } } }); layout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int t, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { layout.removeOnLayoutChangeListener(this); if (showing) { layout.onShow(); currentDelegate = findDelegate(containerFragment, containerLayout); if (bottomOffsetSpring == null || !bottomOffsetSpring.isRunning()) { lastBottomOffset = currentDelegate != null ? currentDelegate.getBottomOffset(tag) : 0; } if (currentDelegate != null) { currentDelegate.onShow(Bulletin.this); } if (isTransitionsEnabled()) { ensureLayoutTransitionCreated(); layout.transitionRunningEnter = true; layout.delegate = currentDelegate; layout.invalidate(); layoutTransition.animateEnter(layout, layout::onEnterTransitionStart, () -> { layout.transitionRunningEnter = false; layout.onEnterTransitionEnd(); setCanHide(true); }, offset -> { if (currentDelegate != null && !top) { currentDelegate.onBottomOffsetChange(layout.getHeight() - offset); } }, currentBottomOffset); } else { if (currentDelegate != null && !top) { currentDelegate.onBottomOffsetChange(layout.getHeight() - currentBottomOffset); } updatePosition(); layout.onEnterTransitionStart(); layout.onEnterTransitionEnd(); setCanHide(true); } } } }); layout.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() { @Override public void onViewAttachedToWindow(View v) { } @Override public void onViewDetachedFromWindow(View v) { layout.removeOnAttachStateChangeListener(this); hide(false, 0); } }); containerLayout.addView(parentLayout); } return this; } public void setCanHide(boolean canHide) { canHide = canHide && loaded; if (this.canHide != canHide && layout != null) { this.canHide = canHide; if (canHide) { layout.postDelayed(hideRunnable, duration); } else { layout.removeCallbacks(hideRunnable); } } } private Runnable onHideListener; public Bulletin setOnHideListener(Runnable listener) { this.onHideListener = listener; return this; } private void ensureLayoutTransitionCreated() { if (layout != null && layoutTransition == null) { layoutTransition = layout.createTransition(); } } public void hide() { hide(isTransitionsEnabled(), 0); } public void hide(long duration) { hide(isTransitionsEnabled(), duration); } public void hide(boolean animated, long duration) { if (layout == null) { return; } if (showing) { showing = false; if (visibleBulletin == this) { visibleBulletin = null; } int bottomOffset = currentBottomOffset; currentBottomOffset = 0; if (ViewCompat.isLaidOut(layout)) { layout.removeCallbacks(hideRunnable); if (animated) { layout.transitionRunningExit = true; layout.delegate = currentDelegate; layout.invalidate(); if (duration >= 0) { Layout.DefaultTransition transition = new Layout.DefaultTransition(); transition.duration = duration; layoutTransition = transition; } else { ensureLayoutTransitionCreated(); } layoutTransition.animateExit(layout, layout::onExitTransitionStart, () -> { if (currentDelegate != null && !layout.top) { currentDelegate.onBottomOffsetChange(0); currentDelegate.onHide(this); } layout.transitionRunningExit = false; layout.onExitTransitionEnd(); layout.onHide(); containerLayout.removeView(parentLayout); containerLayout.removeOnLayoutChangeListener(containerLayoutListener); layout.onDetach(); if (onHideListener != null) { onHideListener.run(); } }, offset -> { if (currentDelegate != null && !layout.top) { currentDelegate.onBottomOffsetChange(layout.getHeight() - offset); } }, bottomOffset); return; } } if (currentDelegate != null && !layout.top) { currentDelegate.onBottomOffsetChange(0); currentDelegate.onHide(this); } layout.onExitTransitionStart(); layout.onExitTransitionEnd(); layout.onHide(); if (containerLayout != null) { AndroidUtilities.runOnUIThread(() -> { containerLayout.removeView(parentLayout); containerLayout.removeOnLayoutChangeListener(containerLayoutListener); }); } layout.onDetach(); if (onHideListener != null) { onHideListener.run(); } } } public boolean isShowing() { return showing; } public Layout getLayout() { return layout; } private static boolean isTransitionsEnabled() { return MessagesController.getGlobalMainSettings().getBoolean("view_animations", true) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2; } public void updatePosition() { if (layout != null) { layout.updatePosition(); } } @Retention(SOURCE) @IntDef(value = {ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT}) private @interface WidthDef { } @Retention(SOURCE) @SuppressLint("RtlHardcoded") @IntDef(value = {Gravity.LEFT, Gravity.RIGHT, Gravity.CENTER_HORIZONTAL, Gravity.NO_GRAVITY}) private @interface GravityDef { } public static abstract class ParentLayout extends FrameLayout { private final Layout layout; private final Rect rect = new Rect(); private final GestureDetector gestureDetector; private boolean pressed; private float translationX; private boolean hideAnimationRunning; private boolean needLeftAlphaAnimation; private boolean needRightAlphaAnimation; public ParentLayout(Layout layout) { super(layout.getContext()); this.layout = layout; gestureDetector = new GestureDetector(layout.getContext(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { if (!hideAnimationRunning) { needLeftAlphaAnimation = layout.isNeedSwipeAlphaAnimation(true); needRightAlphaAnimation = layout.isNeedSwipeAlphaAnimation(false); return true; } return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { layout.setTranslationX(translationX -= distanceX); if (translationX == 0 || (translationX < 0f && needLeftAlphaAnimation) || (translationX > 0f && needRightAlphaAnimation)) { layout.setAlpha(1f - Math.abs(translationX) / layout.getWidth()); } return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (Math.abs(velocityX) > 2000f) { final boolean needAlphaAnimation = (velocityX < 0f && needLeftAlphaAnimation) || (velocityX > 0f && needRightAlphaAnimation); final SpringAnimation springAnimation = new SpringAnimation(layout, DynamicAnimation.TRANSLATION_X, Math.signum(velocityX) * layout.getWidth() * 2f); if (!needAlphaAnimation) { springAnimation.addEndListener((animation, canceled, value, velocity) -> onHide()); springAnimation.addUpdateListener(((animation, value, velocity) -> { if (Math.abs(value) > layout.getWidth()) { animation.cancel(); } })); } springAnimation.getSpring().setDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY); springAnimation.getSpring().setStiffness(100f); springAnimation.setStartVelocity(velocityX); springAnimation.start(); if (needAlphaAnimation) { final SpringAnimation springAnimation2 = new SpringAnimation(layout, DynamicAnimation.ALPHA, 0f); springAnimation2.addEndListener((animation, canceled, value, velocity) -> onHide()); springAnimation2.addUpdateListener(((animation, value, velocity) -> { if (value <= 0f) { animation.cancel(); } })); springAnimation.getSpring().setDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY); springAnimation.getSpring().setStiffness(10f); springAnimation.setStartVelocity(velocityX); springAnimation2.start(); } hideAnimationRunning = true; return true; } return false; } }); gestureDetector.setIsLongpressEnabled(false); addView(layout); } @Override public boolean onTouchEvent(MotionEvent event) { if (pressed || inLayoutHitRect(event.getX(), event.getY())) { gestureDetector.onTouchEvent(event); final int actionMasked = event.getActionMasked(); if (actionMasked == MotionEvent.ACTION_DOWN) { if (!pressed && !hideAnimationRunning) { layout.animate().cancel(); translationX = layout.getTranslationX(); onPressedStateChanged(pressed = true); } } else if (actionMasked == MotionEvent.ACTION_UP || actionMasked == MotionEvent.ACTION_CANCEL) { if (pressed) { if (!hideAnimationRunning) { if (Math.abs(translationX) > layout.getWidth() / 3f) { final float tx = Math.signum(translationX) * layout.getWidth(); final boolean needAlphaAnimation = (translationX < 0f && needLeftAlphaAnimation) || (translationX > 0f && needRightAlphaAnimation); layout.animate().translationX(tx).alpha(needAlphaAnimation ? 0f : 1f).setDuration(200).setInterpolator(AndroidUtilities.accelerateInterpolator).withEndAction(() -> { if (layout.getTranslationX() == tx) { onHide(); } }).start(); } else { layout.animate().translationX(0).alpha(1f).setDuration(200).start(); } } onPressedStateChanged(pressed = false); } } return true; } return false; } private boolean inLayoutHitRect(float x, float y) { layout.getHitRect(rect); return rect.contains((int) x, (int) y); } protected abstract void onPressedStateChanged(boolean pressed); protected abstract void onHide(); } //region Offset Providers public static void addDelegate(@NonNull BaseFragment fragment, @NonNull Delegate delegate) { fragmentDelegates.put(fragment, delegate); } public static void addDelegate(@NonNull FrameLayout containerLayout, @NonNull Delegate delegate) { delegates.put(containerLayout, delegate); } private static Delegate findDelegate(BaseFragment probableFragment, FrameLayout probableContainer) { Delegate delegate; if ((delegate = fragmentDelegates.get(probableFragment)) != null) { return delegate; } if ((delegate = delegates.get(probableContainer)) != null) { return delegate; } return null; } public static void removeDelegate(@NonNull BaseFragment fragment) { fragmentDelegates.remove(fragment); } public static void removeDelegate(@NonNull FrameLayout containerLayout) { delegates.remove(containerLayout); } public interface Delegate { default int getBottomOffset(int tag) { return 0; } default boolean bottomOffsetAnimated() { return true; } default int getLeftPadding() { return 0; } default int getRightPadding() { return 0; } default int getTopOffset(int tag) { return 0; } default boolean clipWithGradient(int tag) { return false; } default void onBottomOffsetChange(float offset) { } default void onShow(Bulletin bulletin) { } default void onHide(Bulletin bulletin) { } default boolean allowLayoutChanges() { return true; } } //endregion //region Layouts public abstract static class Layout extends FrameLayout { private final List<Callback> callbacks = new ArrayList<>(); public boolean transitionRunningEnter; public boolean transitionRunningExit; Delegate delegate; public float inOutOffset; protected Bulletin bulletin; Drawable background; public boolean top; public boolean isTransitionRunning() { return transitionRunningEnter || transitionRunningExit; } @WidthDef private int wideScreenWidth = ViewGroup.LayoutParams.WRAP_CONTENT; @GravityDef private int wideScreenGravity = Gravity.CENTER_HORIZONTAL; private final Theme.ResourcesProvider resourcesProvider; public Layout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { super(context); this.resourcesProvider = resourcesProvider; setMinimumHeight(AndroidUtilities.dp(48)); setBackground(getThemedColor(Theme.key_undo_background)); updateSize(); setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8)); setWillNotDraw(false); ScaleStateListAnimator.apply(this, .02f, 1.5f); } @Override protected boolean verifyDrawable(@NonNull Drawable who) { return background == who || super.verifyDrawable(who); } protected void setBackground(int color) { setBackground(color, 10); } public void setBackground(int color, int rounding) { background = Theme.createRoundRectDrawable(AndroidUtilities.dp(rounding), color); } public final static FloatPropertyCompat<Layout> IN_OUT_OFFSET_Y = new FloatPropertyCompat<Layout>("offsetY") { @Override public float getValue(Layout object) { return object.inOutOffset; } @Override public void setValue(Layout object, float value) { object.setInOutOffset(value); } }; public final static Property<Layout, Float> IN_OUT_OFFSET_Y2 = new AnimationProperties.FloatProperty<Layout>("offsetY") { @Override public Float get(Layout layout) { return layout.inOutOffset; } @Override public void setValue(Layout object, float value) { object.setInOutOffset(value); } }; @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); updateSize(); } public void setTop(boolean top) { this.top = top; updateSize(); } private void updateSize() { final boolean isWideScreen = isWideScreen(); setLayoutParams(LayoutHelper.createFrame(isWideScreen ? wideScreenWidth : LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, isWideScreen ? (top ? Gravity.TOP : Gravity.BOTTOM) | wideScreenGravity : (top ? Gravity.TOP : Gravity.BOTTOM))); } private boolean isWideScreen() { return AndroidUtilities.isTablet() || AndroidUtilities.displaySize.x >= AndroidUtilities.displaySize.y; } private void setWideScreenParams(@WidthDef int width, @GravityDef int gravity) { boolean changed = false; if (wideScreenWidth != width) { wideScreenWidth = width; changed = true; } if (wideScreenGravity != gravity) { wideScreenGravity = gravity; changed = true; } if (isWideScreen() && changed) { updateSize(); } } @SuppressLint("RtlHardcoded") private boolean isNeedSwipeAlphaAnimation(boolean swipeLeft) { if (!isWideScreen() || wideScreenWidth == ViewGroup.LayoutParams.MATCH_PARENT) { return false; } if (wideScreenGravity == Gravity.CENTER_HORIZONTAL) { return true; } if (swipeLeft) { return wideScreenGravity == Gravity.RIGHT; } else { return wideScreenGravity != Gravity.RIGHT; } } protected CharSequence getAccessibilityText() { return null; } public Bulletin getBulletin() { return bulletin; } public boolean isAttachedToBulletin() { return bulletin != null; } @CallSuper protected void onAttach(@NonNull Bulletin bulletin) { this.bulletin = bulletin; for (int i = 0, size = callbacks.size(); i < size; i++) { callbacks.get(i).onAttach(this, bulletin); } } @CallSuper protected void onDetach() { this.bulletin = null; for (int i = 0, size = callbacks.size(); i < size; i++) { callbacks.get(i).onDetach(this); } } @CallSuper protected void onShow() { for (int i = 0, size = callbacks.size(); i < size; i++) { callbacks.get(i).onShow(this); } } @CallSuper protected void onHide() { for (int i = 0, size = callbacks.size(); i < size; i++) { callbacks.get(i).onHide(this); } } @CallSuper protected void onEnterTransitionStart() { for (int i = 0, size = callbacks.size(); i < size; i++) { callbacks.get(i).onEnterTransitionStart(this); } } @CallSuper protected void onEnterTransitionEnd() { for (int i = 0, size = callbacks.size(); i < size; i++) { callbacks.get(i).onEnterTransitionEnd(this); } } @CallSuper protected void onExitTransitionStart() { for (int i = 0, size = callbacks.size(); i < size; i++) { callbacks.get(i).onExitTransitionStart(this); } } @CallSuper protected void onExitTransitionEnd() { for (int i = 0, size = callbacks.size(); i < size; i++) { callbacks.get(i).onExitTransitionEnd(this); } } //region Callbacks public void addCallback(@NonNull Callback callback) { callbacks.add(callback); } public void removeCallback(@NonNull Callback callback) { callbacks.remove(callback); } public void updatePosition() { float translation = 0; if (delegate != null) { if (top) { translation -= delegate.getTopOffset(bulletin != null ? bulletin.tag : 0); } else { translation += getBottomOffset(); } } setTranslationY(-translation + inOutOffset * (top ? -1 : 1)); } public float getBottomOffset() { if (bulletin != null && (delegate == null || delegate.bottomOffsetAnimated()) && bulletin.bottomOffsetSpring != null && bulletin.bottomOffsetSpring.isRunning()) { return bulletin.lastBottomOffset; } return delegate.getBottomOffset(bulletin != null ? bulletin.tag : 0); } public interface Callback { default void onAttach(@NonNull Layout layout, @NonNull Bulletin bulletin) { } default void onDetach(@NonNull Layout layout) { } default void onShow(@NonNull Layout layout) { } default void onHide(@NonNull Layout layout) { } default void onEnterTransitionStart(@NonNull Layout layout) { } default void onEnterTransitionEnd(@NonNull Layout layout) { } default void onExitTransitionStart(@NonNull Layout layout) { } default void onExitTransitionEnd(@NonNull Layout layout) { } } //endregion //region Transitions @NonNull public Transition createTransition() { return new SpringTransition(); } public interface Transition { void animateEnter(@NonNull Layout layout, @Nullable Runnable startAction, @Nullable Runnable endAction, @Nullable Consumer<Float> onUpdate, int bottomOffset); void animateExit(@NonNull Layout layout, @Nullable Runnable startAction, @Nullable Runnable endAction, @Nullable Consumer<Float> onUpdate, int bottomOffset); } public static class DefaultTransition implements Transition { long duration = 255; @Override public void animateEnter(@NonNull Layout layout, @Nullable Runnable startAction, @Nullable Runnable endAction, @Nullable Consumer<Float> onUpdate, int bottomOffset) { layout.setInOutOffset(layout.getMeasuredHeight()); if (onUpdate != null) { onUpdate.accept(layout.getTranslationY()); } final ObjectAnimator animator = ObjectAnimator.ofFloat(layout, IN_OUT_OFFSET_Y2, 0); animator.setDuration(duration); animator.setInterpolator(Easings.easeOutQuad); if (startAction != null || endAction != null) { animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { if (startAction != null) { startAction.run(); } } @Override public void onAnimationEnd(Animator animation) { if (endAction != null) { endAction.run(); } } }); } if (onUpdate != null) { animator.addUpdateListener(a -> onUpdate.accept(layout.getTranslationY())); } animator.start(); } @Override public void animateExit(@NonNull Layout layout, @Nullable Runnable startAction, @Nullable Runnable endAction, @Nullable Consumer<Float> onUpdate, int bottomOffset) { final ObjectAnimator animator = ObjectAnimator.ofFloat(layout, IN_OUT_OFFSET_Y2, layout.getHeight()); animator.setDuration(175); animator.setInterpolator(Easings.easeInQuad); if (startAction != null || endAction != null) { animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { if (startAction != null) { startAction.run(); } } @Override public void onAnimationEnd(Animator animation) { if (endAction != null) { endAction.run(); } } }); } if (onUpdate != null) { animator.addUpdateListener(a -> onUpdate.accept(layout.getTranslationY())); } animator.start(); } } public static class SpringTransition implements Transition { private static final float DAMPING_RATIO = 0.8f; private static final float STIFFNESS = 400f; @Override public void animateEnter(@NonNull Layout layout, @Nullable Runnable startAction, @Nullable Runnable endAction, @Nullable Consumer<Float> onUpdate, int bottomOffset) { layout.setInOutOffset(layout.getMeasuredHeight()); if (onUpdate != null) { onUpdate.accept(layout.getTranslationY()); } final SpringAnimation springAnimation = new SpringAnimation(layout, IN_OUT_OFFSET_Y, 0); springAnimation.getSpring().setDampingRatio(DAMPING_RATIO); springAnimation.getSpring().setStiffness(STIFFNESS); if (endAction != null) { springAnimation.addEndListener((animation, canceled, value, velocity) -> { layout.setInOutOffset(0); if (!canceled) { endAction.run(); } }); } if (onUpdate != null) { springAnimation.addUpdateListener((animation, value, velocity) -> onUpdate.accept(layout.getTranslationY())); } springAnimation.start(); if (startAction != null) { startAction.run(); } } @Override public void animateExit(@NonNull Layout layout, @Nullable Runnable startAction, @Nullable Runnable endAction, @Nullable Consumer<Float> onUpdate, int bottomOffset) { final SpringAnimation springAnimation = new SpringAnimation(layout, IN_OUT_OFFSET_Y, layout.getHeight()); springAnimation.getSpring().setDampingRatio(DAMPING_RATIO); springAnimation.getSpring().setStiffness(STIFFNESS); if (endAction != null) { springAnimation.addEndListener((animation, canceled, value, velocity) -> { if (!canceled) { endAction.run(); } }); } if (onUpdate != null) { springAnimation.addUpdateListener((animation, value, velocity) -> onUpdate.accept(layout.getTranslationY())); } springAnimation.start(); if (startAction != null) { startAction.run(); } } } private void setInOutOffset(float offset) { inOutOffset = offset; updatePosition(); } private LinearGradient clipGradient; private Matrix clipMatrix; private Paint clipPaint; protected int getMeasuredBackgroundHeight() { return getMeasuredHeight(); } @Override protected void dispatchDraw(Canvas canvas) { if (bulletin == null) { return; } background.setBounds(getPaddingLeft(), getPaddingTop(), getMeasuredWidth() - getPaddingRight(), getMeasuredBackgroundHeight() - getPaddingBottom()); if (isTransitionRunning() && delegate != null) { final float top = delegate.getTopOffset(bulletin.tag) - getY(); final float bottom = ((View) getParent()).getMeasuredHeight() - getBottomOffset() - getY(); final boolean clip = delegate.clipWithGradient(bulletin.tag); canvas.save(); canvas.clipRect(0, top, getMeasuredWidth(), bottom); if (clip) { canvas.saveLayerAlpha(0, 0, getWidth(), getHeight(), 0xFF, Canvas.ALL_SAVE_FLAG); } background.draw(canvas); super.dispatchDraw(canvas); if (clip) { if (clipPaint == null) { clipPaint = new Paint(Paint.ANTI_ALIAS_FLAG); clipPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); clipGradient = new LinearGradient(0, 0, 0, AndroidUtilities.dp(8), this.top ? new int[]{0xff000000, 0} : new int[]{0, 0xff000000}, new float[]{0, 1}, Shader.TileMode.CLAMP); clipMatrix = new Matrix(); clipGradient.setLocalMatrix(clipMatrix); clipPaint.setShader(clipGradient); } canvas.save(); clipMatrix.reset(); clipMatrix.postTranslate(0, this.top ? top : bottom - AndroidUtilities.dp(8)); clipGradient.setLocalMatrix(clipMatrix); if (this.top) { canvas.drawRect(0, top, getWidth(), top + AndroidUtilities.dp(8), clipPaint); } else { canvas.drawRect(0, bottom - AndroidUtilities.dp(8), getWidth(), bottom, clipPaint); } canvas.restore(); canvas.restore(); } canvas.restore(); invalidate(); } else { background.draw(canvas); super.dispatchDraw(canvas); } } protected int getThemedColor(int key) { return Theme.getColor(key, resourcesProvider); } //endregion } @SuppressLint("ViewConstructor") public static class ButtonLayout extends Layout { private Button button; public TimerView timerView; private int childrenMeasuredWidth; Theme.ResourcesProvider resourcesProvider; public ButtonLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { super(context, resourcesProvider); this.resourcesProvider = resourcesProvider; } private boolean wrapWidth; public void setWrapWidth() { wrapWidth = true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { childrenMeasuredWidth = 0; if (wrapWidth) { widthMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (button != null && MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST) { setMeasuredDimension(childrenMeasuredWidth + button.getMeasuredWidth(), getMeasuredHeight()); } } @Override protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) { if (button != null && child != button) { widthUsed += button.getMeasuredWidth() - AndroidUtilities.dp(12); } super.measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed); if (child != button) { final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); childrenMeasuredWidth = Math.max(childrenMeasuredWidth, lp.leftMargin + lp.rightMargin + child.getMeasuredWidth()); } } public Button getButton() { return button; } public void setButton(Button button) { if (this.button != null) { removeCallback(this.button); removeView(this.button); } this.button = button; if (button != null) { addCallback(button); addView(button, 0, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.END | Gravity.CENTER_VERTICAL)); } } public void setTimer() { timerView = new TimerView(getContext(), resourcesProvider); timerView.timeLeft = 5000; addView(timerView, LayoutHelper.createFrameRelatively(20, 20, Gravity.START | Gravity.CENTER_VERTICAL, 21, 0, 21, 0)); } } public static class SimpleLayout extends ButtonLayout { public final ImageView imageView; public final LinkSpanDrawable.LinksTextView textView; public SimpleLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { super(context, resourcesProvider); final int undoInfoColor = getThemedColor(Theme.key_undo_infoColor); imageView = new ImageView(context); imageView.setColorFilter(new PorterDuffColorFilter(undoInfoColor, PorterDuff.Mode.MULTIPLY)); addView(imageView, LayoutHelper.createFrameRelatively(24, 24, Gravity.START | Gravity.CENTER_VERTICAL, 16, 12, 16, 12)); textView = new LinkSpanDrawable.LinksTextView(context); textView.setDisablePaddingsOffsetY(true); textView.setSingleLine(); textView.setTextColor(undoInfoColor); textView.setTypeface(Typeface.SANS_SERIF); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); addView(textView, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 56, 0, 16, 0)); } public CharSequence getAccessibilityText() { return textView.getText(); } } @SuppressLint("ViewConstructor") public static class MultiLineLayout extends ButtonLayout { public final BackupImageView imageView = new BackupImageView(getContext()); public final TextView textView = new TextView(getContext()); public MultiLineLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { super(context, resourcesProvider); addView(imageView, LayoutHelper.createFrameRelatively(30, 30, Gravity.START | Gravity.CENTER_VERTICAL, 12, 8, 12, 8)); textView.setGravity(Gravity.START); textView.setPadding(0, AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8)); textView.setTextColor(getThemedColor(Theme.key_undo_infoColor)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); textView.setTypeface(Typeface.SANS_SERIF); addView(textView, LayoutHelper.createFrameRelatively(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 56, 0, 16, 0)); } public CharSequence getAccessibilityText() { return textView.getText(); } } @SuppressLint("ViewConstructor") public static class TwoLineLayout extends ButtonLayout { public final BackupImageView imageView; public final TextView titleTextView; public final TextView subtitleTextView; private final LinearLayout linearLayout; public TwoLineLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { super(context, resourcesProvider); final int undoInfoColor = getThemedColor(Theme.key_undo_infoColor); addView(imageView = new BackupImageView(context), LayoutHelper.createFrameRelatively(29, 29, Gravity.START | Gravity.CENTER_VERTICAL, 12, 12, 12, 12)); linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); addView(linearLayout, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 54, 8, 12, 8)); titleTextView = new TextView(context); titleTextView.setSingleLine(); titleTextView.setTextColor(undoInfoColor); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); linearLayout.addView(titleTextView); subtitleTextView = new TextView(context); subtitleTextView.setMaxLines(2); subtitleTextView.setTextColor(undoInfoColor); subtitleTextView.setLinkTextColor(getThemedColor(Theme.key_undo_cancelColor)); subtitleTextView.setMovementMethod(new LinkMovementMethod()); subtitleTextView.setTypeface(Typeface.SANS_SERIF); subtitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); linearLayout.addView(subtitleTextView); } public CharSequence getAccessibilityText() { return titleTextView.getText() + ".\n" + subtitleTextView.getText(); } public void hideImage() { imageView.setVisibility(GONE); ((MarginLayoutParams) linearLayout.getLayoutParams()).setMarginStart(AndroidUtilities.dp(12)); } } public static class TwoLineLottieLayout extends ButtonLayout { public final RLottieImageView imageView; public final LinkSpanDrawable.LinksTextView titleTextView; public final LinkSpanDrawable.LinksTextView subtitleTextView; private final LinearLayout linearLayout; private final int textColor; public TwoLineLottieLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { super(context, resourcesProvider); this.textColor = getThemedColor(Theme.key_undo_infoColor); setBackground(getThemedColor(Theme.key_undo_background)); imageView = new RLottieImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER); addView(imageView, LayoutHelper.createFrameRelatively(56, 48, Gravity.START | Gravity.CENTER_VERTICAL)); final int undoInfoColor = getThemedColor(Theme.key_undo_infoColor); final int undoLinkColor = getThemedColor(Theme.key_undo_cancelColor); linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); addView(linearLayout, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 52, 8, 8, 8)); titleTextView = new LinkSpanDrawable.LinksTextView(context); titleTextView.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0); titleTextView.setSingleLine(); titleTextView.setTextColor(undoInfoColor); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); linearLayout.addView(titleTextView); subtitleTextView = new LinkSpanDrawable.LinksTextView(context); subtitleTextView.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0); subtitleTextView.setTextColor(undoInfoColor); subtitleTextView.setLinkTextColor(undoLinkColor); subtitleTextView.setTypeface(Typeface.SANS_SERIF); subtitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); linearLayout.addView(subtitleTextView); } @Override protected void onShow() { super.onShow(); imageView.playAnimation(); } public void setAnimation(int resId, String... layers) { setAnimation(resId, 32, 32, layers); } public void setAnimation(int resId, int w, int h, String... layers) { imageView.setAnimation(resId, w, h); for (String layer : layers) { imageView.setLayerColor(layer + ".**", textColor); } } public CharSequence getAccessibilityText() { return titleTextView.getText() + ".\n" + subtitleTextView.getText(); } public void hideImage() { imageView.setVisibility(GONE); ((MarginLayoutParams) linearLayout.getLayoutParams()).setMarginStart(AndroidUtilities.dp(10)); } } public static class LottieLayoutWithReactions extends LottieLayout implements NotificationCenter.NotificationCenterDelegate { private ReactionsContainerLayout reactionsContainerLayout; private SparseLongArray newMessagesByIds; private final BaseFragment fragment; private final int messagesCount; public LottieLayoutWithReactions(BaseFragment fragment, int messagesCount) { super(fragment.getContext(), fragment.getResourceProvider()); this.fragment = fragment; this.messagesCount = messagesCount; init(); } private Bulletin bulletin; public void setBulletin(Bulletin b) { this.bulletin = b; } public void init() { textView.setLayoutParams(LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.TOP, 56, 6, 8, 0)); imageView.setLayoutParams(LayoutHelper.createFrameRelatively(56, 48, Gravity.START | Gravity.TOP)); reactionsContainerLayout = new ReactionsContainerLayout(ReactionsContainerLayout.TYPE_TAGS, fragment, getContext(), fragment.getCurrentAccount(), fragment.getResourceProvider()) { @Override protected void onShownCustomEmojiReactionDialog() { Bulletin bulletin = Bulletin.getVisibleBulletin(); if (bulletin != null) { bulletin.setCanHide(false); } reactionsContainerLayout.getReactionsWindow().windowView.setOnClickListener(v -> { hideReactionsDialog(); Bulletin.hideVisible(); }); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { if (bulletin != null) { bulletin.setCanHide(false); } } else if (ev.getAction() == MotionEvent.ACTION_UP) { if (bulletin != null) { bulletin.setCanHide(true); } } return super.dispatchTouchEvent(ev); } }; reactionsContainerLayout.setPadding(AndroidUtilities.dp(4), AndroidUtilities.dp(24), AndroidUtilities.dp(4), AndroidUtilities.dp(0)); reactionsContainerLayout.setDelegate(new ReactionsContainerLayout.ReactionsContainerDelegate() { @Override public void onReactionClicked(View view, ReactionsLayoutInBubble.VisibleReaction visibleReaction, boolean longpress, boolean addToRecent) { if (newMessagesByIds == null) { return; } final long selfId = UserConfig.getInstance(fragment.getCurrentAccount()).getClientUserId(); boolean isFragmentSavedMessages = fragment instanceof ChatActivity && ((ChatActivity) fragment).getDialogId() == selfId; int lastMessageId = 0; for (int i = 0; i < newMessagesByIds.size(); i++) { int key = newMessagesByIds.keyAt(i); TLRPC.Message message = new TLRPC.Message(); message.dialog_id = fragment.getUserConfig().getClientUserId(); message.id = key; MessageObject messageObject = new MessageObject(fragment.getCurrentAccount(), message, false, false); ArrayList<ReactionsLayoutInBubble.VisibleReaction> visibleReactions = new ArrayList<>(); visibleReactions.add(visibleReaction); fragment.getSendMessagesHelper().sendReaction(messageObject, visibleReactions, visibleReaction, false, false, fragment, null); lastMessageId = message.id; } hideReactionsDialog(); Bulletin.hideVisible(); showTaggedReactionToast(visibleReaction, fragment.getCurrentAccount(), lastMessageId, !isFragmentSavedMessages); } private void showTaggedReactionToast(ReactionsLayoutInBubble.VisibleReaction visibleReaction, int currentAccount, int messageId, boolean addViewButton) { AndroidUtilities.runOnUIThread(() -> { BaseFragment baseFragment = LaunchActivity.getLastFragment(); TLRPC.Document document; if (visibleReaction.documentId == 0) { TLRPC.TL_availableReaction availableReaction = MediaDataController.getInstance(UserConfig.selectedAccount).getReactionsMap().get(visibleReaction.emojicon); if (availableReaction == null) { return; } document = availableReaction.activate_animation; } else { document = AnimatedEmojiDrawable.findDocument(UserConfig.selectedAccount, visibleReaction.documentId); } if (document == null || baseFragment == null) { return; } BulletinFactory.of(baseFragment).createMessagesTaggedBulletin(messagesCount, document, addViewButton ? () -> { Bundle args = new Bundle(); args.putLong("user_id", UserConfig.getInstance(currentAccount).getClientUserId()); args.putInt("message_id", messageId); baseFragment.presentFragment(new ChatActivity(args)); } : null).show(true); }, 300); } }); reactionsContainerLayout.setTop(true); reactionsContainerLayout.setClipChildren(false); reactionsContainerLayout.setClipToPadding(false); reactionsContainerLayout.setVisibility(View.VISIBLE); reactionsContainerLayout.setBubbleOffset(-AndroidUtilities.dp(80)); reactionsContainerLayout.setHint(LocaleController.getString(R.string.SavedTagReactionsHint)); addView(reactionsContainerLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 92.5f, Gravity.CENTER_HORIZONTAL, 0, 36, 0, 0)); reactionsContainerLayout.setMessage(null, null, true); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); NotificationCenter.getInstance(UserConfig.selectedAccount).addObserver(this, NotificationCenter.savedMessagesForwarded); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); NotificationCenter.getInstance(UserConfig.selectedAccount).removeObserver(this, NotificationCenter.savedMessagesForwarded); } public void hideReactionsDialog() { if (reactionsContainerLayout.getReactionsWindow() != null) { reactionsContainerLayout.dismissWindow(); if (reactionsContainerLayout.getReactionsWindow().containerView != null) { reactionsContainerLayout.getReactionsWindow().containerView.animate().alpha(0).setDuration(180).start(); } } } @Override protected int getMeasuredBackgroundHeight() { return textView.getMeasuredHeight() + AndroidUtilities.dp(30); } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.savedMessagesForwarded) { newMessagesByIds = (SparseLongArray) args[0]; } } } public static class LottieLayout extends ButtonLayout { public RLottieImageView imageView; public TextView textView; private int textColor; public LottieLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { super(context, resourcesProvider); imageView = new RLottieImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER); addView(imageView, LayoutHelper.createFrameRelatively(56, 48, Gravity.START | Gravity.CENTER_VERTICAL)); textView = new LinkSpanDrawable.LinksTextView(context) { { setDisablePaddingsOffset(true); } @Override public void setText(CharSequence text, BufferType type) { text = Emoji.replaceEmoji(text, getPaint().getFontMetricsInt(), AndroidUtilities.dp(13), false); super.setText(text, type); } }; NotificationCenter.listenEmojiLoading(textView); textView.setSingleLine(); textView.setTypeface(Typeface.SANS_SERIF); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setPadding(0, AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8)); addView(textView, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 56, 0, 8, 0)); textView.setLinkTextColor(getThemedColor(Theme.key_undo_cancelColor)); setTextColor(getThemedColor(Theme.key_undo_infoColor)); setBackground(getThemedColor(Theme.key_undo_background)); } public LottieLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider, int backgroundColor, int textColor) { this(context, resourcesProvider); setBackground(backgroundColor); setTextColor(textColor); } public void setTextColor(int textColor) { this.textColor = textColor; textView.setTextColor(textColor); } @Override protected void onShow() { super.onShow(); imageView.playAnimation(); } public void setAnimation(int resId, String... layers) { setAnimation(resId, 32, 32, layers); } public void setAnimation(int resId, int w, int h, String... layers) { imageView.setAnimation(resId, w, h); for (String layer : layers) { imageView.setLayerColor(layer + ".**", textColor); } } public void setAnimation(TLRPC.Document document, int w, int h, String... layers) { imageView.setAutoRepeat(true); imageView.setAnimation(document, w, h); for (String layer : layers) { imageView.setLayerColor(layer + ".**", textColor); } } public void setIconPaddingBottom(int paddingBottom) { imageView.setLayoutParams(LayoutHelper.createFrameRelatively(56, 48 - paddingBottom, Gravity.START | Gravity.CENTER_VERTICAL, 0, 0, 0, paddingBottom)); } public CharSequence getAccessibilityText() { return textView.getText(); } } public static interface LoadingLayout { void onTextLoaded(CharSequence text); } public static class LoadingLottieLayout extends LottieLayout implements LoadingLayout { public LinkSpanDrawable.LinksTextView textLoadingView; public LoadingLottieLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { super(context, resourcesProvider); textLoadingView = new LinkSpanDrawable.LinksTextView(context); textLoadingView.setDisablePaddingsOffset(true); textLoadingView.setSingleLine(); textLoadingView.setTypeface(Typeface.SANS_SERIF); textLoadingView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); textLoadingView.setEllipsize(TextUtils.TruncateAt.END); textLoadingView.setPadding(0, AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8)); textView.setVisibility(View.GONE); addView(textLoadingView, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 56, 0, 8, 0)); setTextColor(getThemedColor(Theme.key_undo_infoColor)); } public LoadingLottieLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider, int backgroundColor, int textColor) { this(context, resourcesProvider); setBackground(backgroundColor); setTextColor(textColor); } @Override public void setTextColor(int textColor) { super.setTextColor(textColor); if (textLoadingView != null) { textLoadingView.setTextColor(textColor); } } public void onTextLoaded(CharSequence text) { textView.setText(text); AndroidUtilities.updateViewShow(textLoadingView, false, false, true); AndroidUtilities.updateViewShow(textView, true, false, true); } } public static class UsersLayout extends ButtonLayout { public AvatarsImageView avatarsImageView; public TextView textView; public TextView subtitleView; LinearLayout linearLayout; public UsersLayout(@NonNull Context context, boolean subtitle, Theme.ResourcesProvider resourcesProvider) { super(context, resourcesProvider); avatarsImageView = new AvatarsImageView(context, false); avatarsImageView.setStyle(AvatarsDrawable.STYLE_MESSAGE_SEEN); avatarsImageView.setAvatarsTextSize(AndroidUtilities.dp(18)); addView(avatarsImageView, LayoutHelper.createFrameRelatively(24 + 12 + 12 + 8, 48, Gravity.START | Gravity.CENTER_VERTICAL, 12, 0, 0, 0)); if (!subtitle) { textView = new LinkSpanDrawable.LinksTextView(context) { @Override public void setText(CharSequence text, BufferType type) { text = Emoji.replaceEmoji(text, getPaint().getFontMetricsInt(), AndroidUtilities.dp(13), false); super.setText(text, type); } }; NotificationCenter.listenEmojiLoading(textView); textView.setTypeface(Typeface.SANS_SERIF); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setPadding(0, AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8)); textView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); addView(textView, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 12 + 56 + 2, 0, 12, 0)); } else { linearLayout = new LinearLayout(getContext()); linearLayout.setOrientation(LinearLayout.VERTICAL); addView(linearLayout, LayoutHelper.createFrameRelatively(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 18 + 56 + 2, 0, 12, 0)); textView = new LinkSpanDrawable.LinksTextView(context) { @Override public void setText(CharSequence text, BufferType type) { text = Emoji.replaceEmoji(text, getPaint().getFontMetricsInt(), AndroidUtilities.dp(13), false); super.setText(text, type); } }; NotificationCenter.listenEmojiLoading(textView); textView.setTypeface(Typeface.SANS_SERIF); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setMaxLines(1); linearLayout.addView(textView); subtitleView = new LinkSpanDrawable.LinksTextView(context); subtitleView.setTypeface(Typeface.SANS_SERIF); subtitleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); subtitleView.setEllipsize(TextUtils.TruncateAt.END); subtitleView.setMaxLines(1); subtitleView.setLinkTextColor(getThemedColor(Theme.key_undo_cancelColor)); linearLayout.addView(subtitleView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, 0, 0, 0, 0, 0)); } textView.setLinkTextColor(getThemedColor(Theme.key_undo_cancelColor)); setTextColor(getThemedColor(Theme.key_undo_infoColor)); setBackground(getThemedColor(Theme.key_undo_background)); } public UsersLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider, int backgroundColor, int textColor) { this(context, false, resourcesProvider); setBackground(backgroundColor); setTextColor(textColor); } public void setTextColor(int textColor) { textView.setTextColor(textColor); if (subtitleView != null) { subtitleView.setTextColor(textColor); } } @Override protected void onShow() { super.onShow(); } public CharSequence getAccessibilityText() { return textView.getText(); } } //endregion //region Buttons @SuppressLint("ViewConstructor") public abstract static class Button extends FrameLayout implements Layout.Callback { public Button(@NonNull Context context) { super(context); } @Override public void onAttach(@NonNull Layout layout, @NonNull Bulletin bulletin) { } @Override public void onDetach(@NonNull Layout layout) { } @Override public void onShow(@NonNull Layout layout) { } @Override public void onHide(@NonNull Layout layout) { } @Override public void onEnterTransitionStart(@NonNull Layout layout) { } @Override public void onEnterTransitionEnd(@NonNull Layout layout) { } @Override public void onExitTransitionStart(@NonNull Layout layout) { } @Override public void onExitTransitionEnd(@NonNull Layout layout) { } } @SuppressLint("ViewConstructor") public static final class UndoButton extends Button { private final Theme.ResourcesProvider resourcesProvider; private Runnable undoAction; private Runnable delayedAction; private Bulletin bulletin; private TextView undoTextView; private boolean isUndone; public UndoButton(@NonNull Context context, boolean text) { this(context, text, null); } public UndoButton(@NonNull Context context, boolean text, Theme.ResourcesProvider resourcesProvider) { this(context, text, !text, resourcesProvider); } public UndoButton(@NonNull Context context, boolean text, boolean icon, Theme.ResourcesProvider resourcesProvider) { super(context); this.resourcesProvider = resourcesProvider; final int undoCancelColor = getThemedColor(Theme.key_undo_cancelColor); if (text) { undoTextView = new TextView(context); undoTextView.setBackground(Theme.createSelectorDrawable((undoCancelColor & 0x00ffffff) | 0x19000000, Theme.RIPPLE_MASK_ROUNDRECT_6DP)); undoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); undoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); undoTextView.setTextColor(undoCancelColor); undoTextView.setText(LocaleController.getString("Undo", R.string.Undo)); undoTextView.setGravity(Gravity.CENTER_VERTICAL); ViewHelper.setPaddingRelative(undoTextView, icon ? 34 : 12, 8, 12, 8); addView(undoTextView, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 8, 0, 8, 0)); } if (icon) { final ImageView undoImageView = new ImageView(getContext()); undoImageView.setImageResource(R.drawable.chats_undo); undoImageView.setColorFilter(new PorterDuffColorFilter(undoCancelColor, PorterDuff.Mode.MULTIPLY)); if (!text) { undoImageView.setBackground(Theme.createSelectorDrawable((undoCancelColor & 0x00ffffff) | 0x19000000)); } ViewHelper.setPaddingRelative(undoImageView, 0, 12, 0, 12); addView(undoImageView, LayoutHelper.createFrameRelatively(56, 48, Gravity.CENTER_VERTICAL)); } setOnClickListener(v -> undo()); } public UndoButton setText(CharSequence text) { if (undoTextView != null) { undoTextView.setText(text); } return this; } public void undo() { if (bulletin != null) { isUndone = true; if (undoAction != null) { undoAction.run(); } if (bulletin != null) { bulletin.hide(); } } } @Override public void onAttach(@NonNull Layout layout, @NonNull Bulletin bulletin) { this.bulletin = bulletin; } @Override public void onDetach(@NonNull Layout layout) { this.bulletin = null; if (delayedAction != null && !isUndone) { delayedAction.run(); } } public UndoButton setUndoAction(Runnable undoAction) { this.undoAction = undoAction; return this; } public UndoButton setDelayedAction(Runnable delayedAction) { this.delayedAction = delayedAction; return this; } protected int getThemedColor(int key) { if (resourcesProvider != null) { return resourcesProvider.getColor(key); } return Theme.getColor(key); } } // TODO: possibility of loading icon as well public void onLoaded(CharSequence text) { loaded = true; if (layout instanceof LoadingLayout) { ((LoadingLayout) layout).onTextLoaded(text); } setCanHide(true); } //endregion public static class EmptyBulletin extends Bulletin { public EmptyBulletin() { super(); } @Override public Bulletin show() { return this; } } private static class TimerView extends View { private final Paint progressPaint; private long timeLeft; private int prevSeconds; private String timeLeftString; private int textWidth; StaticLayout timeLayout; StaticLayout timeLayoutOut; int textWidthOut; float timeReplaceProgress = 1f; private TextPaint textPaint; private long lastUpdateTime; RectF rect = new RectF(); public TimerView(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize(AndroidUtilities.dp(12)); textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textPaint.setColor(Theme.getColor(Theme.key_undo_infoColor, resourcesProvider)); progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG); progressPaint.setStyle(Paint.Style.STROKE); progressPaint.setStrokeWidth(AndroidUtilities.dp(2)); progressPaint.setStrokeCap(Paint.Cap.ROUND); progressPaint.setColor(Theme.getColor(Theme.key_undo_infoColor, resourcesProvider)); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int newSeconds = timeLeft > 0 ? (int) Math.ceil(timeLeft / 1000.0f) : 0; rect.set(AndroidUtilities.dp(1), AndroidUtilities.dp(1), getMeasuredWidth() - AndroidUtilities.dp(1), getMeasuredHeight() - AndroidUtilities.dp(1)); if (prevSeconds != newSeconds) { prevSeconds = newSeconds; timeLeftString = String.valueOf(Math.max(0, 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, android.text.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() - textWidthOut / 2f, rect.centerY() - timeLayoutOut.getHeight() / 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 / 2f, rect.centerY() - timeLayout.getHeight() / 2f - AndroidUtilities.dp(10) * (1f - timeReplaceProgress)); timeLayout.draw(canvas); if (timeReplaceProgress != 1f) { textPaint.setAlpha(alpha); } canvas.restore(); } canvas.drawArc(rect, -90, -360 * (Math.max(0, timeLeft) / 5000.0f), false, progressPaint); if (lastUpdateTime != 0) { long newTime = System.currentTimeMillis(); long dt = newTime - lastUpdateTime; timeLeft -= dt; lastUpdateTime = newTime; } else { lastUpdateTime = System.currentTimeMillis(); } invalidate(); } } // to make bulletin above everything // use as BulletinFactory.of(BulletinWindow.make(context), resourcesProvider)... public static class BulletinWindow extends Dialog { public static BulletinWindowLayout make(Context context, Delegate delegate) { return new BulletinWindow(context, delegate).container; } public static BulletinWindowLayout make(Context context) { return new BulletinWindow(context, null).container; } private final BulletinWindowLayout container; private BulletinWindow(Context context, Delegate delegate) { super(context); setContentView( container = new BulletinWindowLayout(context), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) ); if (Build.VERSION.SDK_INT >= 21) { container.setFitsSystemWindows(true); container.setOnApplyWindowInsetsListener((v, insets) -> { applyInsets(insets); v.requestLayout(); if (Build.VERSION.SDK_INT >= 30) { return WindowInsets.CONSUMED; } else { return insets.consumeSystemWindowInsets(); } }); if (Build.VERSION.SDK_INT >= 30) { container.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); } else { container.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } } addDelegate(container, new Delegate() { @Override public int getBottomOffset(int tag) { return delegate == null ? 0 : delegate.getBottomOffset(tag); } @Override public int getTopOffset(int tag) { return delegate == null ? AndroidUtilities.statusBarHeight : delegate.getTopOffset(tag); } @Override public boolean clipWithGradient(int tag) { return delegate != null && delegate.clipWithGradient(tag); } }); try { Window window = getWindow(); window.setWindowAnimations(R.style.DialogNoAnimation); window.setBackgroundDrawable(null); params = window.getAttributes(); params.width = ViewGroup.LayoutParams.MATCH_PARENT; params.height = ViewGroup.LayoutParams.MATCH_PARENT; params.gravity = Gravity.TOP | Gravity.LEFT; params.dimAmount = 0; params.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND; params.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { params.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION; } params.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; if (Build.VERSION.SDK_INT >= 21) { params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS; } params.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN; if (Build.VERSION.SDK_INT >= 28) { params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; } window.setAttributes(params); AndroidUtilities.setLightNavigationBar(window, AndroidUtilities.computePerceivedBrightness(Theme.getColor(Theme.key_windowBackgroundGray)) > 0.721f); } catch (Exception ignore) {} } @RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH) private void applyInsets(WindowInsets insets) { if (container != null) { container.setPadding( insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(), insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom() ); } } private WindowManager.LayoutParams params; public class BulletinWindowLayout extends FrameLayout { public BulletinWindowLayout(Context context) { super(context); } @Override public void addView(View child) { super.addView(child); BulletinWindow.this.show(); } @Override public void removeView(View child) { super.removeView(child); try { BulletinWindow.this.dismiss(); } catch (Exception ignore) { } removeDelegate(container); } public void setTouchable(boolean touchable) { if (params == null) { return; } if (!touchable) { params.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; } else { params.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; } BulletinWindow.this.getWindow().setAttributes(params); } @Nullable public WindowManager.LayoutParams getLayout() { return params; } public void updateLayout() { BulletinWindow.this.getWindow().setAttributes(params); } } } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Components/Bulletin.java
2,166
/* * 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.graphics.Canvas; import android.graphics.Matrix; import android.graphics.RectF; import android.text.TextUtils; import android.view.View; import org.telegram.messenger.video.MediaCodecVideoConvertor; import org.telegram.tgnet.AbstractSerializedData; import org.telegram.tgnet.SerializedData; import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.tl.TL_stories; import org.telegram.ui.Components.AnimatedFileDrawable; import org.telegram.ui.Components.Paint.PaintTypeface; import org.telegram.ui.Components.PhotoFilterView; import org.telegram.ui.Components.Point; import org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble; import org.telegram.ui.Stories.recorder.StoryEntry; import java.util.ArrayList; import java.util.Locale; public class VideoEditedInfo { public long startTime; public long endTime; public long avatarStartTime = -1; public float start; public float end; public int compressQuality; public int rotationValue; public int originalWidth; public int originalHeight; public int originalBitrate; public int resultWidth; public int resultHeight; public int bitrate; public int framerate = 24; public String originalPath; public long estimatedSize; public long estimatedDuration; public boolean roundVideo; public boolean muted; public float volume = 1f; public long originalDuration; public TLRPC.InputFile file; public TLRPC.InputEncryptedFile encryptedFile; public byte[] key; public byte[] iv; public MediaController.SavedFilterState filterState; public String paintPath, blurPath, messagePath, messageVideoMaskPath, backgroundPath; public ArrayList<MediaEntity> mediaEntities; public MediaController.CropState cropState; public boolean isPhoto; public boolean isStory; public StoryEntry.HDRInfo hdrInfo; public boolean isSticker; public Bitmap thumb; public boolean notReadyYet; public Integer gradientTopColor, gradientBottomColor; public int account; public boolean isDark; public long wallpaperPeerId = Long.MIN_VALUE; public boolean forceFragmenting; public boolean alreadyScheduledConverting; public boolean canceled; public boolean videoConvertFirstWrite; public boolean needUpdateProgress = false; public boolean shouldLimitFps = true; public boolean tryUseHevc = false; public boolean fromCamera; public ArrayList<MediaCodecVideoConvertor.MixedSoundInfo> mixedSoundInfos = new ArrayList<>(); public static class EmojiEntity extends TLRPC.TL_messageEntityCustomEmoji { public String documentAbsolutePath; public MediaEntity entity; public byte subType; @Override public void readParams(AbstractSerializedData stream, boolean exception) { super.readParams(stream, exception); subType = stream.readByte(exception); boolean hasPath = stream.readBool(exception); if (hasPath) { documentAbsolutePath = stream.readString(exception); } if (TextUtils.isEmpty(documentAbsolutePath)) { documentAbsolutePath = null; } } @Override public void serializeToStream(AbstractSerializedData stream) { super.serializeToStream(stream); stream.writeByte(subType); stream.writeBool(!TextUtils.isEmpty(documentAbsolutePath)); if (!TextUtils.isEmpty(documentAbsolutePath)) { stream.writeString(documentAbsolutePath); } } } public static class MediaEntity { public static final byte TYPE_STICKER = 0; public static final byte TYPE_TEXT = 1; public static final byte TYPE_PHOTO = 2; public static final byte TYPE_LOCATION = 3; public static final byte TYPE_REACTION = 4; public static final byte TYPE_ROUND = 5; public static final byte TYPE_MESSAGE = 6; public byte type; public byte subType; public float x; public float y; public float rotation; public float width; public float height; public float additionalWidth, additionalHeight; public String text = ""; public ArrayList<EmojiEntity> entities = new ArrayList<>(); public int color; public int fontSize; public PaintTypeface textTypeface; public String textTypefaceKey; public int textAlign; public int viewWidth; public int viewHeight; public float roundRadius; public String segmentedPath = ""; public float scale = 1.0f; public float textViewWidth; public float textViewHeight; public float textViewX; public float textViewY; public boolean customTextView; public TLRPC.Document document; public Object parentObject; public int[] metadata; public long ptr; public float currentFrame; public float framesPerDraw; public Bitmap bitmap; public Matrix matrix; public View view; public Canvas canvas; public AnimatedFileDrawable animatedFileDrawable; public boolean looped; public Canvas roundRadiusCanvas; public boolean firstSeek; public TL_stories.MediaArea mediaArea; public TLRPC.MessageMedia mediaGeo; public float density; public long roundOffset; public long roundLeft; public long roundRight; public long roundDuration; public int W, H; public ReactionsLayoutInBubble.VisibleReaction visibleReaction; public MediaEntity() { } public MediaEntity(AbstractSerializedData data, boolean full) { this(data, full, false); } public MediaEntity(AbstractSerializedData data, boolean full, boolean exception) { type = data.readByte(exception); subType = data.readByte(exception); x = data.readFloat(exception); y = data.readFloat(exception); rotation = data.readFloat(exception); width = data.readFloat(exception); height = data.readFloat(exception); text = data.readString(exception); int count = data.readInt32(exception); for (int i = 0; i < count; ++i) { EmojiEntity entity = new EmojiEntity(); data.readInt32(exception); entity.readParams(data, exception); entities.add(entity); } color = data.readInt32(exception); fontSize = data.readInt32(exception); viewWidth = data.readInt32(exception); viewHeight = data.readInt32(exception); textAlign = data.readInt32(exception); textTypeface = PaintTypeface.find(textTypefaceKey = data.readString(exception)); scale = data.readFloat(exception); textViewWidth = data.readFloat(exception); textViewHeight = data.readFloat(exception); textViewX = data.readFloat(exception); textViewY = data.readFloat(exception); if (full) { int magic = data.readInt32(exception); if (magic == TLRPC.TL_null.constructor) { document = null; } else { document = TLRPC.Document.TLdeserialize(data, magic, exception); } } if (type == TYPE_LOCATION) { density = data.readFloat(exception); mediaArea = TL_stories.MediaArea.TLdeserialize(data, data.readInt32(exception), exception); mediaGeo = TLRPC.MessageMedia.TLdeserialize(data, data.readInt32(exception), exception); if (data.remaining() > 0) { int magic = data.readInt32(exception); if (magic == 0xdeadbeef) { String emoji = data.readString(exception); if (mediaGeo instanceof TLRPC.TL_messageMediaVenue) { ((TLRPC.TL_messageMediaVenue) mediaGeo).emoji = emoji; } } } } if (type == TYPE_REACTION) { mediaArea = TL_stories.MediaArea.TLdeserialize(data, data.readInt32(exception), exception); } if (type == TYPE_ROUND) { roundOffset = data.readInt64(exception); roundLeft = data.readInt64(exception); roundRight = data.readInt64(exception); roundDuration = data.readInt64(exception); } if (type == TYPE_PHOTO) { segmentedPath = data.readString(exception); } } public void serializeTo(AbstractSerializedData data, boolean full) { data.writeByte(type); data.writeByte(subType); data.writeFloat(x); data.writeFloat(y); data.writeFloat(rotation); data.writeFloat(width); data.writeFloat(height); data.writeString(text); data.writeInt32(entities.size()); for (int i = 0; i < entities.size(); ++i) { entities.get(i).serializeToStream(data); } data.writeInt32(color); data.writeInt32(fontSize); data.writeInt32(viewWidth); data.writeInt32(viewHeight); data.writeInt32(textAlign); data.writeString(textTypeface == null ? (textTypefaceKey == null ? "" : textTypefaceKey) : textTypeface.getKey()); data.writeFloat(scale); data.writeFloat(textViewWidth); data.writeFloat(textViewHeight); data.writeFloat(textViewX); data.writeFloat(textViewY); if (full) { if (document == null) { data.writeInt32(TLRPC.TL_null.constructor); } else { document.serializeToStream(data); } } if (type == TYPE_LOCATION) { data.writeFloat(density); mediaArea.serializeToStream(data); if (mediaGeo.provider == null) { mediaGeo.provider = ""; } if (mediaGeo.venue_id == null) { mediaGeo.venue_id = ""; } if (mediaGeo.venue_type == null) { mediaGeo.venue_type = ""; } mediaGeo.serializeToStream(data); if (mediaGeo instanceof TLRPC.TL_messageMediaVenue && ((TLRPC.TL_messageMediaVenue) mediaGeo).emoji != null) { data.writeInt32(0xdeadbeef); data.writeString(((TLRPC.TL_messageMediaVenue) mediaGeo).emoji); } else { data.writeInt32(TLRPC.TL_null.constructor); } } if (type == TYPE_REACTION) { mediaArea.serializeToStream(data); } if (type == TYPE_ROUND) { data.writeInt64(roundOffset); data.writeInt64(roundLeft); data.writeInt64(roundRight); data.writeInt64(roundDuration); } if (type == TYPE_PHOTO) { data.writeString(segmentedPath); } } public MediaEntity copy() { MediaEntity entity = new MediaEntity(); entity.type = type; entity.subType = subType; entity.x = x; entity.y = y; entity.rotation = rotation; entity.width = width; entity.height = height; entity.additionalHeight = additionalHeight; entity.text = text; if (entities != null) { entity.entities = new ArrayList<>(); entity.entities.addAll(entities); } entity.color = color; entity.fontSize = fontSize; entity.textTypeface = textTypeface; entity.textTypefaceKey = textTypefaceKey; entity.textAlign = textAlign; entity.viewWidth = viewWidth; entity.viewHeight = viewHeight; entity.roundRadius = roundRadius; entity.scale = scale; entity.textViewWidth = textViewWidth; entity.textViewHeight = textViewHeight; entity.textViewX = textViewX; entity.textViewY = textViewY; entity.document = document; entity.parentObject = parentObject; entity.metadata = metadata; entity.ptr = ptr; entity.currentFrame = currentFrame; entity.framesPerDraw = framesPerDraw; entity.bitmap = bitmap; entity.view = view; entity.canvas = canvas; entity.animatedFileDrawable = animatedFileDrawable; entity.roundRadiusCanvas = roundRadiusCanvas; entity.mediaArea = mediaArea; entity.mediaGeo = mediaGeo; entity.density = density; entity.W = W; entity.H = H; entity.visibleReaction = visibleReaction; entity.roundOffset = roundOffset; entity.roundDuration = roundDuration; entity.roundLeft = roundLeft; entity.roundRight = roundRight; return entity; } } public String getString() { String filters; if (avatarStartTime != -1 || filterState != null || paintPath != null || blurPath != null || mediaEntities != null && !mediaEntities.isEmpty() || cropState != null) { int len = 10; if (filterState != null) { len += 160; } byte[] paintPathBytes; if (paintPath != null) { paintPathBytes = paintPath.getBytes(); len += paintPathBytes.length; } else { paintPathBytes = null; } byte[] blurPathBytes; if (blurPath != null) { blurPathBytes = blurPath.getBytes(); len += blurPathBytes.length; } else { blurPathBytes = null; } SerializedData serializedData = new SerializedData(len); serializedData.writeInt32(10); serializedData.writeInt64(avatarStartTime); serializedData.writeInt32(originalBitrate); if (filterState != null) { serializedData.writeByte(1); serializedData.writeFloat(filterState.enhanceValue); serializedData.writeFloat(filterState.softenSkinValue); serializedData.writeFloat(filterState.exposureValue); serializedData.writeFloat(filterState.contrastValue); serializedData.writeFloat(filterState.warmthValue); serializedData.writeFloat(filterState.saturationValue); serializedData.writeFloat(filterState.fadeValue); serializedData.writeInt32(filterState.tintShadowsColor); serializedData.writeInt32(filterState.tintHighlightsColor); serializedData.writeFloat(filterState.highlightsValue); serializedData.writeFloat(filterState.shadowsValue); serializedData.writeFloat(filterState.vignetteValue); serializedData.writeFloat(filterState.grainValue); serializedData.writeInt32(filterState.blurType); serializedData.writeFloat(filterState.sharpenValue); serializedData.writeFloat(filterState.blurExcludeSize); if (filterState.blurExcludePoint != null) { serializedData.writeFloat(filterState.blurExcludePoint.x); serializedData.writeFloat(filterState.blurExcludePoint.y); } else { serializedData.writeFloat(0); serializedData.writeFloat(0); } serializedData.writeFloat(filterState.blurExcludeBlurSize); serializedData.writeFloat(filterState.blurAngle); for (int a = 0; a < 4; a++) { PhotoFilterView.CurvesValue curvesValue; if (a == 0) { curvesValue = filterState.curvesToolValue.luminanceCurve; } else if (a == 1) { curvesValue = filterState.curvesToolValue.redCurve; } else if (a == 2) { curvesValue = filterState.curvesToolValue.greenCurve; } else { curvesValue = filterState.curvesToolValue.blueCurve; } serializedData.writeFloat(curvesValue.blacksLevel); serializedData.writeFloat(curvesValue.shadowsLevel); serializedData.writeFloat(curvesValue.midtonesLevel); serializedData.writeFloat(curvesValue.highlightsLevel); serializedData.writeFloat(curvesValue.whitesLevel); } } else { serializedData.writeByte(0); } if (paintPathBytes != null) { serializedData.writeByte(1); serializedData.writeByteArray(paintPathBytes); } else { serializedData.writeByte(0); } if (mediaEntities != null && !mediaEntities.isEmpty()) { serializedData.writeByte(1); serializedData.writeInt32(mediaEntities.size()); for (int a = 0, N = mediaEntities.size(); a < N; a++) { mediaEntities.get(a).serializeTo(serializedData, false); } serializedData.writeByte(isPhoto ? 1 : 0); } else { serializedData.writeByte(0); } if (cropState != null) { serializedData.writeByte(1); serializedData.writeFloat(cropState.cropPx); serializedData.writeFloat(cropState.cropPy); serializedData.writeFloat(cropState.cropPw); serializedData.writeFloat(cropState.cropPh); serializedData.writeFloat(cropState.cropScale); serializedData.writeFloat(cropState.cropRotate); serializedData.writeInt32(cropState.transformWidth); serializedData.writeInt32(cropState.transformHeight); serializedData.writeInt32(cropState.transformRotation); serializedData.writeBool(cropState.mirrored); } else { serializedData.writeByte(0); } serializedData.writeInt32(0); serializedData.writeBool(isStory); serializedData.writeBool(fromCamera); if (blurPathBytes != null) { serializedData.writeByte(1); serializedData.writeByteArray(blurPathBytes); } else { serializedData.writeByte(0); } serializedData.writeFloat(volume); serializedData.writeBool(isSticker); filters = Utilities.bytesToHex(serializedData.toByteArray()); serializedData.cleanup(); } else { filters = ""; } return String.format(Locale.US, "-1_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_-%s_%s", startTime, endTime, rotationValue, originalWidth, originalHeight, bitrate, resultWidth, resultHeight, originalDuration, framerate, filters, originalPath); } public boolean parseString(String string) { if (string.length() < 6) { return false; } try { String[] args = string.split("_"); if (args.length >= 11) { startTime = Long.parseLong(args[1]); endTime = Long.parseLong(args[2]); rotationValue = Integer.parseInt(args[3]); originalWidth = Integer.parseInt(args[4]); originalHeight = Integer.parseInt(args[5]); bitrate = Integer.parseInt(args[6]); resultWidth = Integer.parseInt(args[7]); resultHeight = Integer.parseInt(args[8]); originalDuration = Long.parseLong(args[9]); framerate = Integer.parseInt(args[10]); muted = bitrate == -1; int start; if (args[11].startsWith("-")) { start = 12; String s = args[11].substring(1); if (s.length() > 0) { SerializedData serializedData = new SerializedData(Utilities.hexToBytes(s)); int version = serializedData.readInt32(false); if (version >= 3) { avatarStartTime = serializedData.readInt64(false); originalBitrate = serializedData.readInt32(false); } byte has = serializedData.readByte(false); if (has != 0) { filterState = new MediaController.SavedFilterState(); filterState.enhanceValue = serializedData.readFloat(false); if (version >= 5) { filterState.softenSkinValue = serializedData.readFloat(false); } filterState.exposureValue = serializedData.readFloat(false); filterState.contrastValue = serializedData.readFloat(false); filterState.warmthValue = serializedData.readFloat(false); filterState.saturationValue = serializedData.readFloat(false); filterState.fadeValue = serializedData.readFloat(false); filterState.tintShadowsColor = serializedData.readInt32(false); filterState.tintHighlightsColor = serializedData.readInt32(false); filterState.highlightsValue = serializedData.readFloat(false); filterState.shadowsValue = serializedData.readFloat(false); filterState.vignetteValue = serializedData.readFloat(false); filterState.grainValue = serializedData.readFloat(false); filterState.blurType = serializedData.readInt32(false); filterState.sharpenValue = serializedData.readFloat(false); filterState.blurExcludeSize = serializedData.readFloat(false); filterState.blurExcludePoint = new Point(serializedData.readFloat(false), serializedData.readFloat(false)); filterState.blurExcludeBlurSize = serializedData.readFloat(false); filterState.blurAngle = serializedData.readFloat(false); for (int a = 0; a < 4; a++) { PhotoFilterView.CurvesValue curvesValue; if (a == 0) { curvesValue = filterState.curvesToolValue.luminanceCurve; } else if (a == 1) { curvesValue = filterState.curvesToolValue.redCurve; } else if (a == 2) { curvesValue = filterState.curvesToolValue.greenCurve; } else { curvesValue = filterState.curvesToolValue.blueCurve; } curvesValue.blacksLevel = serializedData.readFloat(false); curvesValue.shadowsLevel = serializedData.readFloat(false); curvesValue.midtonesLevel = serializedData.readFloat(false); curvesValue.highlightsLevel = serializedData.readFloat(false); curvesValue.whitesLevel = serializedData.readFloat(false); } } has = serializedData.readByte(false); if (has != 0) { byte[] bytes = serializedData.readByteArray(false); paintPath = new String(bytes); } has = serializedData.readByte(false); if (has != 0) { int count = serializedData.readInt32(false); mediaEntities = new ArrayList<>(count); for (int a = 0; a < count; a++) { mediaEntities.add(new MediaEntity(serializedData, false)); } isPhoto = serializedData.readByte(false) == 1; } if (version >= 2) { has = serializedData.readByte(false); if (has != 0) { cropState = new MediaController.CropState(); cropState.cropPx = serializedData.readFloat(false); cropState.cropPy = serializedData.readFloat(false); cropState.cropPw = serializedData.readFloat(false); cropState.cropPh = serializedData.readFloat(false); cropState.cropScale = serializedData.readFloat(false); cropState.cropRotate = serializedData.readFloat(false); cropState.transformWidth = serializedData.readInt32(false); cropState.transformHeight = serializedData.readInt32(false); cropState.transformRotation = serializedData.readInt32(false); if (version >= 4) { cropState.mirrored = serializedData.readBool(false); } } } if (version >= 6) { serializedData.readInt32(false); } if (version >= 7) { isStory = serializedData.readBool(false); fromCamera = serializedData.readBool(false); } if (version >= 8) { has = serializedData.readByte(false); if (has != 0) { byte[] bytes = serializedData.readByteArray(false); blurPath = new String(bytes); } } if (version >= 9) { volume = serializedData.readFloat(false); } if (version >= 10) { isSticker = serializedData.readBool(false); } serializedData.cleanup(); } } else { start = 11; } for (int a = start; a < args.length; a++) { if (originalPath == null) { originalPath = args[a]; } else { originalPath += "_" + args[a]; } } } return true; } catch (Exception e) { FileLog.e(e); } return false; } public boolean needConvert() { if (isStory) { if (!fromCamera) { return true; } return !mixedSoundInfos.isEmpty() || mediaEntities != null || paintPath != null || blurPath != null || filterState != null || (cropState != null && !cropState.isEmpty()) || startTime > 0 || endTime != -1 && endTime != estimatedDuration || originalHeight != resultHeight || originalWidth != resultWidth; } return !mixedSoundInfos.isEmpty() || mediaEntities != null || paintPath != null || blurPath != null || filterState != null || cropState != null || !roundVideo || startTime > 0 || endTime != -1 && endTime != estimatedDuration; } public boolean canAutoPlaySourceVideo() { return roundVideo; } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/VideoEditedInfo.java
2,167
/* * Copyright 2015 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.graphics.SurfaceTexture; import android.opengl.EGL14; import android.opengl.EGLConfig; import android.opengl.EGLContext; import android.opengl.EGLDisplay; import android.opengl.EGLExt; import android.opengl.EGLSurface; import android.os.Build; import androidx.annotation.Nullable; import android.view.Surface; import org.webrtc.EglBase; /** * Holds EGL state and utility methods for handling an EGL14 EGLContext, an EGLDisplay, * and an EGLSurface. */ @SuppressWarnings("ReferenceEquality") // We want to compare to EGL14 constants. @TargetApi(18) class EglBase14Impl implements EglBase14 { private static final String TAG = "EglBase14Impl"; private static final int EGLExt_SDK_VERSION = Build.VERSION_CODES.JELLY_BEAN_MR2; private static final int CURRENT_SDK_VERSION = Build.VERSION.SDK_INT; private EGLContext eglContext; @Nullable private EGLConfig eglConfig; private EGLDisplay eglDisplay; private EGLSurface eglSurface = EGL14.EGL_NO_SURFACE; private EGLSurface eglSurfaceBackground = EGL14.EGL_NO_SURFACE; // EGL 1.4 is supported from API 17. But EGLExt that is used for setting presentation // time stamp on a surface is supported from 18 so we require 18. public static boolean isEGL14Supported() { Logging.d(TAG, "SDK version: " + CURRENT_SDK_VERSION + ". isEGL14Supported: " + (CURRENT_SDK_VERSION >= EGLExt_SDK_VERSION)); return (CURRENT_SDK_VERSION >= EGLExt_SDK_VERSION); } public static class Context implements EglBase14.Context { private final EGLContext egl14Context; @Override public EGLContext getRawContext() { return egl14Context; } @Override @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.LOLLIPOP) public long getNativeEglContext() { return CURRENT_SDK_VERSION >= Build.VERSION_CODES.LOLLIPOP ? egl14Context.getNativeHandle() : egl14Context.getHandle(); } public Context(android.opengl.EGLContext eglContext) { this.egl14Context = eglContext; } } // Create a new context with the specified config type, sharing data with sharedContext. // |sharedContext| may be null. public EglBase14Impl(EGLContext sharedContext, int[] configAttributes) { eglDisplay = getEglDisplay(); eglConfig = getEglConfig(eglDisplay, configAttributes); final int openGlesVersion = EglBase.getOpenGlesVersionFromConfig(configAttributes); Logging.d(TAG, "Using OpenGL ES version " + openGlesVersion); eglContext = createEglContext(sharedContext, eglDisplay, eglConfig, openGlesVersion); } // Create EGLSurface from the Android Surface. @Override public void createSurface(Surface surface) { createSurfaceInternal(surface, false); } // Create EGLSurface from the Android Surface. @Override public void createBackgroundSurface(SurfaceTexture surface) { createSurfaceInternal(surface, true); } // Create EGLSurface from the Android SurfaceTexture. @Override public void createSurface(SurfaceTexture surfaceTexture) { createSurfaceInternal(surfaceTexture, false); } // Create EGLSurface from either Surface or SurfaceTexture. private void createSurfaceInternal(Object surface, boolean background) { if (!(surface instanceof Surface) && !(surface instanceof SurfaceTexture)) { throw new IllegalStateException("Input must be either a Surface or SurfaceTexture"); } checkIsNotReleased(); if (background) { if (eglSurfaceBackground != EGL14.EGL_NO_SURFACE) { throw new RuntimeException("Already has an EGLSurface"); } int[] surfaceAttribs = {EGL14.EGL_NONE}; eglSurfaceBackground = EGL14.eglCreateWindowSurface(eglDisplay, eglConfig, surface, surfaceAttribs, 0); if (eglSurfaceBackground == EGL14.EGL_NO_SURFACE) { throw new RuntimeException( "Failed to create window surface: 0x" + Integer.toHexString(EGL14.eglGetError())); } } else { if (eglSurface != EGL14.EGL_NO_SURFACE) { throw new RuntimeException("Already has an EGLSurface"); } int[] surfaceAttribs = {EGL14.EGL_NONE}; eglSurface = EGL14.eglCreateWindowSurface(eglDisplay, eglConfig, surface, surfaceAttribs, 0); if (eglSurface == EGL14.EGL_NO_SURFACE) { throw new RuntimeException( "Failed to create window surface: 0x" + Integer.toHexString(EGL14.eglGetError())); } } } @Override public void createDummyPbufferSurface() { createPbufferSurface(1, 1); } @Override public void createPbufferSurface(int width, int height) { checkIsNotReleased(); if (eglSurface != EGL14.EGL_NO_SURFACE) { throw new RuntimeException("Already has an EGLSurface"); } int[] surfaceAttribs = {EGL14.EGL_WIDTH, width, EGL14.EGL_HEIGHT, height, EGL14.EGL_NONE}; eglSurface = EGL14.eglCreatePbufferSurface(eglDisplay, eglConfig, surfaceAttribs, 0); if (eglSurface == EGL14.EGL_NO_SURFACE) { throw new RuntimeException("Failed to create pixel buffer surface with size " + width + "x" + height + ": 0x" + Integer.toHexString(EGL14.eglGetError())); } } @Override public Context getEglBaseContext() { return new Context(eglContext); } @Override public boolean hasSurface() { return eglSurface != EGL14.EGL_NO_SURFACE; } @Override public int surfaceWidth() { final int widthArray[] = new int[1]; EGL14.eglQuerySurface(eglDisplay, eglSurface, EGL14.EGL_WIDTH, widthArray, 0); return widthArray[0]; } @Override public int surfaceHeight() { final int heightArray[] = new int[1]; EGL14.eglQuerySurface(eglDisplay, eglSurface, EGL14.EGL_HEIGHT, heightArray, 0); return heightArray[0]; } @Override public void releaseSurface(boolean background) { if (background) { if (eglSurfaceBackground != EGL14.EGL_NO_SURFACE) { EGL14.eglDestroySurface(eglDisplay, eglSurfaceBackground); eglSurfaceBackground = EGL14.EGL_NO_SURFACE; } } else { if (eglSurface != EGL14.EGL_NO_SURFACE) { EGL14.eglDestroySurface(eglDisplay, eglSurface); eglSurface = EGL14.EGL_NO_SURFACE; } } } private void checkIsNotReleased() { if (eglDisplay == EGL14.EGL_NO_DISPLAY || eglContext == EGL14.EGL_NO_CONTEXT || eglConfig == null) { throw new RuntimeException("This object has been released"); } } @Override public void release() { checkIsNotReleased(); releaseSurface(false); releaseSurface(true); detachCurrent(); synchronized (EglBase.lock) { EGL14.eglDestroyContext(eglDisplay, eglContext); } EGL14.eglReleaseThread(); EGL14.eglTerminate(eglDisplay); eglContext = EGL14.EGL_NO_CONTEXT; eglDisplay = EGL14.EGL_NO_DISPLAY; eglConfig = null; } @Override public void makeCurrent() { checkIsNotReleased(); if (eglSurface == EGL14.EGL_NO_SURFACE) { throw new RuntimeException("No EGLSurface - can't make current"); } synchronized (EglBase.lock) { if (!EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) { throw new RuntimeException( "eglMakeCurrent failed: 0x" + Integer.toHexString(EGL14.eglGetError())); } } } @Override public void makeBackgroundCurrent() { checkIsNotReleased(); if (eglSurfaceBackground == EGL14.EGL_NO_SURFACE) { throw new RuntimeException("No EGLSurface - can't make current"); } synchronized (EglBase.lock) { if (!EGL14.eglMakeCurrent(eglDisplay, eglSurfaceBackground, eglSurfaceBackground, eglContext)) { throw new RuntimeException( "eglMakeCurrent failed: 0x" + Integer.toHexString(EGL14.eglGetError())); } } } @Override public boolean hasBackgroundSurface() { return eglSurfaceBackground != EGL14.EGL_NO_SURFACE; } // Detach the current EGL context, so that it can be made current on another thread. @Override public void detachCurrent() { synchronized (EglBase.lock) { if (!EGL14.eglMakeCurrent( eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT)) { throw new RuntimeException( "eglDetachCurrent failed: 0x" + Integer.toHexString(EGL14.eglGetError())); } } } @Override public void swapBuffers(boolean background) { checkIsNotReleased(); EGLSurface surface = background ? eglSurfaceBackground : eglSurface; if (surface == EGL14.EGL_NO_SURFACE) { throw new RuntimeException("No EGLSurface - can't swap buffers"); } synchronized (EglBase.lock) { EGL14.eglSwapBuffers(eglDisplay, surface); } } @Override public void swapBuffers(long timeStampNs, boolean background) { checkIsNotReleased(); EGLSurface surface = background ? eglSurfaceBackground : eglSurface; if (surface == EGL14.EGL_NO_SURFACE) { throw new RuntimeException("No EGLSurface - can't swap buffers"); } synchronized (EglBase.lock) { // See // https://android.googlesource.com/platform/frameworks/native/+/tools_r22.2/opengl/specs/EGL_ANDROID_presentation_time.txt EGLExt.eglPresentationTimeANDROID(eglDisplay, surface, timeStampNs); EGL14.eglSwapBuffers(eglDisplay, surface); } } // Return an EGLDisplay, or die trying. private static EGLDisplay getEglDisplay() { EGLDisplay eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY); if (eglDisplay == EGL14.EGL_NO_DISPLAY) { throw new RuntimeException( "Unable to get EGL14 display: 0x" + Integer.toHexString(EGL14.eglGetError())); } int[] version = new int[2]; if (!EGL14.eglInitialize(eglDisplay, version, 0, version, 1)) { throw new RuntimeException( "Unable to initialize EGL14: 0x" + Integer.toHexString(EGL14.eglGetError())); } return eglDisplay; } // Return an EGLConfig, or die trying. private static EGLConfig getEglConfig(EGLDisplay eglDisplay, int[] configAttributes) { EGLConfig[] configs = new EGLConfig[1]; int[] numConfigs = new int[1]; if (!EGL14.eglChooseConfig( eglDisplay, configAttributes, 0, configs, 0, configs.length, numConfigs, 0)) { throw new RuntimeException( "eglChooseConfig failed: 0x" + Integer.toHexString(EGL14.eglGetError())); } if (numConfigs[0] <= 0) { throw new RuntimeException("Unable to find any matching EGL config"); } final EGLConfig eglConfig = configs[0]; if (eglConfig == null) { throw new RuntimeException("eglChooseConfig returned null"); } return eglConfig; } // Return an EGLConfig, or die trying. private static EGLContext createEglContext(@Nullable EGLContext sharedContext, EGLDisplay eglDisplay, EGLConfig eglConfig, int openGlesVersion) { if (sharedContext != null && sharedContext == EGL14.EGL_NO_CONTEXT) { throw new RuntimeException("Invalid sharedContext"); } int[] contextAttributes = {EGL14.EGL_CONTEXT_CLIENT_VERSION, openGlesVersion, EGL14.EGL_NONE}; EGLContext rootContext = sharedContext == null ? EGL14.EGL_NO_CONTEXT : sharedContext; final EGLContext eglContext; synchronized (EglBase.lock) { eglContext = EGL14.eglCreateContext(eglDisplay, eglConfig, rootContext, contextAttributes, 0); } if (eglContext == EGL14.EGL_NO_CONTEXT) { throw new RuntimeException( "Failed to create EGL context: 0x" + Integer.toHexString(EGL14.eglGetError())); } return eglContext; } }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/org/webrtc/EglBase14Impl.java
2,168
package mindustry.async; import arc.math.*; import arc.math.geom.*; import arc.math.geom.QuadTree.*; import arc.struct.*; import mindustry.*; import mindustry.async.PhysicsProcess.PhysicsWorld.*; import mindustry.entities.*; import mindustry.gen.*; public class PhysicsProcess implements AsyncProcess{ public static final int layers = 3, layerGround = 0, layerLegs = 1, layerFlying = 2; private PhysicsWorld physics; private Seq<PhysicRef> refs = new Seq<>(false); //currently only enabled for units private EntityGroup<Unit> group = Groups.unit; @Override public void begin(){ if(physics == null) return; boolean local = !Vars.net.client(); //remove stale entities refs.removeAll(ref -> { if(!ref.entity.isAdded()){ physics.remove(ref.body); ref.entity.physref(null); return true; } return false; }); //find Units without bodies and assign them for(Unit entity : group){ if(entity == null || entity.type == null || !entity.type.physics) continue; if(entity.physref == null){ PhysicsBody body = new PhysicsBody(); body.x = entity.x; body.y = entity.y; body.mass = entity.mass(); body.radius = entity.hitSize / 2f; PhysicRef ref = new PhysicRef(entity, body); refs.add(ref); entity.physref = ref; physics.add(body); } //save last position PhysicRef ref = entity.physref; ref.body.layer = entity.collisionLayer(); ref.x = entity.x; ref.y = entity.y; ref.body.local = local || entity.isLocal(); } } @Override public void process(){ if(physics == null) return; //get last position vectors before step for(PhysicRef ref : refs){ //force set target position ref.body.x = ref.x; ref.body.y = ref.y; } physics.update(); } @Override public void end(){ if(physics == null) return; //move entities for(PhysicRef ref : refs){ Physicsc entity = ref.entity; //move by delta entity.move(ref.body.x - ref.x, ref.body.y - ref.y); } } @Override public void reset(){ if(physics != null){ refs.clear(); physics = null; } } @Override public void init(){ reset(); physics = new PhysicsWorld(Vars.world.getQuadBounds(new Rect())); } public static class PhysicRef{ public Physicsc entity; public PhysicsBody body; public float x, y; public PhysicRef(Physicsc entity, PhysicsBody body){ this.entity = entity; this.body = body; } } //world for simulating physics in a different thread public static class PhysicsWorld{ //how much to soften movement by private static final float scl = 1.25f; private final QuadTree<PhysicsBody>[] trees = new QuadTree[layers]; private final Seq<PhysicsBody> bodies = new Seq<>(false, 16, PhysicsBody.class); private final Seq<PhysicsBody> seq = new Seq<>(PhysicsBody.class); private final Rect rect = new Rect(); private final Vec2 vec = new Vec2(); public PhysicsWorld(Rect bounds){ for(int i = 0; i < layers; i++){ trees[i] = new QuadTree<>(new Rect(bounds)); } } public void add(PhysicsBody body){ bodies.add(body); } public void remove(PhysicsBody body){ bodies.remove(body); } public void update(){ for(int i = 0; i < layers; i++){ trees[i].clear(); } var bodyItems = bodies.items; int bodySize = bodies.size; for(int i = 0; i < bodySize; i++){ PhysicsBody body = bodyItems[i]; body.collided = false; trees[body.layer].insert(body); } for(int i = 0; i < bodySize; i++){ PhysicsBody body = bodyItems[i]; //for clients, the only body that collides is the local one; all other physics simulations are handled by the server. if(!body.local) continue; body.hitbox(rect); seq.size = 0; trees[body.layer].intersect(rect, seq); int size = seq.size; var items = seq.items; for(int j = 0; j < size; j++){ PhysicsBody other = items[j]; if(other == body || other.collided) continue; float rs = body.radius + other.radius; float dst = Mathf.dst(body.x, body.y, other.x, other.y); if(dst < rs){ vec.set(body.x - other.x, body.y - other.y).setLength(rs - dst); float ms = body.mass + other.mass; float m1 = other.mass / ms, m2 = body.mass / ms; //first body is always local due to guard check above body.x += vec.x * m1 / scl; body.y += vec.y * m1 / scl; if(other.local){ other.x -= vec.x * m2 / scl; other.y -= vec.y * m2 / scl; } } } body.collided = true; } } public static class PhysicsBody implements QuadTreeObject{ public float x, y, radius, mass; public int layer = 0; public boolean collided = false, local = true; @Override public void hitbox(Rect out){ out.setCentered(x, y, radius * 2, radius * 2); } } } }
Anuken/Mindustry
core/src/mindustry/async/PhysicsProcess.java
2,169
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2012-15 The Processing Foundation Copyright (c) 2006-12 Ben Fry and Casey Reas Copyright (c) 2004-06 Michael Chang This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.core; import static java.awt.Font.BOLD; import static java.awt.Font.ITALIC; import static java.awt.Font.PLAIN; import processing.data.*; // TODO replace these with PMatrix2D import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.util.Map; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This class is not part of the Processing API and should not be used * directly. Instead, use loadShape() and methods like it, which will make * use of this class. Using this class directly will cause your code to break * when combined with future versions of Processing. * <p> * SVG stands for Scalable Vector Graphics, a portable graphics format. * It is a vector format so it allows for "infinite" resolution and relatively * small file sizes. Most modern media software can view SVG files, including * Adobe products, Firefox, etc. Illustrator and Inkscape can edit SVG files. * View the SVG specification <A HREF="http://www.w3.org/TR/SVG">here</A>. * <p> * We have no intention of turning this into a full-featured SVG library. * The goal of this project is a basic shape importer that originally was small * enough to be included with applets, meaning that its download size should be * in the neighborhood of 25-30 Kb. Though we're far less limited nowadays on * size constraints, we remain extremely limited in terms of time, and do not * have volunteers who are available to maintain a larger SVG library. * <p> * For more sophisticated import/export, consider the * <A HREF="http://xmlgraphics.apache.org/batik/">Batik</A> * library from the Apache Software Foundation. * <p> * Batik is used in the SVG Export library in Processing 3, however using it * for full SVG import is still a considerable amount of work. Wiring it to * Java2D wouldn't be too bad, but using it with OpenGL, JavaFX, and features * like begin/endRecord() and begin/endRaw() would be considerable effort. * <p> * Future improvements to this library may focus on this properly supporting * a specific subset of SVG, for instance the simpler SVG profiles known as * <A HREF="http://www.w3.org/TR/SVGMobile/">SVG Tiny or Basic</A>, * although we still would not support the interactivity options. * * <p> <hr noshade> <p> * * A minimal example program using SVG: * (assuming a working moo.svg is in your data folder) * * <PRE> * PShape moo; * * void setup() { * size(400, 400); * moo = loadShape("moo.svg"); * } * void draw() { * background(255); * shape(moo, mouseX, mouseY); * } * </PRE> */ public class PShapeSVG extends PShape { XML element; /// Values between 0 and 1. protected float opacity; float strokeOpacity; float fillOpacity; /** Width of containing SVG (used for percentages). */ protected float svgWidth; /** Height of containing SVG (used for percentages). */ protected float svgHeight; /** √((w² + h²)/2) of containing SVG (used for percentages). */ protected float svgSizeXY; protected Gradient strokeGradient; String strokeName; // id of another object, gradients only? protected Gradient fillGradient; String fillName; // id of another object /** * Initializes a new SVG object from the given XML object. */ public PShapeSVG(XML svg) { this(null, svg, true); if (!svg.getName().equals("svg")) { if (svg.getName().toLowerCase().equals("html")) { // Common case is that files aren't downloaded properly throw new RuntimeException("This appears to be a web page, not an SVG file."); } else { throw new RuntimeException("The root node is not <svg>, it's <" + svg.getName() + ">"); } } } protected PShapeSVG(PShapeSVG parent, XML properties, boolean parseKids) { setParent(parent); // Need to get width/height in early. if (properties.getName().equals("svg")) { String unitWidth = properties.getString("width"); String unitHeight = properties.getString("height"); // Can't handle width/height as percentages easily. I'm just going // to put in 100 as a dummy value, beacuse this means that it will // come out as a reasonable value. if (unitWidth != null) width = parseUnitSize(unitWidth, 100); if (unitHeight != null) height = parseUnitSize(unitHeight, 100); String viewBoxStr = properties.getString("viewBox"); if (viewBoxStr != null) { float[] viewBox = PApplet.parseFloat(PApplet.splitTokens(viewBoxStr)); if (unitWidth == null || unitHeight == null) { // Not proper parsing of the viewBox, but will cover us for cases where // the width and height of the object is not specified. width = viewBox[2]; height = viewBox[3]; } else { // http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute // TODO: preserveAspectRatio. if (matrix == null) matrix = new PMatrix2D(); matrix.scale(width/viewBox[2], height/viewBox[3]); matrix.translate(-viewBox[0], -viewBox[1]); } } // Negative size is illegal. if (width < 0 || height < 0) throw new RuntimeException("<svg>: width (" + width + ") and height (" + height + ") must not be negative."); // It's technically valid to have width or height == 0. Not specified at // all is what to test for. if ((unitWidth == null || unitHeight == null) && viewBoxStr == null) { //throw new RuntimeException("width/height not specified"); PGraphics.showWarning("The width and/or height is not " + "readable in the <svg> tag of this file."); // For the spec, the default is 100% and 100%. For purposes // here, insert a dummy value because this is prolly just a // font or something for which the w/h doesn't matter. width = 1; height = 1; } svgWidth = width; svgHeight = height; svgSizeXY = PApplet.sqrt((svgWidth*svgWidth + svgHeight*svgHeight)/2.0f); } element = properties; name = properties.getString("id"); // @#$(* adobe illustrator mangles names of objects when re-saving if (name != null) { while (true) { String[] m = PApplet.match(name, "_x([A-Za-z0-9]{2})_"); if (m == null) break; char repair = (char) PApplet.unhex(m[1]); name = name.replace(m[0], "" + repair); } } String displayStr = properties.getString("display", "inline"); visible = !displayStr.equals("none"); String transformStr = properties.getString("transform"); if (transformStr != null) { if (matrix == null) { matrix = parseTransform(transformStr); } else { matrix.preApply(parseTransform(transformStr)); } } if (parseKids) { parseColors(properties); parseChildren(properties); } } // Broken out so that subclasses can copy any additional variables // (i.e. fillGradientPaint and strokeGradientPaint) protected void setParent(PShapeSVG parent) { // Need to set this so that findChild() works. // Otherwise 'parent' is null until addChild() is called later. this.parent = parent; if (parent == null) { // set values to their defaults according to the SVG spec stroke = false; strokeColor = 0xff000000; strokeWeight = 1; strokeCap = PConstants.SQUARE; // equivalent to BUTT in svg spec strokeJoin = PConstants.MITER; strokeGradient = null; // strokeGradientPaint = null; strokeName = null; fill = true; fillColor = 0xff000000; fillGradient = null; // fillGradientPaint = null; fillName = null; //hasTransform = false; //transformation = null; //new float[] { 1, 0, 0, 1, 0, 0 }; // svgWidth, svgHeight, and svgXYSize done below. strokeOpacity = 1; fillOpacity = 1; opacity = 1; } else { stroke = parent.stroke; strokeColor = parent.strokeColor; strokeWeight = parent.strokeWeight; strokeCap = parent.strokeCap; strokeJoin = parent.strokeJoin; strokeGradient = parent.strokeGradient; // strokeGradientPaint = parent.strokeGradientPaint; strokeName = parent.strokeName; fill = parent.fill; fillColor = parent.fillColor; fillGradient = parent.fillGradient; // fillGradientPaint = parent.fillGradientPaint; fillName = parent.fillName; svgWidth = parent.svgWidth; svgHeight = parent.svgHeight; svgSizeXY = parent.svgSizeXY; opacity = parent.opacity; } // The rect and ellipse modes are set to CORNER since it is the expected // mode for svg shapes. rectMode = CORNER; ellipseMode = CORNER; } /** Factory method for subclasses. */ protected PShapeSVG createShape(PShapeSVG parent, XML properties, boolean parseKids) { return new PShapeSVG(parent, properties, parseKids); } protected void parseChildren(XML graphics) { XML[] elements = graphics.getChildren(); children = new PShape[elements.length]; childCount = 0; for (XML elem : elements) { PShape kid = parseChild(elem); if (kid != null) addChild(kid); } children = (PShape[]) PApplet.subset(children, 0, childCount); } /** * Parse a child XML element. * Override this method to add parsing for more SVG elements. */ protected PShape parseChild(XML elem) { // System.err.println("parsing child in pshape " + elem.getName()); String name = elem.getName(); PShapeSVG shape = null; if (name == null) { // just some whitespace that can be ignored (hopefully) } else if (name.equals("g")) { shape = createShape(this, elem, true); } else if (name.equals("defs")) { // generally this will contain gradient info, so may // as well just throw it into a group element for parsing shape = createShape(this, elem, true); } else if (name.equals("line")) { shape = createShape(this, elem, true); shape.parseLine(); } else if (name.equals("circle")) { shape = createShape(this, elem, true); shape.parseEllipse(true); } else if (name.equals("ellipse")) { shape = createShape(this, elem, true); shape.parseEllipse(false); } else if (name.equals("rect")) { shape = createShape(this, elem, true); shape.parseRect(); } else if (name.equals("image")) { shape = createShape(this, elem, true); shape.parseImage(); } else if (name.equals("polygon")) { shape = createShape(this, elem, true); shape.parsePoly(true); } else if (name.equals("polyline")) { shape = createShape(this, elem, true); shape.parsePoly(false); } else if (name.equals("path")) { shape = createShape(this, elem, true); shape.parsePath(); } else if (name.equals("radialGradient")) { return new RadialGradient(this, elem); } else if (name.equals("linearGradient")) { return new LinearGradient(this, elem); } else if (name.equals("font")) { return new Font(this, elem); // } else if (name.equals("font-face")) { // return new FontFace(this, elem); // } else if (name.equals("glyph") || name.equals("missing-glyph")) { // return new FontGlyph(this, elem); } else if (name.equals("text")) { // || name.equals("font")) { return new Text(this, elem); } else if (name.equals("tspan")) { return new LineOfText(this, elem); } else if (name.equals("filter")) { PGraphics.showWarning("Filters are not supported."); } else if (name.equals("mask")) { PGraphics.showWarning("Masks are not supported."); } else if (name.equals("pattern")) { PGraphics.showWarning("Patterns are not supported."); } else if (name.equals("stop")) { // stop tag is handled by gradient parser, so don't warn about it } else if (name.equals("sodipodi:namedview")) { // these are always in Inkscape files, the warnings get tedious } else if (name.equals("metadata") || name.equals("title") || name.equals("desc")) { // fontforge just stuffs <metadata> in as a comment. // All harmless stuff, irrelevant to rendering. return null; } else if (!name.startsWith("#")) { PGraphics.showWarning("Ignoring <" + name + "> tag."); // new Exception().printStackTrace(); } return shape; } protected void parseLine() { kind = LINE; family = PRIMITIVE; params = new float[] { getFloatWithUnit(element, "x1", svgWidth), getFloatWithUnit(element, "y1", svgHeight), getFloatWithUnit(element, "x2", svgWidth), getFloatWithUnit(element, "y2", svgHeight) }; } /** * Handles parsing ellipse and circle tags. * @param circle true if this is a circle and not an ellipse */ protected void parseEllipse(boolean circle) { kind = ELLIPSE; family = PRIMITIVE; params = new float[4]; params[0] = getFloatWithUnit(element, "cx", svgWidth); params[1] = getFloatWithUnit(element, "cy", svgHeight); float rx, ry; if (circle) { rx = ry = getFloatWithUnit(element, "r", svgSizeXY); } else { rx = getFloatWithUnit(element, "rx", svgWidth); ry = getFloatWithUnit(element, "ry", svgHeight); } params[0] -= rx; params[1] -= ry; params[2] = rx*2; params[3] = ry*2; } protected void parseRect() { kind = RECT; family = PRIMITIVE; params = new float[] { getFloatWithUnit(element, "x", svgWidth), getFloatWithUnit(element, "y", svgHeight), getFloatWithUnit(element, "width", svgWidth), getFloatWithUnit(element, "height", svgHeight) }; } protected void parseImage() { kind = RECT; textureMode = NORMAL; family = PRIMITIVE; params = new float[] { getFloatWithUnit(element, "x", svgWidth), getFloatWithUnit(element, "y", svgHeight), getFloatWithUnit(element, "width", svgWidth), getFloatWithUnit(element, "height", svgHeight) }; this.imagePath = element.getString("xlink:href"); } /** * Parse a polyline or polygon from an SVG file. * Syntax defined at http://www.w3.org/TR/SVG/shapes.html#PointsBNF * @param close true if shape is closed (polygon), false if not (polyline) */ protected void parsePoly(boolean close) { family = PATH; this.close = close; String pointsAttr = element.getString("points"); if (pointsAttr != null) { Pattern pattern = Pattern.compile("([+-]?[\\d]+(\\.[\\d]+)?([eE][+-][\\d]+)?)(,?\\s*)([+-]?[\\d]+(\\.[\\d]+)?([eE][+-][\\d]+)?)"); Matcher matcher = pattern.matcher(pointsAttr); vertexCount = 0; while (matcher.find()) { vertexCount++; } matcher.reset(); vertices = new float[vertexCount][2]; for (int i = 0; i < vertexCount; i++) { matcher.find(); vertices[i][X] = Float.parseFloat(matcher.group(1)); vertices[i][Y] = Float.parseFloat(matcher.group(5)); } // String[] pointsBuffer = PApplet.splitTokens(pointsAttr); // vertexCount = pointsBuffer.length; // vertices = new float[vertexCount][2]; // for (int i = 0; i < vertexCount; i++) { // String pb[] = PApplet.splitTokens(pointsBuffer[i], ", \t\r\n"); // vertices[i][X] = Float.parseFloat(pb[0]); // vertices[i][Y] = Float.parseFloat(pb[1]); // } } } protected void parsePath() { family = PATH; kind = 0; String pathData = element.getString("d"); if (pathData == null || PApplet.trim(pathData).length() == 0) { return; } char[] pathDataChars = pathData.toCharArray(); StringBuilder pathBuffer = new StringBuilder(); boolean lastSeparate = false; for (int i = 0; i < pathDataChars.length; i++) { char c = pathDataChars[i]; boolean separate = false; if (c == 'M' || c == 'm' || c == 'L' || c == 'l' || c == 'H' || c == 'h' || c == 'V' || c == 'v' || c == 'C' || c == 'c' || // beziers c == 'S' || c == 's' || c == 'Q' || c == 'q' || // quadratic beziers c == 'T' || c == 't' || c == 'A' || c == 'a' || // elliptical arc c == 'Z' || c == 'z' || // closepath c == ',') { separate = true; if (i != 0) { pathBuffer.append("|"); } } if (c == 'Z' || c == 'z') { separate = false; } if (c == '-' && !lastSeparate) { // allow for 'e' notation in numbers, e.g. 2.10e-9 // http://dev.processing.org/bugs/show_bug.cgi?id=1408 if (i == 0 || pathDataChars[i-1] != 'e') { pathBuffer.append("|"); } } if (c != ',') { pathBuffer.append(c); //"" + pathDataBuffer.charAt(i)); } if (separate && c != ',' && c != '-') { pathBuffer.append("|"); } lastSeparate = separate; } // use whitespace constant to get rid of extra spaces and CR or LF String[] pathTokens = PApplet.splitTokens(pathBuffer.toString(), "|" + WHITESPACE); vertices = new float[pathTokens.length][2]; vertexCodes = new int[pathTokens.length]; float cx = 0; float cy = 0; int i = 0; char implicitCommand = '\0'; // char prevCommand = '\0'; boolean prevCurve = false; float ctrlX, ctrlY; // store values for closepath so that relative coords work properly float movetoX = 0; float movetoY = 0; while (i < pathTokens.length) { char c = pathTokens[i].charAt(0); if (((c >= '0' && c <= '9') || (c == '-')) && implicitCommand != '\0') { c = implicitCommand; i--; } else { implicitCommand = c; } switch (c) { case 'M': // M - move to (absolute) cx = PApplet.parseFloat(pathTokens[i + 1]); cy = PApplet.parseFloat(pathTokens[i + 2]); movetoX = cx; movetoY = cy; parsePathMoveto(cx, cy); implicitCommand = 'L'; i += 3; break; case 'm': // m - move to (relative) cx = cx + PApplet.parseFloat(pathTokens[i + 1]); cy = cy + PApplet.parseFloat(pathTokens[i + 2]); movetoX = cx; movetoY = cy; parsePathMoveto(cx, cy); implicitCommand = 'l'; i += 3; break; case 'L': cx = PApplet.parseFloat(pathTokens[i + 1]); cy = PApplet.parseFloat(pathTokens[i + 2]); parsePathLineto(cx, cy); i += 3; break; case 'l': cx = cx + PApplet.parseFloat(pathTokens[i + 1]); cy = cy + PApplet.parseFloat(pathTokens[i + 2]); parsePathLineto(cx, cy); i += 3; break; // horizontal lineto absolute case 'H': cx = PApplet.parseFloat(pathTokens[i + 1]); parsePathLineto(cx, cy); i += 2; break; // horizontal lineto relative case 'h': cx = cx + PApplet.parseFloat(pathTokens[i + 1]); parsePathLineto(cx, cy); i += 2; break; case 'V': cy = PApplet.parseFloat(pathTokens[i + 1]); parsePathLineto(cx, cy); i += 2; break; case 'v': cy = cy + PApplet.parseFloat(pathTokens[i + 1]); parsePathLineto(cx, cy); i += 2; break; // C - curve to (absolute) case 'C': { float ctrlX1 = PApplet.parseFloat(pathTokens[i + 1]); float ctrlY1 = PApplet.parseFloat(pathTokens[i + 2]); float ctrlX2 = PApplet.parseFloat(pathTokens[i + 3]); float ctrlY2 = PApplet.parseFloat(pathTokens[i + 4]); float endX = PApplet.parseFloat(pathTokens[i + 5]); float endY = PApplet.parseFloat(pathTokens[i + 6]); parsePathCurveto(ctrlX1, ctrlY1, ctrlX2, ctrlY2, endX, endY); cx = endX; cy = endY; i += 7; prevCurve = true; } break; // c - curve to (relative) case 'c': { float ctrlX1 = cx + PApplet.parseFloat(pathTokens[i + 1]); float ctrlY1 = cy + PApplet.parseFloat(pathTokens[i + 2]); float ctrlX2 = cx + PApplet.parseFloat(pathTokens[i + 3]); float ctrlY2 = cy + PApplet.parseFloat(pathTokens[i + 4]); float endX = cx + PApplet.parseFloat(pathTokens[i + 5]); float endY = cy + PApplet.parseFloat(pathTokens[i + 6]); parsePathCurveto(ctrlX1, ctrlY1, ctrlX2, ctrlY2, endX, endY); cx = endX; cy = endY; i += 7; prevCurve = true; } break; // S - curve to shorthand (absolute) // Draws a cubic Bézier curve from the current point to (x,y). The first // control point is assumed to be the reflection of the second control // point on the previous command relative to the current point. // (x2,y2) is the second control point (i.e., the control point // at the end of the curve). S (uppercase) indicates that absolute // coordinates will follow; s (lowercase) indicates that relative // coordinates will follow. Multiple sets of coordinates may be specified // to draw a polybézier. At the end of the command, the new current point // becomes the final (x,y) coordinate pair used in the polybézier. case 'S': { // (If there is no previous command or if the previous command was not // an C, c, S or s, assume the first control point is coincident with // the current point.) if (!prevCurve) { ctrlX = cx; ctrlY = cy; } else { float ppx = vertices[vertexCount-2][X]; float ppy = vertices[vertexCount-2][Y]; float px = vertices[vertexCount-1][X]; float py = vertices[vertexCount-1][Y]; ctrlX = px + (px - ppx); ctrlY = py + (py - ppy); } float ctrlX2 = PApplet.parseFloat(pathTokens[i + 1]); float ctrlY2 = PApplet.parseFloat(pathTokens[i + 2]); float endX = PApplet.parseFloat(pathTokens[i + 3]); float endY = PApplet.parseFloat(pathTokens[i + 4]); parsePathCurveto(ctrlX, ctrlY, ctrlX2, ctrlY2, endX, endY); cx = endX; cy = endY; i += 5; prevCurve = true; } break; // s - curve to shorthand (relative) case 's': { if (!prevCurve) { ctrlX = cx; ctrlY = cy; } else { float ppx = vertices[vertexCount-2][X]; float ppy = vertices[vertexCount-2][Y]; float px = vertices[vertexCount-1][X]; float py = vertices[vertexCount-1][Y]; ctrlX = px + (px - ppx); ctrlY = py + (py - ppy); } float ctrlX2 = cx + PApplet.parseFloat(pathTokens[i + 1]); float ctrlY2 = cy + PApplet.parseFloat(pathTokens[i + 2]); float endX = cx + PApplet.parseFloat(pathTokens[i + 3]); float endY = cy + PApplet.parseFloat(pathTokens[i + 4]); parsePathCurveto(ctrlX, ctrlY, ctrlX2, ctrlY2, endX, endY); cx = endX; cy = endY; i += 5; prevCurve = true; } break; // Q - quadratic curve to (absolute) // Draws a quadratic Bézier curve from the current point to (x,y) using // (x1,y1) as the control point. Q (uppercase) indicates that absolute // coordinates will follow; q (lowercase) indicates that relative // coordinates will follow. Multiple sets of coordinates may be specified // to draw a polybézier. At the end of the command, the new current point // becomes the final (x,y) coordinate pair used in the polybézier. case 'Q': { ctrlX = PApplet.parseFloat(pathTokens[i + 1]); ctrlY = PApplet.parseFloat(pathTokens[i + 2]); float endX = PApplet.parseFloat(pathTokens[i + 3]); float endY = PApplet.parseFloat(pathTokens[i + 4]); //parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); parsePathQuadto(ctrlX, ctrlY, endX, endY); cx = endX; cy = endY; i += 5; prevCurve = true; } break; // q - quadratic curve to (relative) case 'q': { ctrlX = cx + PApplet.parseFloat(pathTokens[i + 1]); ctrlY = cy + PApplet.parseFloat(pathTokens[i + 2]); float endX = cx + PApplet.parseFloat(pathTokens[i + 3]); float endY = cy + PApplet.parseFloat(pathTokens[i + 4]); //parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); parsePathQuadto(ctrlX, ctrlY, endX, endY); cx = endX; cy = endY; i += 5; prevCurve = true; } break; // T - quadratic curveto shorthand (absolute) // The control point is assumed to be the reflection of the control // point on the previous command relative to the current point. case 'T': { // If there is no previous command or if the previous command was // not a Q, q, T or t, assume the control point is coincident // with the current point. if (!prevCurve) { ctrlX = cx; ctrlY = cy; } else { float ppx = vertices[vertexCount-2][X]; float ppy = vertices[vertexCount-2][Y]; float px = vertices[vertexCount-1][X]; float py = vertices[vertexCount-1][Y]; ctrlX = px + (px - ppx); ctrlY = py + (py - ppy); } float endX = PApplet.parseFloat(pathTokens[i + 1]); float endY = PApplet.parseFloat(pathTokens[i + 2]); //parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); parsePathQuadto(ctrlX, ctrlY, endX, endY); cx = endX; cy = endY; i += 3; prevCurve = true; } break; // t - quadratic curveto shorthand (relative) case 't': { if (!prevCurve) { ctrlX = cx; ctrlY = cy; } else { float ppx = vertices[vertexCount-2][X]; float ppy = vertices[vertexCount-2][Y]; float px = vertices[vertexCount-1][X]; float py = vertices[vertexCount-1][Y]; ctrlX = px + (px - ppx); ctrlY = py + (py - ppy); } float endX = cx + PApplet.parseFloat(pathTokens[i + 1]); float endY = cy + PApplet.parseFloat(pathTokens[i + 2]); //parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); parsePathQuadto(ctrlX, ctrlY, endX, endY); cx = endX; cy = endY; i += 3; prevCurve = true; } break; // A - elliptical arc to (absolute) case 'A': { float rx = PApplet.parseFloat(pathTokens[i + 1]); float ry = PApplet.parseFloat(pathTokens[i + 2]); float angle = PApplet.parseFloat(pathTokens[i + 3]); boolean fa = PApplet.parseFloat(pathTokens[i + 4]) != 0; boolean fs = PApplet.parseFloat(pathTokens[i + 5]) != 0; float endX = PApplet.parseFloat(pathTokens[i + 6]); float endY = PApplet.parseFloat(pathTokens[i + 7]); parsePathArcto(cx, cy, rx, ry, angle, fa, fs, endX, endY); cx = endX; cy = endY; i += 8; prevCurve = true; } break; // a - elliptical arc to (relative) case 'a': { float rx = PApplet.parseFloat(pathTokens[i + 1]); float ry = PApplet.parseFloat(pathTokens[i + 2]); float angle = PApplet.parseFloat(pathTokens[i + 3]); boolean fa = PApplet.parseFloat(pathTokens[i + 4]) != 0; boolean fs = PApplet.parseFloat(pathTokens[i + 5]) != 0; float endX = cx + PApplet.parseFloat(pathTokens[i + 6]); float endY = cy + PApplet.parseFloat(pathTokens[i + 7]); parsePathArcto(cx, cy, rx, ry, angle, fa, fs, endX, endY); cx = endX; cy = endY; i += 8; prevCurve = true; } break; case 'Z': case 'z': // since closing the path, the 'current' point needs // to return back to the last moveto location. // http://code.google.com/p/processing/issues/detail?id=1058 cx = movetoX; cy = movetoY; close = true; i++; break; default: String parsed = PApplet.join(PApplet.subset(pathTokens, 0, i), ","); String unparsed = PApplet.join(PApplet.subset(pathTokens, i), ","); System.err.println("parsed: " + parsed); System.err.println("unparsed: " + unparsed); throw new RuntimeException("shape command not handled: " + pathTokens[i]); } // prevCommand = c; } } // private void parsePathCheck(int num) { // if (vertexCount + num-1 >= vertices.length) { // //vertices = (float[][]) PApplet.expand(vertices); // float[][] temp = new float[vertexCount << 1][2]; // System.arraycopy(vertices, 0, temp, 0, vertexCount); // vertices = temp; // } // } private void parsePathVertex(float x, float y) { if (vertexCount == vertices.length) { //vertices = (float[][]) PApplet.expand(vertices); float[][] temp = new float[vertexCount << 1][2]; System.arraycopy(vertices, 0, temp, 0, vertexCount); vertices = temp; } vertices[vertexCount][X] = x; vertices[vertexCount][Y] = y; vertexCount++; } private void parsePathCode(int what) { if (vertexCodeCount == vertexCodes.length) { vertexCodes = PApplet.expand(vertexCodes); } vertexCodes[vertexCodeCount++] = what; } private void parsePathMoveto(float px, float py) { if (vertexCount > 0) { parsePathCode(BREAK); } parsePathCode(VERTEX); parsePathVertex(px, py); } private void parsePathLineto(float px, float py) { parsePathCode(VERTEX); parsePathVertex(px, py); } private void parsePathCurveto(float x1, float y1, float x2, float y2, float x3, float y3) { parsePathCode(BEZIER_VERTEX); parsePathVertex(x1, y1); parsePathVertex(x2, y2); parsePathVertex(x3, y3); } // private void parsePathQuadto(float x1, float y1, // float cx, float cy, // float x2, float y2) { // //System.out.println("quadto: " + x1 + "," + y1 + " " + cx + "," + cy + " " + x2 + "," + y2); //// parsePathCode(BEZIER_VERTEX); // parsePathCode(QUAD_BEZIER_VERTEX); // // x1/y1 already covered by last moveto, lineto, or curveto // // parsePathVertex(x1 + ((cx-x1)*2/3.0f), y1 + ((cy-y1)*2/3.0f)); // parsePathVertex(x2 + ((cx-x2)*2/3.0f), y2 + ((cy-y2)*2/3.0f)); // parsePathVertex(x2, y2); // } private void parsePathQuadto(float cx, float cy, float x2, float y2) { //System.out.println("quadto: " + x1 + "," + y1 + " " + cx + "," + cy + " " + x2 + "," + y2); // parsePathCode(BEZIER_VERTEX); parsePathCode(QUADRATIC_VERTEX); // x1/y1 already covered by last moveto, lineto, or curveto parsePathVertex(cx, cy); parsePathVertex(x2, y2); } // Approximates elliptical arc by several bezier segments. // Meets SVG standard requirements from: // http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands // http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes // Based on arc to bezier curve equations from: // http://www.spaceroots.org/documents/ellipse/node22.html private void parsePathArcto(float x1, float y1, float rx, float ry, float angle, boolean fa, boolean fs, float x2, float y2) { if (x1 == x2 && y1 == y2) return; if (rx == 0 || ry == 0) { parsePathLineto(x2, y2); return; } rx = PApplet.abs(rx); ry = PApplet.abs(ry); float phi = PApplet.radians(((angle % 360) + 360) % 360); float cosPhi = PApplet.cos(phi), sinPhi = PApplet.sin(phi); float x1r = ( cosPhi * (x1 - x2) + sinPhi * (y1 - y2)) / 2; float y1r = (-sinPhi * (x1 - x2) + cosPhi * (y1 - y2)) / 2; float cxr, cyr; { float A = (x1r*x1r) / (rx*rx) + (y1r*y1r) / (ry*ry); if (A > 1) { // No solution, scale ellipse up according to SVG standard float sqrtA = PApplet.sqrt(A); rx *= sqrtA; cxr = 0; ry *= sqrtA; cyr = 0; } else { float k = ((fa == fs) ? -1f : 1f) * PApplet.sqrt((rx*rx * ry*ry) / ((rx*rx * y1r*y1r) + (ry*ry * x1r*x1r)) - 1f); cxr = k * rx * y1r / ry; cyr = -k * ry * x1r / rx; } } float cx = cosPhi * cxr - sinPhi * cyr + (x1 + x2) / 2; float cy = sinPhi * cxr + cosPhi * cyr + (y1 + y2) / 2; float phi1, phiDelta; { float sx = ( x1r - cxr) / rx, sy = ( y1r - cyr) / ry; float tx = (-x1r - cxr) / rx, ty = (-y1r - cyr) / ry; phi1 = PApplet.atan2(sy, sx); phiDelta = (((PApplet.atan2(ty, tx) - phi1) % TWO_PI) + TWO_PI) % TWO_PI; if (!fs) phiDelta -= TWO_PI; } // One segment can not cover more that PI, less than PI/2 is // recommended to avoid visible inaccuracies caused by rounding errors int segmentCount = PApplet.ceil(PApplet.abs(phiDelta) / TWO_PI * 4); float inc = phiDelta / segmentCount; float a = PApplet.sin(inc) * (PApplet.sqrt(4 + 3 * PApplet.sq(PApplet.tan(inc / 2))) - 1) / 3; float sinPhi1 = PApplet.sin(phi1), cosPhi1 = PApplet.cos(phi1); float p1x = x1; float p1y = y1; float relq1x = a * (-rx * cosPhi * sinPhi1 - ry * sinPhi * cosPhi1); float relq1y = a * (-rx * sinPhi * sinPhi1 + ry * cosPhi * cosPhi1); for (int i = 0; i < segmentCount; i++) { float eta = phi1 + (i + 1) * inc; float sinEta = PApplet.sin(eta), cosEta = PApplet.cos(eta); float p2x = cx + rx * cosPhi * cosEta - ry * sinPhi * sinEta; float p2y = cy + rx * sinPhi * cosEta + ry * cosPhi * sinEta; float relq2x = a * (-rx * cosPhi * sinEta - ry * sinPhi * cosEta); float relq2y = a * (-rx * sinPhi * sinEta + ry * cosPhi * cosEta); if (i == segmentCount - 1) { p2x = x2; p2y = y2; } parsePathCode(BEZIER_VERTEX); parsePathVertex(p1x + relq1x, p1y + relq1y); parsePathVertex(p2x - relq2x, p2y - relq2y); parsePathVertex(p2x, p2y); p1x = p2x; relq1x = relq2x; p1y = p2y; relq1y = relq2y; } } /** * Parse the specified SVG matrix into a PMatrix2D. Note that PMatrix2D * is rotated relative to the SVG definition, so parameters are rearranged * here. More about the transformation matrices in * <a href="http://www.w3.org/TR/SVG/coords.html#TransformAttribute">this section</a> * of the SVG documentation. * @param matrixStr text of the matrix param. * @return a good old-fashioned PMatrix2D */ static protected PMatrix2D parseTransform(String matrixStr) { matrixStr = matrixStr.trim(); PMatrix2D outgoing = null; int start = 0; int stop = -1; while ((stop = matrixStr.indexOf(')', start)) != -1) { PMatrix2D m = parseSingleTransform(matrixStr.substring(start, stop+1)); if (outgoing == null) { outgoing = m; } else { outgoing.apply(m); } start = stop + 1; } return outgoing; } static protected PMatrix2D parseSingleTransform(String matrixStr) { //String[] pieces = PApplet.match(matrixStr, "^\\s*(\\w+)\\((.*)\\)\\s*$"); String[] pieces = PApplet.match(matrixStr, "[,\\s]*(\\w+)\\((.*)\\)"); if (pieces == null) { System.err.println("Could not parse transform " + matrixStr); return null; } float[] m = PApplet.parseFloat(PApplet.splitTokens(pieces[2], ", ")); if (pieces[1].equals("matrix")) { return new PMatrix2D(m[0], m[2], m[4], m[1], m[3], m[5]); } else if (pieces[1].equals("translate")) { float tx = m[0]; float ty = (m.length == 2) ? m[1] : m[0]; return new PMatrix2D(1, 0, tx, 0, 1, ty); } else if (pieces[1].equals("scale")) { float sx = m[0]; float sy = (m.length == 2) ? m[1] : m[0]; return new PMatrix2D(sx, 0, 0, 0, sy, 0); } else if (pieces[1].equals("rotate")) { float angle = m[0]; if (m.length == 1) { float c = PApplet.cos(angle); float s = PApplet.sin(angle); // SVG version is cos(a) sin(a) -sin(a) cos(a) 0 0 return new PMatrix2D(c, -s, 0, s, c, 0); } else if (m.length == 3) { PMatrix2D mat = new PMatrix2D(0, 1, m[1], 1, 0, m[2]); mat.rotate(m[0]); mat.translate(-m[1], -m[2]); return mat; } } else if (pieces[1].equals("skewX")) { return new PMatrix2D(1, 0, 1, PApplet.tan(m[0]), 0, 0); } else if (pieces[1].equals("skewY")) { return new PMatrix2D(1, 0, 1, 0, PApplet.tan(m[0]), 0); } return null; } protected void parseColors(XML properties) { if (properties.hasAttribute("opacity")) { String opacityText = properties.getString("opacity"); setOpacity(opacityText); } if (properties.hasAttribute("stroke")) { String strokeText = properties.getString("stroke"); setColor(strokeText, false); } if (properties.hasAttribute("stroke-opacity")) { String strokeOpacityText = properties.getString("stroke-opacity"); setStrokeOpacity(strokeOpacityText); } if (properties.hasAttribute("stroke-width")) { // if NaN (i.e. if it's 'inherit') then default back to the inherit setting String lineweight = properties.getString("stroke-width"); setStrokeWeight(lineweight); } if (properties.hasAttribute("stroke-linejoin")) { String linejoin = properties.getString("stroke-linejoin"); setStrokeJoin(linejoin); } if (properties.hasAttribute("stroke-linecap")) { String linecap = properties.getString("stroke-linecap"); setStrokeCap(linecap); } // fill defaults to black (though stroke defaults to "none") // http://www.w3.org/TR/SVG/painting.html#FillProperties if (properties.hasAttribute("fill")) { String fillText = properties.getString("fill"); setColor(fillText, true); } if (properties.hasAttribute("fill-opacity")) { String fillOpacityText = properties.getString("fill-opacity"); setFillOpacity(fillOpacityText); } if (properties.hasAttribute("style")) { String styleText = properties.getString("style"); String[] styleTokens = PApplet.splitTokens(styleText, ";"); //PApplet.println(styleTokens); for (int i = 0; i < styleTokens.length; i++) { String[] tokens = PApplet.splitTokens(styleTokens[i], ":"); //PApplet.println(tokens); tokens[0] = PApplet.trim(tokens[0]); if (tokens[0].equals("fill")) { setColor(tokens[1], true); } else if(tokens[0].equals("fill-opacity")) { setFillOpacity(tokens[1]); } else if(tokens[0].equals("stroke")) { setColor(tokens[1], false); } else if(tokens[0].equals("stroke-width")) { setStrokeWeight(tokens[1]); } else if(tokens[0].equals("stroke-linecap")) { setStrokeCap(tokens[1]); } else if(tokens[0].equals("stroke-linejoin")) { setStrokeJoin(tokens[1]); } else if(tokens[0].equals("stroke-opacity")) { setStrokeOpacity(tokens[1]); } else if(tokens[0].equals("opacity")) { setOpacity(tokens[1]); } else { // Other attributes are not yet implemented } } } } void setOpacity(String opacityText) { opacity = PApplet.parseFloat(opacityText); strokeColor = ((int) (opacity * 255)) << 24 | strokeColor & 0xFFFFFF; fillColor = ((int) (opacity * 255)) << 24 | fillColor & 0xFFFFFF; } void setStrokeWeight(String lineweight) { strokeWeight = parseUnitSize(lineweight, svgSizeXY); } void setStrokeOpacity(String opacityText) { strokeOpacity = PApplet.parseFloat(opacityText); strokeColor = ((int) (strokeOpacity * 255)) << 24 | strokeColor & 0xFFFFFF; } void setStrokeJoin(String linejoin) { if (linejoin.equals("inherit")) { // do nothing, will inherit automatically } else if (linejoin.equals("miter")) { strokeJoin = PConstants.MITER; } else if (linejoin.equals("round")) { strokeJoin = PConstants.ROUND; } else if (linejoin.equals("bevel")) { strokeJoin = PConstants.BEVEL; } } void setStrokeCap(String linecap) { if (linecap.equals("inherit")) { // do nothing, will inherit automatically } else if (linecap.equals("butt")) { strokeCap = PConstants.SQUARE; } else if (linecap.equals("round")) { strokeCap = PConstants.ROUND; } else if (linecap.equals("square")) { strokeCap = PConstants.PROJECT; } } void setFillOpacity(String opacityText) { fillOpacity = PApplet.parseFloat(opacityText); fillColor = ((int) (fillOpacity * 255)) << 24 | fillColor & 0xFFFFFF; } void setColor(String colorText, boolean isFill) { colorText = colorText.trim(); int opacityMask = fillColor & 0xFF000000; boolean visible = true; int color = 0; String name = ""; // String lColorText = colorText.toLowerCase(); Gradient gradient = null; // Object paint = null; if (colorText.equals("none")) { visible = false; } else if (colorText.startsWith("url(#")) { name = colorText.substring(5, colorText.length() - 1); Object object = findChild(name); if (object instanceof Gradient) { gradient = (Gradient) object; // in 3.0a11, do this on first draw inside PShapeJava2D // paint = calcGradientPaint(gradient); //, opacity); } else { // visible = false; System.err.println("url " + name + " refers to unexpected data: " + object); } } else { // Prints errors itself. color = opacityMask | parseSimpleColor(colorText); } if (isFill) { fill = visible; fillColor = color; fillName = name; fillGradient = gradient; // fillGradientPaint = paint; } else { stroke = visible; strokeColor = color; strokeName = name; strokeGradient = gradient; // strokeGradientPaint = paint; } } /** * Parses the "color" datatype only, and prints an error if it is not of this form. * http://www.w3.org/TR/SVG/types.html#DataTypeColor * @return 0xRRGGBB (no alpha). Zero on error. */ static protected int parseSimpleColor(String colorText) { colorText = colorText.toLowerCase().trim(); //if (colorNames.containsKey(colorText)) { if (colorNames.hasKey(colorText)) { return colorNames.get(colorText); } else if (colorText.startsWith("#")) { if (colorText.length() == 4) { // Short form: #ABC, transform to long form #AABBCC colorText = colorText.replaceAll("^#(.)(.)(.)$", "#$1$1$2$2$3$3"); } return (Integer.parseInt(colorText.substring(1), 16)) & 0xFFFFFF; //System.out.println("hex for fill is " + PApplet.hex(fillColor)); } else if (colorText.startsWith("rgb")) { return parseRGB(colorText); } else { System.err.println("Cannot parse \"" + colorText + "\"."); return 0; } } /** * Deliberately conforms to the HTML 4.01 color spec + en-gb grey, rather * than the (unlikely to be useful) entire 147-color system used in SVG. */ static protected IntDict colorNames = new IntDict(new Object[][] { { "aqua", 0x00ffff }, { "black", 0x000000 }, { "blue", 0x0000ff }, { "fuchsia", 0xff00ff }, { "gray", 0x808080 }, { "grey", 0x808080 }, { "green", 0x008000 }, { "lime", 0x00ff00 }, { "maroon", 0x800000 }, { "navy", 0x000080 }, { "olive", 0x808000 }, { "purple", 0x800080 }, { "red", 0xff0000 }, { "silver", 0xc0c0c0 }, { "teal", 0x008080 }, { "white", 0xffffff }, { "yellow", 0xffff00 } }); /* static protected Map<String, Integer> colorNames; static { colorNames = new HashMap<String, Integer>(); colorNames.put("aqua", 0x00ffff); colorNames.put("black", 0x000000); colorNames.put("blue", 0x0000ff); colorNames.put("fuchsia", 0xff00ff); colorNames.put("gray", 0x808080); colorNames.put("grey", 0x808080); colorNames.put("green", 0x008000); colorNames.put("lime", 0x00ff00); colorNames.put("maroon", 0x800000); colorNames.put("navy", 0x000080); colorNames.put("olive", 0x808000); colorNames.put("purple", 0x800080); colorNames.put("red", 0xff0000); colorNames.put("silver", 0xc0c0c0); colorNames.put("teal", 0x008080); colorNames.put("white", 0xffffff); colorNames.put("yellow", 0xffff00); } */ static protected int parseRGB(String what) { int leftParen = what.indexOf('(') + 1; int rightParen = what.indexOf(')'); String sub = what.substring(leftParen, rightParen); String[] values = PApplet.splitTokens(sub, ", "); int rgbValue = 0; if (values.length == 3) { // Color spec allows for rgb values to be percentages. for (int i = 0; i < 3; i++) { rgbValue <<= 8; if (values[i].endsWith("%")) { rgbValue |= (int)(PApplet.constrain(255*parseFloatOrPercent(values[i]), 0, 255)); } else { rgbValue |= PApplet.constrain(PApplet.parseInt(values[i]), 0, 255); } } } else System.err.println("Could not read color \"" + what + "\"."); return rgbValue; } //static protected Map<String, String> parseStyleAttributes(String style) { static protected StringDict parseStyleAttributes(String style) { //Map<String, String> table = new HashMap<String, String>(); StringDict table = new StringDict(); // if (style == null) return table; if (style != null) { String[] pieces = style.split(";"); for (int i = 0; i < pieces.length; i++) { String[] parts = pieces[i].split(":"); //table.put(parts[0], parts[1]); table.set(parts[0], parts[1]); } } return table; } /** * Used in place of element.getFloatAttribute(a) because we can * have a unit suffix (length or coordinate). * @param element what to parse * @param attribute name of the attribute to get * @param relativeTo (float) Used for %. When relative to viewbox, should * be svgWidth for horizontal dimentions, svgHeight for vertical, and * svgXYSize for anything else. * @return unit-parsed version of the data */ static protected float getFloatWithUnit(XML element, String attribute, float relativeTo) { String val = element.getString(attribute); return (val == null) ? 0 : parseUnitSize(val, relativeTo); } /** * Parse a size that may have a suffix for its units. * This assumes 90dpi, which implies, as given in the * <A HREF="http://www.w3.org/TR/SVG/coords.html#Units">units</A> spec: * <UL> * <LI>"1pt" equals "1.25px" (and therefore 1.25 user units) * <LI>"1pc" equals "15px" (and therefore 15 user units) * <LI>"1mm" would be "3.543307px" (3.543307 user units) * <LI>"1cm" equals "35.43307px" (and therefore 35.43307 user units) * <LI>"1in" equals "90px" (and therefore 90 user units) * </UL> * @param relativeTo (float) Used for %. When relative to viewbox, should * be svgWidth for horizontal dimentions, svgHeight for vertical, and * svgXYSize for anything else. */ static protected float parseUnitSize(String text, float relativeTo) { int len = text.length() - 2; if (text.endsWith("pt")) { return PApplet.parseFloat(text.substring(0, len)) * 1.25f; } else if (text.endsWith("pc")) { return PApplet.parseFloat(text.substring(0, len)) * 15; } else if (text.endsWith("mm")) { return PApplet.parseFloat(text.substring(0, len)) * 3.543307f; } else if (text.endsWith("cm")) { return PApplet.parseFloat(text.substring(0, len)) * 35.43307f; } else if (text.endsWith("in")) { return PApplet.parseFloat(text.substring(0, len)) * 90; } else if (text.endsWith("px")) { return PApplet.parseFloat(text.substring(0, len)); } else if (text.endsWith("%")) { return relativeTo * parseFloatOrPercent(text); } else { return PApplet.parseFloat(text); } } static protected float parseFloatOrPercent(String text) { text = text.trim(); if (text.endsWith("%")) { return Float.parseFloat(text.substring(0, text.length() - 1)) / 100.0f; } else { return Float.parseFloat(text); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static public class Gradient extends PShapeSVG { AffineTransform transform; public float[] offset; public int[] color; public int count; public Gradient(PShapeSVG parent, XML properties) { super(parent, properties, true); XML[] elements = properties.getChildren(); offset = new float[elements.length]; color = new int[elements.length]; // <stop offset="0" style="stop-color:#967348"/> for (int i = 0; i < elements.length; i++) { XML elem = elements[i]; String name = elem.getName(); if (name.equals("stop")) { String offsetAttr = elem.getString("offset"); offset[count] = parseFloatOrPercent(offsetAttr); String style = elem.getString("style"); //Map<String, String> styles = parseStyleAttributes(style); StringDict styles = parseStyleAttributes(style); String colorStr = styles.get("stop-color"); if (colorStr == null) { colorStr = elem.getString("stop-color"); if (colorStr == null) colorStr = "#000000"; } String opacityStr = styles.get("stop-opacity"); if (opacityStr == null) { opacityStr = elem.getString("stop-opacity"); if (opacityStr == null) opacityStr = "1"; } int tupacity = PApplet.constrain( (int)(PApplet.parseFloat(opacityStr) * 255), 0, 255); color[count] = (tupacity << 24) | parseSimpleColor(colorStr); count++; } } offset = PApplet.subset(offset, 0, count); color = PApplet.subset(color, 0, count); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static public class LinearGradient extends Gradient { public float x1, y1, x2, y2; public LinearGradient(PShapeSVG parent, XML properties) { super(parent, properties); this.x1 = getFloatWithUnit(properties, "x1", svgWidth); this.y1 = getFloatWithUnit(properties, "y1", svgHeight); this.x2 = getFloatWithUnit(properties, "x2", svgWidth); this.y2 = getFloatWithUnit(properties, "y2", svgHeight); String transformStr = properties.getString("gradientTransform"); if (transformStr != null) { float[] t = parseTransform(transformStr).get(null); this.transform = new AffineTransform(t[0], t[3], t[1], t[4], t[2], t[5]); Point2D t1 = transform.transform(new Point2D.Float(x1, y1), null); Point2D t2 = transform.transform(new Point2D.Float(x2, y2), null); this.x1 = (float) t1.getX(); this.y1 = (float) t1.getY(); this.x2 = (float) t2.getX(); this.y2 = (float) t2.getY(); } } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static public class RadialGradient extends Gradient { public float cx, cy, r; public RadialGradient(PShapeSVG parent, XML properties) { super(parent, properties); this.cx = getFloatWithUnit(properties, "cx", svgWidth); this.cy = getFloatWithUnit(properties, "cy", svgHeight); this.r = getFloatWithUnit(properties, "r", svgSizeXY); String transformStr = properties.getString("gradientTransform"); if (transformStr != null) { float[] t = parseTransform(transformStr).get(null); this.transform = new AffineTransform(t[0], t[3], t[1], t[4], t[2], t[5]); Point2D t1 = transform.transform(new Point2D.Float(cx, cy), null); Point2D t2 = transform.transform(new Point2D.Float(cx + r, cy), null); this.cx = (float) t1.getX(); this.cy = (float) t1.getY(); this.r = (float) (t2.getX() - t1.getX()); } } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // static private float TEXT_QUALITY = 1; static private PFont parseFont(XML properties) { String fontFamily = null; float size = 10; int weight = PLAIN; // 0 int italic = 0; if (properties.hasAttribute("style")) { String styleText = properties.getString("style"); String[] styleTokens = PApplet.splitTokens(styleText, ";"); //PApplet.println(styleTokens); for (int i = 0; i < styleTokens.length; i++) { String[] tokens = PApplet.splitTokens(styleTokens[i], ":"); //PApplet.println(tokens); tokens[0] = PApplet.trim(tokens[0]); if (tokens[0].equals("font-style")) { // PApplet.println("font-style: " + tokens[1]); if (tokens[1].contains("italic")) { italic = ITALIC; } } else if (tokens[0].equals("font-variant")) { // PApplet.println("font-variant: " + tokens[1]); // setFillOpacity(tokens[1]); } else if (tokens[0].equals("font-weight")) { // PApplet.println("font-weight: " + tokens[1]); if (tokens[1].contains("bold")) { weight = BOLD; // PApplet.println("Bold weight ! "); } } else if (tokens[0].equals("font-stretch")) { // not supported. } else if (tokens[0].equals("font-size")) { // PApplet.println("font-size: " + tokens[1]); size = Float.parseFloat(tokens[1].split("px")[0]); // PApplet.println("font-size-parsed: " + size); } else if (tokens[0].equals("line-height")) { // not supported } else if (tokens[0].equals("font-family")) { // PApplet.println("Font-family: " + tokens[1]); fontFamily = tokens[1]; } else if (tokens[0].equals("text-align")) { // not supported } else if (tokens[0].equals("letter-spacing")) { // not supported } else if (tokens[0].equals("word-spacing")) { // not supported } else if (tokens[0].equals("writing-mode")) { // not supported } else if (tokens[0].equals("text-anchor")) { // not supported } else { // Other attributes are not yet implemented } } } if (fontFamily == null) { return null; } // size = size * TEXT_QUALITY; return createFont(fontFamily, weight | italic, size, true); } static protected PFont createFont(String name, int weight, float size, boolean smooth) { //System.out.println("Try to create a font of " + name + " family, " + weight); java.awt.Font baseFont = new java.awt.Font(name, weight, (int) size); //System.out.println("Resulting family : " + baseFont.getFamily() + " " + baseFont.getStyle()); return new PFont(baseFont.deriveFont(size), smooth, null); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static public class Text extends PShapeSVG { protected PFont font; public Text(PShapeSVG parent, XML properties) { super(parent, properties, true); // get location float x = Float.parseFloat(properties.getString("x")); float y = Float.parseFloat(properties.getString("y")); if (matrix == null) { matrix = new PMatrix2D(); } matrix.translate(x, y); family = GROUP; font = parseFont(properties); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static public class LineOfText extends PShapeSVG { String textToDisplay; PFont font; public LineOfText(PShapeSVG parent, XML properties) { // TODO: child should ideally be parsed too for inline content. super(parent, properties, false); //get location float x = Float.parseFloat(properties.getString("x")); float y = Float.parseFloat(properties.getString("y")); float parentX = Float.parseFloat(parent.element.getString("x")); float parentY = Float.parseFloat(parent.element.getString("y")); if (matrix == null) matrix = new PMatrix2D(); matrix.translate(x - parentX, (y - parentY) / 2f); // get the first properties parseColors(properties); font = parseFont(properties); // cleaned up syntax but removing b/c unused [fry 190118] //boolean isLine = properties.getString("role").equals("line"); if (this.childCount > 0) { // no inline content yet. } String text = properties.getContent(); textToDisplay = text; } @Override public void drawImpl(PGraphics g) { if (font == null) { font = ((Text) parent).font; if (font == null) { return; } } pre(g); // g.textFont(font, font.size / TEXT_QUALITY); g.textFont(font, font.size); g.text(textToDisplay, 0, 0); post(g); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static public class Font extends PShapeSVG { public FontFace face; public Map<String, FontGlyph> namedGlyphs; public Map<Character, FontGlyph> unicodeGlyphs; public int glyphCount; public FontGlyph[] glyphs; public FontGlyph missingGlyph; int horizAdvX; public Font(PShapeSVG parent, XML properties) { super(parent, properties, false); // handle(parent, properties); XML[] elements = properties.getChildren(); horizAdvX = properties.getInt("horiz-adv-x", 0); namedGlyphs = new HashMap<>(); unicodeGlyphs = new HashMap<>(); glyphCount = 0; glyphs = new FontGlyph[elements.length]; for (int i = 0; i < elements.length; i++) { String name = elements[i].getName(); XML elem = elements[i]; if (name == null) { // skip it } else if (name.equals("glyph")) { FontGlyph fg = new FontGlyph(this, elem, this); if (fg.isLegit()) { if (fg.name != null) { namedGlyphs.put(fg.name, fg); } if (fg.unicode != 0) { unicodeGlyphs.put(Character.valueOf(fg.unicode), fg); } } glyphs[glyphCount++] = fg; } else if (name.equals("missing-glyph")) { // System.out.println("got missing glyph inside <font>"); missingGlyph = new FontGlyph(this, elem, this); } else if (name.equals("font-face")) { face = new FontFace(this, elem); } else { System.err.println("Ignoring " + name + " inside <font>"); } } } protected void drawShape() { // does nothing for fonts } public void drawString(PGraphics g, String str, float x, float y, float size) { // 1) scale by the 1.0/unitsPerEm // 2) scale up by a font size g.pushMatrix(); float s = size / face.unitsPerEm; //System.out.println("scale is " + s); // swap y coord at the same time, since fonts have y=0 at baseline g.translate(x, y); g.scale(s, -s); char[] c = str.toCharArray(); for (int i = 0; i < c.length; i++) { // call draw on each char (pulling it w/ the unicode table) FontGlyph fg = unicodeGlyphs.get(Character.valueOf(c[i])); if (fg != null) { fg.draw(g); // add horizAdvX/unitsPerEm to the x coordinate along the way g.translate(fg.horizAdvX, 0); } else { System.err.println("'" + c[i] + "' not available."); } } g.popMatrix(); } public void drawChar(PGraphics g, char c, float x, float y, float size) { g.pushMatrix(); float s = size / face.unitsPerEm; g.translate(x, y); g.scale(s, -s); FontGlyph fg = unicodeGlyphs.get(Character.valueOf(c)); if (fg != null) g.shape(fg); g.popMatrix(); } public float textWidth(String str, float size) { float w = 0; char[] c = str.toCharArray(); for (int i = 0; i < c.length; i++) { // call draw on each char (pulling it w/ the unicode table) FontGlyph fg = unicodeGlyphs.get(Character.valueOf(c[i])); if (fg != null) { w += (float) fg.horizAdvX / face.unitsPerEm; } } return w * size; } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static class FontFace extends PShapeSVG { int horizOriginX; // dflt 0 int horizOriginY; // dflt 0 // int horizAdvX; // no dflt? int vertOriginX; // dflt horizAdvX/2 int vertOriginY; // dflt ascent int vertAdvY; // dflt 1em (unitsPerEm value) String fontFamily; int fontWeight; // can also be normal or bold (also comma separated) String fontStretch; int unitsPerEm; // dflt 1000 int[] panose1; // dflt "0 0 0 0 0 0 0 0 0 0" int ascent; int descent; int[] bbox; // spec says comma separated, tho not w/ forge int underlineThickness; int underlinePosition; //String unicodeRange; // gonna ignore for now public FontFace(PShapeSVG parent, XML properties) { super(parent, properties, true); unitsPerEm = properties.getInt("units-per-em", 1000); } protected void drawShape() { // nothing to draw in the font face attribute } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static public class FontGlyph extends PShapeSVG { // extends Path public String name; char unicode; int horizAdvX; public FontGlyph(PShapeSVG parent, XML properties, Font font) { super(parent, properties, true); super.parsePath(); // ?? name = properties.getString("glyph-name"); String u = properties.getString("unicode"); unicode = 0; if (u != null) { if (u.length() == 1) { unicode = u.charAt(0); //System.out.println("unicode for " + name + " is " + u); } else { System.err.println("unicode for " + name + " is more than one char: " + u); } } if (properties.hasAttribute("horiz-adv-x")) { horizAdvX = properties.getInt("horiz-adv-x"); } else { horizAdvX = font.horizAdvX; } } protected boolean isLegit() { // TODO need a better way to handle this... return vertexCount != 0; } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Get a particular element based on its SVG ID. When editing SVG by hand, * this is the id="" tag on any SVG element. When editing from Illustrator, * these IDs can be edited by expanding the layers palette. The names used * in the layers palette, both for the layers or the shapes and groups * beneath them can be used here. * <PRE> * // This code grabs "Layer 3" and the shapes beneath it. * PShape layer3 = svg.getChild("Layer 3"); * </PRE> */ @Override public PShape getChild(String name) { PShape found = super.getChild(name); if (found == null) { // Otherwise try with underscores instead of spaces // (this is how Illustrator handles spaces in the layer names). found = super.getChild(name.replace(' ', '_')); } // Set bounding box based on the parent bounding box if (found != null) { // found.x = this.x; // found.y = this.y; found.width = this.width; found.height = this.height; } return found; } /** * Prints out the SVG document. Useful for parsing. */ public void print() { PApplet.println(element.toString()); } }
processing/processing
core/src/processing/core/PShapeSVG.java
2,170
/* * 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.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.SystemClock; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.util.Property; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.OvershootInterpolator; import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.Keep; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.DialogObject; import org.telegram.messenger.Emoji; import org.telegram.messenger.LocaleController; 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.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; 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.TextCell; import org.telegram.ui.ChatActivity; import org.telegram.ui.ProfileActivity; 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.Objects; public class PollVotesAlert extends BottomSheet { private RecyclerListView listView; private Adapter listAdapter; private Drawable shadowDrawable; private View actionBarShadow; private ActionBar actionBar; private AnimatorSet actionBarAnimation; private ChatActivity chatActivity; private MessageObject messageObject; private TLRPC.Poll poll; private TLRPC.InputPeer peer; private HashSet<VotesList> loadingMore = new HashSet<>(); private HashMap<VotesList, Button> votesPercents = new HashMap<>(); private ArrayList<VotesList> voters = new ArrayList<>(); private AnimatedEmojiSpan.TextViewEmojis titleTextView; private int scrollOffsetY; private int topBeforeSwitch; private ArrayList<Integer> queries = new ArrayList<>(); private Paint placeholderPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private LinearGradient placeholderGradient; private Matrix placeholderMatrix; private float totalTranslation; private float gradientWidth; private boolean loadingResults = true; private RectF rect = new RectF(); private static class VotesList { public int count; public ArrayList<TLRPC.MessagePeerVote> votes; public ArrayList<TLRPC.User> users; public String next_offset; public byte[] option; public boolean collapsed; public int collapsedCount = 10; public VotesList(TLRPC.TL_messages_votesList votesList, byte[] o) { count = votesList.count; votes = votesList.votes; users = votesList.users; next_offset = votesList.next_offset; option = o; } public int getCount() { if (collapsed) { return Math.min(collapsedCount, votes.size()); } return votes.size(); } public int getCollapsed() { if (votes.size() <= 15) { return 0; } else if (collapsed) { return 1; } else { return 2; } } } public class SectionCell extends FrameLayout { private AnimatedEmojiSpan.TextViewEmojis textView; private TextView middleTextView; private AnimatedTextView righTextView; public SectionCell(Context context) { super(context); setBackgroundColor(Theme.getColor(Theme.key_graySection)); textView = new AnimatedEmojiSpan.TextViewEmojis(getContext()); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextColor(Theme.getColor(Theme.key_graySectionText)); textView.setSingleLine(true); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); middleTextView = new TextView(getContext()); middleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); middleTextView.setTextColor(Theme.getColor(Theme.key_graySectionText)); middleTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); righTextView = new AnimatedTextView(getContext()) { @Override public boolean post(Runnable action) { return containerView.post(action); } @Override public boolean postDelayed(Runnable action, long delayMillis) { return containerView.postDelayed(action, delayMillis); } @Override public void invalidate() { super.invalidate(); if (SectionCell.this == listView.getPinnedHeader()) { listView.invalidate(); } } }; righTextView.setTextSize(AndroidUtilities.dp(14)); righTextView.setTextColor(Theme.getColor(Theme.key_graySectionText)); righTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT)); righTextView.setOnClickListener(v -> onCollapseClick()); addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 0 : 16), 0, (LocaleController.isRTL ? 16 : 0), 0)); addView(middleTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 0, 0, 0, 0)); addView(righTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP, 16, 0, 16, 0)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { heightMeasureSpec = MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(32), MeasureSpec.EXACTLY); measureChildWithMargins(middleTextView, widthMeasureSpec, 0, heightMeasureSpec, 0); measureChildWithMargins(righTextView, widthMeasureSpec, 0, heightMeasureSpec, 0); measureChildWithMargins(textView, widthMeasureSpec, middleTextView.getMeasuredWidth() + righTextView.getMeasuredWidth() + AndroidUtilities.dp(32), heightMeasureSpec, 0); setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), AndroidUtilities.dp(32)); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (LocaleController.isRTL) { int l = textView.getLeft() - middleTextView.getMeasuredWidth(); middleTextView.layout(l, middleTextView.getTop(), l + middleTextView.getMeasuredWidth(), middleTextView.getBottom()); } else { int l = textView.getRight(); middleTextView.layout(l, middleTextView.getTop(), l + middleTextView.getMeasuredWidth(), middleTextView.getBottom()); } } protected void onCollapseClick() { } public void setText(CharSequence left, ArrayList<TLRPC.MessageEntity> entities, int percent, int votesCount, int collapsed, boolean animated) { if (entities != null) { NotificationCenter.listenEmojiLoading(textView); CharSequence answerText = new SpannableStringBuilder(left); MediaDataController.addTextStyleRuns(entities, left, (Spannable) answerText); answerText = Emoji.replaceEmoji(answerText, textView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(14), false); MessageObject.replaceAnimatedEmoji(answerText, entities, textView.getPaint().getFontMetricsInt()); textView.setText(answerText); } else { textView.setText(Emoji.replaceEmoji(left, textView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(14), false)); } String p = String.format("%d", percent); SpannableStringBuilder builder; if (LocaleController.isRTL) { builder = new SpannableStringBuilder(String.format("%s%% – ", percent)); } else { builder = new SpannableStringBuilder(String.format(" – %s%%", percent)); } builder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 3, 3 + p.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); middleTextView.setText(builder); if (collapsed == 0) { if (poll.quiz) { righTextView.setText(LocaleController.formatPluralString("Answer", votesCount), animated); } else { righTextView.setText(LocaleController.formatPluralString("Vote", votesCount), animated); } } else if (collapsed == 1) { righTextView.setText(LocaleController.getString("PollExpand", R.string.PollExpand), animated); } else { righTextView.setText(LocaleController.getString("PollCollapse", R.string.PollCollapse), animated); } } } public static final Property<UserCell, Float> USER_CELL_PROPERTY = new AnimationProperties.FloatProperty<UserCell>("placeholderAlpha") { @Override public void setValue(UserCell object, float value) { object.setPlaceholderAlpha(value); } @Override public Float get(UserCell object) { return object.getPlaceholderAlpha(); } }; public class UserCell extends FrameLayout { private BackupImageView avatarImageView; private SimpleTextView nameTextView; private AvatarDrawable avatarDrawable; private StatusBadgeComponent statusBadgeComponent; private TLRPC.User currentUser; private TLRPC.Chat currentChat; private CharSequence lastName; private int lastStatus; private TLRPC.FileLocation lastAvatar; private int currentAccount = UserConfig.selectedAccount; private boolean needDivider; private int placeholderNum; private boolean drawPlaceholder; private float placeholderAlpha = 1.0f; private ArrayList<Animator> animators; public UserCell(Context context) { super(context); setWillNotDraw(false); avatarDrawable = new AvatarDrawable(); avatarImageView = new BackupImageView(context); avatarImageView.setRoundRadius(AndroidUtilities.dp(18)); addView(avatarImageView, LayoutHelper.createFrame(36, 36, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 0 : 14, 6, LocaleController.isRTL ? 14 : 0, 0)); nameTextView = new SimpleTextView(context); nameTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); nameTextView.setTextSize(16); nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 24, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 28 : 65, 12, LocaleController.isRTL ? 65 : 28, 0)); statusBadgeComponent = new StatusBadgeComponent(nameTextView, 20); } public void setData(TLObject object, int num, boolean divider) { if (object instanceof TLRPC.User) { currentUser = (TLRPC.User) object; currentChat = null; } else if (object instanceof TLRPC.Chat) { currentChat = (TLRPC.Chat) object; currentUser = null; } else { currentUser = null; currentChat = null; } needDivider = divider; drawPlaceholder = object == null; placeholderNum = num; if (object == null) { nameTextView.setText(""); avatarImageView.setImageDrawable(null); } else { update(0); } if (animators != null) { animators.add(ObjectAnimator.ofFloat(avatarImageView, View.ALPHA, 0.0f, 1.0f)); animators.add(ObjectAnimator.ofFloat(nameTextView, View.ALPHA, 0.0f, 1.0f)); animators.add(ObjectAnimator.ofFloat(this, USER_CELL_PROPERTY, 1.0f, 0.0f)); } else if (!drawPlaceholder) { placeholderAlpha = 0.0f; } } @Keep public void setPlaceholderAlpha(float value) { placeholderAlpha = value; invalidate(); } @Keep public float getPlaceholderAlpha() { return placeholderAlpha; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48) + (needDivider ? 1 : 0), MeasureSpec.EXACTLY)); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); statusBadgeComponent.onAttachedToWindow(); } @Override protected void onDetachedFromWindow() { statusBadgeComponent.onDetachedFromWindow(); super.onDetachedFromWindow(); } public void update(int mask) { TLRPC.FileLocation photo = null; String newName = null; if (currentUser != null && currentUser.photo != null) { photo = currentUser.photo.photo_small; } else if (currentChat != null && currentChat.photo != null) { photo = currentChat.photo.photo_small; } if (mask != 0) { boolean continueUpdate = false; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0) { if (lastAvatar != null && photo == null || lastAvatar == null && photo != null || lastAvatar != null && photo != null && (lastAvatar.volume_id != photo.volume_id || lastAvatar.local_id != photo.local_id)) { continueUpdate = true; } } if (currentUser != null && !continueUpdate && (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { int newStatus = 0; if (currentUser.status != null) { newStatus = currentUser.status.expires; } if (newStatus != lastStatus) { continueUpdate = true; } } if (!continueUpdate && lastName != null && (mask & MessagesController.UPDATE_MASK_NAME) != 0) { if (currentUser != null) { newName = UserObject.getUserName(currentUser); } else if (currentChat != null) { newName = currentChat.title; } if (!TextUtils.equals(newName, lastName)) { continueUpdate = true; } } if (!continueUpdate) { return; } } if (currentUser != null) { avatarDrawable.setInfo(currentAccount, currentUser); if (currentUser.status != null) { lastStatus = currentUser.status.expires; } else { lastStatus = 0; } } else if (currentChat != null) { avatarDrawable.setInfo(currentAccount, currentChat); } if (currentUser != null) { lastName = newName == null ? UserObject.getUserName(currentUser) : newName; lastName = Emoji.replaceEmoji(lastName, nameTextView.getPaint().getFontMetricsInt(), false); } else if (currentChat != null) { lastName = currentChat.title; lastName = Emoji.replaceEmoji(lastName, nameTextView.getPaint().getFontMetricsInt(), false); } else { lastName = ""; } nameTextView.setText(lastName); nameTextView.setRightDrawable(statusBadgeComponent.updateDrawable(currentUser, currentChat, Theme.getColor(Theme.key_chats_verifiedBackground, resourcesProvider), false)); lastAvatar = photo; if (currentChat != null) { avatarImageView.setForUserOrChat(currentChat, avatarDrawable); } else if (currentUser != null) { avatarImageView.setForUserOrChat(currentUser, avatarDrawable); } else { avatarImageView.setImageDrawable(avatarDrawable); } } @Override public boolean hasOverlappingRendering() { return false; } @Override protected void onDraw(Canvas canvas) { if (drawPlaceholder || placeholderAlpha != 0) { placeholderPaint.setAlpha((int) (255 * placeholderAlpha)); int cx = avatarImageView.getLeft() + avatarImageView.getMeasuredWidth() / 2; int cy = avatarImageView.getTop() + avatarImageView.getMeasuredHeight() / 2; canvas.drawCircle(cx, cy, avatarImageView.getMeasuredWidth() / 2, placeholderPaint); int w; if (placeholderNum % 2 == 0) { cx = AndroidUtilities.dp(65); w = AndroidUtilities.dp(48); } else { cx = AndroidUtilities.dp(65); w = AndroidUtilities.dp(60); } if (LocaleController.isRTL) { cx = getMeasuredWidth() - cx - w; } rect.set(cx, cy - AndroidUtilities.dp(4), cx + w, cy + AndroidUtilities.dp(4)); canvas.drawRoundRect(rect, AndroidUtilities.dp(4), AndroidUtilities.dp(4), placeholderPaint); if (placeholderNum % 2 == 0) { cx = AndroidUtilities.dp(119); w = AndroidUtilities.dp(60); } else { cx = AndroidUtilities.dp(131); w = AndroidUtilities.dp(80); } if (LocaleController.isRTL) { cx = getMeasuredWidth() - cx - w; } rect.set(cx, cy - AndroidUtilities.dp(4), cx + w, cy + AndroidUtilities.dp(4)); canvas.drawRoundRect(rect, AndroidUtilities.dp(4), AndroidUtilities.dp(4), placeholderPaint); } if (needDivider) { canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(64), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(64) : 0), getMeasuredHeight() - 1, Theme.dividerPaint); } } } public static void showForPoll(ChatActivity parentFragment, MessageObject messageObject) { if (parentFragment == null || parentFragment.getParentActivity() == null) { return; } PollVotesAlert alert = new PollVotesAlert(parentFragment, messageObject); parentFragment.showDialog(alert); } private static class Button { private float decimal; private int percent; private int votesCount; } public PollVotesAlert(ChatActivity parentFragment, MessageObject message) { super(parentFragment.getParentActivity(), true); fixNavigationBar(); messageObject = message; chatActivity = parentFragment; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) messageObject.messageOwner.media; poll = mediaPoll.poll; Context context = parentFragment.getParentActivity(); peer = parentFragment.getMessagesController().getInputPeer((int) message.getDialogId()); ArrayList<VotesList> loadedVoters = new ArrayList<>(); int count = mediaPoll.results.results.size(); Integer[] reqIds = new Integer[count]; for (int a = 0; a < count; a++) { TLRPC.TL_pollAnswerVoters answerVoters = mediaPoll.results.results.get(a); if (answerVoters.voters == 0) { continue; } TLRPC.TL_messages_votesList votesList = new TLRPC.TL_messages_votesList(); int N = answerVoters.voters <= 15 ? answerVoters.voters : 10; for (int b = 0; b < N; b++) { votesList.votes.add(new TLRPC.TL_messagePeerVoteInputOption()); } votesList.next_offset = N < answerVoters.voters ? "empty" : null; votesList.count = answerVoters.voters; VotesList list = new VotesList(votesList, answerVoters.option); voters.add(list); TLRPC.TL_messages_getPollVotes req = new TLRPC.TL_messages_getPollVotes(); req.peer = peer; req.id = messageObject.getId(); req.limit = answerVoters.voters <= 15 ? 15 : 10; req.flags |= 1; req.option = answerVoters.option; int num = a; reqIds[a] = parentFragment.getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { queries.remove(reqIds[num]); if (response != null) { TLRPC.TL_messages_votesList res = (TLRPC.TL_messages_votesList) response; parentFragment.getMessagesController().putUsers(res.users, false); if (!res.votes.isEmpty()) { loadedVoters.add(new VotesList(res, answerVoters.option)); } if (queries.isEmpty()) { boolean countChanged = false; for (int b = 0, N2 = loadedVoters.size(); b < N2; b++) { VotesList votesList1 = loadedVoters.get(b); for (int c = 0, N3 = voters.size(); c < N3; c++) { VotesList votesList2 = voters.get(c); if (Arrays.equals(votesList1.option, votesList2.option)) { votesList2.next_offset = votesList1.next_offset; if (votesList2.count != votesList1.count || votesList2.votes.size() != votesList1.votes.size()) { countChanged = true; } votesList2.count = votesList1.count; votesList2.users = votesList1.users; votesList2.votes = votesList1.votes; break; } } } loadingResults = false; if (listView != null) { if (currentSheetAnimationType != 0 || startAnimationRunnable != null || countChanged) { if (countChanged) { updateButtons(); } listAdapter.notifyDataSetChanged(); } else { int c = listView.getChildCount(); ArrayList<Animator> animators = new ArrayList<>(); for (int b = 0; b < c; b++) { View child = listView.getChildAt(b); if (!(child instanceof UserCell)) { continue; } RecyclerView.ViewHolder holder = listView.findContainingViewHolder(child); if (holder == null) { continue; } UserCell cell = (UserCell) child; cell.animators = animators; cell.setEnabled(true); listAdapter.onViewAttachedToWindow(holder); cell.animators = null; } if (!animators.isEmpty()) { AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(animators); animatorSet.setDuration(180); animatorSet.start(); } loadingResults = false; } } } } else { dismiss(); } })); queries.add(reqIds[a]); } updateButtons(); Collections.sort(voters, new Comparator<VotesList>() { private int getIndex(VotesList votesList) { for (int a = 0, N = poll.answers.size(); a < N; a++) { TLRPC.PollAnswer answer = poll.answers.get(a); if (Arrays.equals(answer.option, votesList.option)) { return a; } } return 0; } @Override public int compare(VotesList o1, VotesList o2) { int i1 = getIndex(o1); int i2 = getIndex(o2); if (i1 > i2) { return 1; } else if (i1 < i2) { return -1; } return 0; } }); updatePlaceholder(); shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); containerView = new FrameLayout(context) { private boolean ignoreLayout = false; private RectF rect = new RectF(); @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int totalHeight = MeasureSpec.getSize(heightMeasureSpec); if (Build.VERSION.SDK_INT >= 21 && !isFullscreen) { ignoreLayout = true; setPadding(backgroundPaddingLeft, AndroidUtilities.statusBarHeight, backgroundPaddingLeft, 0); ignoreLayout = false; } int availableHeight = totalHeight - getPaddingTop(); LayoutParams layoutParams = (LayoutParams) listView.getLayoutParams(); layoutParams.topMargin = ActionBar.getCurrentActionBarHeight(); layoutParams = (LayoutParams) actionBarShadow.getLayoutParams(); layoutParams.topMargin = ActionBar.getCurrentActionBarHeight(); int contentSize = backgroundPaddingTop + AndroidUtilities.dp(15) + AndroidUtilities.statusBarHeight; int sectionCount = listAdapter.getSectionCount(); for (int a = 0; a < sectionCount; a++) { if (a == 0) { titleTextView.measure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec - backgroundPaddingLeft * 2), MeasureSpec.EXACTLY), heightMeasureSpec); contentSize += titleTextView.getMeasuredHeight(); } else { int count = listAdapter.getCountForSection(a); contentSize += AndroidUtilities.dp(32) + AndroidUtilities.dp(50) * (count - 1); } } int padding = (contentSize < availableHeight ? availableHeight - contentSize : availableHeight - (availableHeight / 5 * 3)) + AndroidUtilities.dp(8); if (listView.getPaddingTop() != padding) { ignoreLayout = true; listView.setPinnedSectionOffsetY(-padding); listView.setPadding(0, padding, 0, 0); ignoreLayout = false; } super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(totalHeight, MeasureSpec.EXACTLY)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); updateLayout(false); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN && scrollOffsetY != 0 && ev.getY() < scrollOffsetY + AndroidUtilities.dp(12) && actionBar.getAlpha() == 0.0f) { dismiss(); return true; } return super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent e) { return !isDismissed() && super.onTouchEvent(e); } @Override public void requestLayout() { if (ignoreLayout) { return; } super.requestLayout(); } @Override protected void onDraw(Canvas canvas) { int offset = AndroidUtilities.dp(13); int top = scrollOffsetY - backgroundPaddingTop - offset; if (currentSheetAnimationType == 1) { top += listView.getTranslationY(); } int y = top + AndroidUtilities.dp(20); int height = getMeasuredHeight() + AndroidUtilities.dp(15) + backgroundPaddingTop; float rad = 1.0f; if (top + backgroundPaddingTop < ActionBar.getCurrentActionBarHeight()) { float toMove = offset + AndroidUtilities.dp(11 - 7); float moveProgress = Math.min(1.0f, (ActionBar.getCurrentActionBarHeight() - top - backgroundPaddingTop) / toMove); float availableToMove = ActionBar.getCurrentActionBarHeight() - toMove; int diff = (int) (availableToMove * moveProgress); top -= diff; y -= diff; height += diff; rad = 1.0f - moveProgress; } if (Build.VERSION.SDK_INT >= 21) { top += AndroidUtilities.statusBarHeight; y += AndroidUtilities.statusBarHeight; } shadowDrawable.setBounds(0, top, getMeasuredWidth(), height); shadowDrawable.draw(canvas); if (rad != 1.0f) { Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_dialogBackground)); rect.set(backgroundPaddingLeft, backgroundPaddingTop + top, getMeasuredWidth() - backgroundPaddingLeft, backgroundPaddingTop + top + AndroidUtilities.dp(24)); canvas.drawRoundRect(rect, AndroidUtilities.dp(12) * rad, AndroidUtilities.dp(12) * rad, Theme.dialogs_onlineCirclePaint); } if (rad != 0) { float alphaProgress = 1.0f; int w = AndroidUtilities.dp(36); rect.set((getMeasuredWidth() - w) / 2, y, (getMeasuredWidth() + w) / 2, y + AndroidUtilities.dp(4)); int color = Theme.getColor(Theme.key_sheet_scrollUp); int alpha = Color.alpha(color); Theme.dialogs_onlineCirclePaint.setColor(color); Theme.dialogs_onlineCirclePaint.setAlpha((int) (alpha * alphaProgress * rad)); canvas.drawRoundRect(rect, AndroidUtilities.dp(2), AndroidUtilities.dp(2), Theme.dialogs_onlineCirclePaint); } int color1 = Theme.getColor(Theme.key_dialogBackground); int finalColor = Color.argb((int) (255 * actionBar.getAlpha()), (int) (Color.red(color1) * 0.8f), (int) (Color.green(color1) * 0.8f), (int) (Color.blue(color1) * 0.8f)); Theme.dialogs_onlineCirclePaint.setColor(finalColor); canvas.drawRect(backgroundPaddingLeft, 0, getMeasuredWidth() - backgroundPaddingLeft, AndroidUtilities.statusBarHeight, Theme.dialogs_onlineCirclePaint); } }; containerView.setWillNotDraw(false); containerView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, 0); listView = new RecyclerListView(context) { long lastUpdateTime; @Override protected boolean allowSelectChildAtPosition(float x, float y) { return y >= scrollOffsetY + (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0); } @Override protected void dispatchDraw(Canvas canvas) { if (loadingResults) { long newUpdateTime = SystemClock.elapsedRealtime(); long dt = Math.abs(lastUpdateTime - newUpdateTime); if (dt > 17) { dt = 16; } lastUpdateTime = newUpdateTime; totalTranslation += dt * gradientWidth / 1800.0f; while (totalTranslation >= gradientWidth * 2) { totalTranslation -= gradientWidth * 2; } placeholderMatrix.setTranslate(totalTranslation, 0); placeholderGradient.setLocalMatrix(placeholderMatrix); invalidateViews(); invalidate(); } super.dispatchDraw(canvas); } }; DefaultItemAnimator itemAnimator = new DefaultItemAnimator(); itemAnimator.setAddDuration(150); itemAnimator.setMoveDuration(350); itemAnimator.setChangeDuration(0); itemAnimator.setRemoveDuration(0); itemAnimator.setDelayAnimations(false); itemAnimator.setMoveInterpolator(new OvershootInterpolator(1.1f)); itemAnimator.setTranslationInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); listView.setItemAnimator(itemAnimator); listView.setClipToPadding(false); listView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false) { @Override protected int getExtraLayoutSpace(RecyclerView.State state) { return AndroidUtilities.dp(4000); } }); listView.setHorizontalScrollBarEnabled(false); listView.setVerticalScrollBarEnabled(false); listView.setSectionsType(RecyclerListView.SECTIONS_TYPE_DATE); containerView.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); listView.setAdapter(listAdapter = new Adapter(context)); listView.setGlowColor(Theme.getColor(Theme.key_dialogScrollGlow)); listView.setOnItemClickListener((view, position) -> { if (parentFragment == null || parentFragment.getParentActivity() == null || queries != null && !queries.isEmpty()) { return; } if (view instanceof TextCell) { int section = listAdapter.getSectionForPosition(position) - 1; int row = listAdapter.getPositionInSectionForPosition(position) - 1; if (row <= 0 || section < 0) { return; } VotesList votesList = voters.get(section); if (row != votesList.getCount() || loadingMore.contains(votesList)) { return; } if (votesList.collapsed && votesList.collapsedCount < votesList.votes.size()) { votesList.collapsedCount = Math.min(votesList.collapsedCount + 50, votesList.votes.size()); if (votesList.collapsedCount == votesList.votes.size()) { votesList.collapsed = false; } animateSectionUpdates(null); listAdapter.update(true); return; } loadingMore.add(votesList); TLRPC.TL_messages_getPollVotes req = new TLRPC.TL_messages_getPollVotes(); req.peer = peer; req.id = messageObject.getId(); req.limit = 50; req.flags |= 1; req.option = votesList.option; req.flags |= 2; req.offset = votesList.next_offset; chatActivity.getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (!isShowing()) { return; } loadingMore.remove(votesList); if (response != null) { TLRPC.TL_messages_votesList res = (TLRPC.TL_messages_votesList) response; parentFragment.getMessagesController().putUsers(res.users, false); votesList.votes.addAll(res.votes); votesList.next_offset = res.next_offset; animateSectionUpdates(null); listAdapter.update(true); } })); } else if (view instanceof UserCell) { UserCell userCell = (UserCell) view; if (userCell.currentUser == null && userCell.currentChat == null) { return; } Bundle args = new Bundle(); if (userCell.currentUser != null) { args.putLong("user_id", userCell.currentUser.id); } else { args.putLong("chat_id", userCell.currentChat.id); } dismiss(); ProfileActivity fragment = new ProfileActivity(args); if (userCell.currentUser != null) { TLRPC.User currentUser = parentFragment.getCurrentUser(); fragment.setPlayProfileAnimation(currentUser != null && currentUser.id == userCell.currentUser.id ? 1 : 0); } else { TLRPC.Chat currentChat = parentFragment.getCurrentChat(); fragment.setPlayProfileAnimation(currentChat != null && currentChat.id == userCell.currentChat.id ? 1 : 0); } parentFragment.presentFragment(fragment); } }); listView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (listView.getChildCount() <= 0) { return; } updateLayout(true); } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { int offset = AndroidUtilities.dp(13); int top = scrollOffsetY - backgroundPaddingTop - offset; if (top + backgroundPaddingTop < ActionBar.getCurrentActionBarHeight() && listView.canScrollVertically(1)) { View child = listView.getChildAt(0); RecyclerListView.Holder holder = (RecyclerListView.Holder) listView.findViewHolderForAdapterPosition(0); if (holder != null && holder.itemView.getTop() > AndroidUtilities.dp(7)) { listView.smoothScrollBy(0, holder.itemView.getTop() - AndroidUtilities.dp(7)); } } } } }); titleTextView = new AnimatedEmojiSpan.TextViewEmojis(context); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); titleTextView.setPadding(AndroidUtilities.dp(21), AndroidUtilities.dp(5), AndroidUtilities.dp(14), AndroidUtilities.dp(21)); titleTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); titleTextView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)); if (poll.question != null && poll.question.entities != null) { NotificationCenter.listenEmojiLoading(titleTextView); CharSequence questionText = new SpannableStringBuilder(poll.question.text); MediaDataController.addTextStyleRuns(poll.question.entities, poll.question.text, (Spannable) questionText); questionText = Emoji.replaceEmoji(questionText, titleTextView.getPaint().getFontMetricsInt(), false); MessageObject.replaceAnimatedEmoji(questionText, poll.question.entities, titleTextView.getPaint().getFontMetricsInt()); titleTextView.setText(questionText); } else { titleTextView.setText(Emoji.replaceEmoji(poll.question == null ? "" : poll.question.text, titleTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(18), false)); } actionBar = new ActionBar(context) { @Override public void setAlpha(float alpha) { super.setAlpha(alpha); containerView.invalidate(); } }; actionBar.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setItemsColor(Theme.getColor(Theme.key_dialogTextBlack), false); actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_dialogButtonSelector), false); actionBar.setTitleColor(Theme.getColor(Theme.key_dialogTextBlack)); actionBar.setSubtitleColor(Theme.getColor(Theme.key_player_actionBarSubtitle)); actionBar.setOccupyStatusBar(false); actionBar.setAlpha(0.0f); actionBar.setTitle(LocaleController.getString("PollResults", R.string.PollResults)); if (poll.quiz) { actionBar.setSubtitle(LocaleController.formatPluralString("Answer", mediaPoll.results.total_voters)); } else { actionBar.setSubtitle(LocaleController.formatPluralString("Vote", mediaPoll.results.total_voters)); } containerView.addView(actionBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { dismiss(); } } }); actionBarShadow = new View(context); actionBarShadow.setAlpha(0.0f); actionBarShadow.setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); containerView.addView(actionBarShadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 1)); } private int getCurrentTop() { if (listView.getChildCount() != 0) { View child = listView.getChildAt(0); RecyclerListView.Holder holder = (RecyclerListView.Holder) listView.findContainingViewHolder(child); if (holder != null) { return listView.getPaddingTop() - (holder.getAdapterPosition() == 0 && child.getTop() >= 0 ? child.getTop() : 0); } } return -1000; } private void updateButtons() { votesPercents.clear(); int restPercent = 100; boolean hasDifferent = false; int previousPercent = 0; TLRPC.TL_messageMediaPoll media = (TLRPC.TL_messageMediaPoll) messageObject.messageOwner.media; ArrayList<Button> sortedPollButtons = new ArrayList<>(); int maxVote = 0; for (int a = 0, N = voters.size(); a < N; a++) { VotesList list = voters.get(a); Button button = new Button(); sortedPollButtons.add(button); votesPercents.put(list, button); if (!media.results.results.isEmpty()) { for (int b = 0, N2 = media.results.results.size(); b < N2; b++) { TLRPC.TL_pollAnswerVoters answer = media.results.results.get(b); if (Arrays.equals(list.option, answer.option)) { button.votesCount = answer.voters; button.decimal = 100 * (answer.voters / (float) media.results.total_voters); button.percent = (int) button.decimal; button.decimal -= button.percent; if (previousPercent == 0) { previousPercent = button.percent; } else if (button.percent != 0 && previousPercent != button.percent) { hasDifferent = true; } restPercent -= button.percent; maxVote = Math.max(button.percent, maxVote); break; } } } } if (hasDifferent && restPercent != 0) { Collections.sort(sortedPollButtons, (o1, o2) -> { if (o1.decimal > o2.decimal) { return -1; } else if (o1.decimal < o2.decimal) { return 1; } return 0; }); for (int a = 0, N = Math.min(restPercent, sortedPollButtons.size()); a < N; a++) { sortedPollButtons.get(a).percent += 1; } } } @Override protected boolean canDismissWithSwipe() { return false; } @Override public void dismissInternal() { for (int a = 0, N = queries.size(); a < N; a++) { chatActivity.getConnectionsManager().cancelRequest(queries.get(a), true); } super.dismissInternal(); } @SuppressLint("NewApi") private void updateLayout(boolean animated) { if (listView.getChildCount() <= 0) { listView.setTopGlowOffset(scrollOffsetY = listView.getPaddingTop()); containerView.invalidate(); return; } View child = listView.getChildAt(0); RecyclerListView.Holder holder = (RecyclerListView.Holder) listView.findContainingViewHolder(child); int top = child.getTop(); int newOffset = AndroidUtilities.dp(7); if (top >= AndroidUtilities.dp(7) && holder != null && holder.getAdapterPosition() == 0) { newOffset = top; } boolean show = newOffset <= AndroidUtilities.dp(12); if (show && actionBar.getTag() == null || !show && actionBar.getTag() != null) { actionBar.setTag(show ? 1 : null); if (actionBarAnimation != null) { actionBarAnimation.cancel(); actionBarAnimation = null; } actionBarAnimation = new AnimatorSet(); actionBarAnimation.setDuration(180); actionBarAnimation.playTogether( ObjectAnimator.ofFloat(actionBar, View.ALPHA, show ? 1.0f : 0.0f), ObjectAnimator.ofFloat(actionBarShadow, View.ALPHA, show ? 1.0f : 0.0f)); actionBarAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { actionBarAnimation = null; } }); actionBarAnimation.start(); } FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); newOffset += layoutParams.topMargin - AndroidUtilities.dp(11); if (scrollOffsetY != newOffset) { listView.setTopGlowOffset((scrollOffsetY = newOffset) - layoutParams.topMargin); containerView.invalidate(); } } private void updatePlaceholder() { if (placeholderPaint == null) { return; } int color0 = Theme.getColor(Theme.key_dialogBackground); int color1 = Theme.getColor(Theme.key_dialogBackgroundGray); color0 = AndroidUtilities.getAverageColor(color1, color0); placeholderPaint.setColor(color1); placeholderGradient = new LinearGradient(0, 0, gradientWidth = AndroidUtilities.dp(500), 0, new int[]{color1, color0, color1}, new float[]{0.0f, 0.18f, 0.36f}, Shader.TileMode.REPEAT); placeholderPaint.setShader(placeholderGradient); placeholderMatrix = new Matrix(); placeholderGradient.setLocalMatrix(placeholderMatrix); } public class Adapter extends RecyclerListView.SectionsAdapter { private int currentAccount = UserConfig.selectedAccount; private Context mContext; public Adapter(Context context) { mContext = context; } public Object getItem(int section, int position) { if (section == 0) { return 293145; } section--; if (position == 0) { return -928312; } else if (section >= 0 && section < voters.size() && position - 1 < voters.get(section).getCount()) { return Objects.hash(DialogObject.getPeerDialogId(voters.get(section).votes.get(position - 1).peer)); } else { return -182734; } } @Override public boolean isEnabled(RecyclerView.ViewHolder holder, int section, int row) { if (section == 0 || row == 0 || queries != null && !queries.isEmpty()) { return false; } return true; } @Override public int getSectionCount() { return voters.size() + 1; } @Override public int getCountForSection(int section) { if (section == 0) { return 1; } section--; VotesList votesList = voters.get(section); return votesList.getCount() + 1 + (TextUtils.isEmpty(votesList.next_offset) && !votesList.collapsed ? 0 : 1); } private SectionCell createSectionCell() { return new SectionCell(mContext) { @Override protected void onCollapseClick() { VotesList list = (VotesList) getTag(R.id.object_tag); if (list.votes.size() <= 15) { return; } list.collapsed = !list.collapsed; if (list.collapsed) { list.collapsedCount = 10; } animateSectionUpdates(this); listAdapter.update(true); } }; } @Override public View getSectionHeaderView(int section, View view) { if (view == null) { view = createSectionCell(); } SectionCell sectionCell = (SectionCell) view; if (section == 0) { sectionCell.setAlpha(0.0f); } else { section -= 1; view.setAlpha(1.0f); VotesList votesList = voters.get(section); for (int a = 0, N = poll.answers.size(); a < N; a++) { TLRPC.PollAnswer answer = poll.answers.get(a); if (Arrays.equals(answer.option, votesList.option)) { Button button = votesPercents.get(votesList); if (button == null) { continue; } sectionCell.setText(answer.text == null ? "" : answer.text.text, answer.text == null ? null : answer.text.entities, calcPercent(votesList.option), votesList.count, votesList.getCollapsed(), false); sectionCell.setTag(R.id.object_tag, votesList); break; } } } return view; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; switch (viewType) { case 0: { view = new UserCell(mContext); break; } case 1: { if (titleTextView.getParent() != null) { ViewGroup p = (ViewGroup) titleTextView.getParent(); p.removeView(titleTextView); } view = titleTextView; break; } case 2: { view = createSectionCell(); break; } case 3: default: { TextCell textCell = new TextCell(mContext, 23, true); textCell.setOffsetFromImage(65); textCell.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); textCell.setColors(Theme.key_switchTrackChecked, Theme.key_windowBackgroundWhiteBlueText4); view = textCell; break; } } return new RecyclerListView.Holder(view); } @Override public void onBindViewHolder(int section, int position, RecyclerView.ViewHolder holder) { switch (holder.getItemViewType()) { case 2: { SectionCell sectionCell = (SectionCell) holder.itemView; section--; VotesList votesList = voters.get(section); TLRPC.MessagePeerVote vote = votesList.votes.get(0); for (int a = 0, N = poll.answers.size(); a < N; a++) { TLRPC.PollAnswer answer = poll.answers.get(a); if (Arrays.equals(answer.option, votesList.option)) { Button button = votesPercents.get(votesList); if (button == null) { continue; } sectionCell.setText(answer.text == null ? "" : answer.text.text, answer.text == null ? null : answer.text.entities, calcPercent(votesList.option), votesList.count, votesList.getCollapsed(), false); sectionCell.setTag(R.id.object_tag, votesList); break; } } break; } case 3: { TextCell textCell = (TextCell) holder.itemView; section--; VotesList votesList = voters.get(section); textCell.setTextAndIcon(LocaleController.formatPluralString("ShowVotes", votesList.count - votesList.getCount()), R.drawable.arrow_more, false); break; } } } @Override public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) { if (holder.getItemViewType() == 0) { int position = holder.getAdapterPosition(); int section = getSectionForPosition(position); position = getPositionInSectionForPosition(position); section--; position--; UserCell userCell = (UserCell) holder.itemView; VotesList votesList = voters.get(section); TLRPC.MessagePeerVote vote = votesList.votes.get(position); TLObject object = chatActivity.getMessagesController().getUserOrChat(DialogObject.getPeerDialogId(vote.peer)); userCell.setData(object, position, position != votesList.getCount() - 1 || !TextUtils.isEmpty(votesList.next_offset) || votesList.collapsed); } } @Override public int getItemViewType(int section, int position) { if (section == 0) { return 1; } if (position == 0) { return 2; } position--; section--; VotesList votesList = voters.get(section); if (position < votesList.getCount()) { return 0; } return 3; } @Override public String getLetter(int position) { return null; } @Override public void getPositionForScrollProgress(RecyclerListView listView, float progress, int[] position) { position[0] = 0; position[1] = 0; } } public int calcPercent(byte[] option) { if (option == null) { return 0; } int all = 0; int count = 0; for (int i = 0; i < voters.size(); ++i) { VotesList votesList = voters.get(i); if (votesList != null) { all += votesList.count; if (Arrays.equals(votesList.option, option)) { count += votesList.count; } } } if (all <= 0) { return 0; } return (int) Math.round(count / (float) all * 100); } public void animateSectionUpdates(View view) { for (int i = -2; i < listView.getChildCount(); ++i) { View child = i == -2 ? view : (i == -1 ? listView.getPinnedHeader() : listView.getChildAt(i)); if (child instanceof SectionCell && child.getTag(R.id.object_tag) instanceof VotesList) { SectionCell sectionCell = (SectionCell) child; VotesList votesList = (VotesList) child.getTag(R.id.object_tag); for (int a = 0, N = poll.answers.size(); a < N; a++) { TLRPC.PollAnswer answer = poll.answers.get(a); if (Arrays.equals(answer.option, votesList.option)) { Button button = votesPercents.get(votesList); if (button == null) { continue; } sectionCell.setText(answer.text == null ? "" : answer.text.text, answer.text == null ? null : answer.text.entities, calcPercent(votesList.option), votesList.count, votesList.getCollapsed(), true); sectionCell.setTag(R.id.object_tag, votesList); break; } } } } listView.relayoutPinnedHeader(); listView.invalidate(); } @Override public ArrayList<ThemeDescription> getThemeDescriptions() { ArrayList<ThemeDescription> themeDescriptions = new ArrayList<>(); ThemeDescription.ThemeDescriptionDelegate delegate = this::updatePlaceholder; themeDescriptions.add(new ThemeDescription(containerView, 0, null, null, null, null, Theme.key_sheet_scrollUp)); themeDescriptions.add(new ThemeDescription(containerView, 0, null, null, new Drawable[]{shadowDrawable}, null, Theme.key_dialogBackground)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_dialogBackground)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_LISTGLOWCOLOR, null, null, null, null, Theme.key_dialogScrollGlow)); 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_SUBTITLECOLOR, null, null, null, null, Theme.key_player_actionBarSubtitle)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_dialogTextBlack)); themeDescriptions.add(new ThemeDescription(titleTextView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_dialogTextBlack)); themeDescriptions.add(new ThemeDescription(actionBarShadow, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_dialogShadowLine)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{View.class}, null, null, null, delegate, Theme.key_dialogBackground)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{View.class}, null, null, null, delegate, Theme.key_dialogBackgroundGray)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_SECTIONS, new Class[]{SectionCell.class}, new String[]{"textView"}, null, null, null, Theme.key_graySectionText)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_SECTIONS, new Class[]{SectionCell.class}, new String[]{"middleTextView"}, null, null, null, Theme.key_graySectionText)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_SECTIONS, new Class[]{SectionCell.class}, new String[]{"righTextView"}, null, null, null, Theme.key_graySectionText)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_CELLBACKGROUNDCOLOR | ThemeDescription.FLAG_SECTIONS, new Class[]{SectionCell.class}, null, null, null, Theme.key_graySection)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{UserCell.class}, new String[]{"nameTextView"}, null, null, null, Theme.key_dialogTextBlack)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{View.class}, Theme.dividerPaint, null, null, Theme.key_divider)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{TextCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlueText4)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{TextCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_switchTrackChecked)); return themeDescriptions; } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Components/PollVotesAlert.java
2,171
package com.baeldung.dto; public enum FuelType { ELECTRIC, BIO_DIESEL }
eugenp/tutorials
mapstruct/src/main/java/com/baeldung/dto/FuelType.java
2,172
/* * 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.ui.Cells; import static org.telegram.messenger.AndroidUtilities.dp; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.text.Layout; 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.style.ClickableSpan; import android.text.style.ReplacementSpan; import android.text.style.StyleSpan; import android.view.HapticFeedbackConstants; import android.view.MotionEvent; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.view.animation.Interpolator; import android.view.animation.OvershootInterpolator; import androidx.collection.LongSparseArray; import androidx.core.content.ContextCompat; import androidx.core.graphics.ColorUtils; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ChatThemeController; import org.telegram.messenger.CodeHighlighting; import org.telegram.messenger.ContactsController; import org.telegram.messenger.DialogObject; import org.telegram.messenger.DownloadController; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.LiteMode; 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.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.messenger.Utilities; 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.Theme; import org.telegram.ui.Adapters.DialogsAdapter; import org.telegram.ui.Components.AnimatedEmojiDrawable; import org.telegram.ui.Components.AnimatedEmojiSpan; import org.telegram.ui.Components.AnimatedFloat; import org.telegram.ui.Components.AvatarDrawable; import org.telegram.ui.Components.BubbleCounterPath; import org.telegram.ui.Components.CanvasButton; import org.telegram.ui.Components.CheckBox2; import org.telegram.ui.Components.ColoredImageSpan; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.DialogCellTags; import org.telegram.ui.Components.EmptyStubSpan; import org.telegram.ui.Components.ForegroundColorSpanThemable; import org.telegram.ui.Components.Forum.ForumBubbleDrawable; import org.telegram.ui.Components.Forum.ForumUtilities; import org.telegram.ui.Components.Premium.PremiumGradient; import org.telegram.ui.Components.PullForegroundDrawable; import org.telegram.ui.Components.QuoteSpan; import org.telegram.ui.Components.RLottieDrawable; import org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble; import org.telegram.ui.Components.StaticLayoutEx; import org.telegram.ui.Components.StatusDrawable; import org.telegram.ui.Components.SwipeGestureSettingsView; import org.telegram.ui.Components.TextStyleSpan; import org.telegram.ui.Components.TimerDrawable; import org.telegram.ui.Components.TypefaceSpan; import org.telegram.ui.Components.URLSpanNoUnderline; import org.telegram.ui.Components.URLSpanNoUnderlineBold; import org.telegram.ui.Components.VectorAvatarThumbDrawable; import org.telegram.ui.Components.spoilers.SpoilerEffect; import org.telegram.ui.DialogsActivity; import org.telegram.ui.RightSlidingDialogContainer; import org.telegram.ui.Stories.StoriesListPlaceProvider; import org.telegram.ui.Stories.StoriesUtilities; import org.telegram.ui.Stories.StoryViewer; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.Stack; public class DialogCell extends BaseCell implements StoriesListPlaceProvider.AvatarOverlaysView { public boolean drawingForBlur; public boolean collapsed; public boolean drawArchive = true; public float rightFragmentOffset; boolean moving; private RLottieDrawable lastDrawTranslationDrawable; private int lastDrawSwipeMessageStringId; public boolean swipeCanceled; public static final int SENT_STATE_NOTHING = -1; public static final int SENT_STATE_PROGRESS = 0; public static final int SENT_STATE_SENT = 1; public static final int SENT_STATE_READ = 2; public boolean drawAvatar = true; public int avatarStart = 10; public int messagePaddingStart = 72; public int heightDefault = 72; public int heightThreeLines = 78; public int addHeightForTags = 3; public int addForumHeightForTags = 11; public TLRPC.TL_forumTopic forumTopic; public boolean useFromUserAsAvatar; private boolean isTopic; private boolean twoLinesForName; private boolean nameIsEllipsized; private Paint topicCounterPaint; private Paint counterPaintOutline; public float chekBoxPaddingTop = 42; private boolean needEmoji; private boolean hasNameInMessage; private TextPaint currentMessagePaint; private Paint buttonBackgroundPaint; CanvasButton canvasButton; DialogCellDelegate delegate; private boolean applyName; private boolean lastTopicMessageUnread; private boolean showTopicIconInName; protected Drawable topicIconInName[]; private float rightFragmentOpenedProgress; public boolean isTransitionSupport; public boolean drawAvatarSelector; public boolean inPreviewMode; private boolean buttonCreated; private int ttlPeriod; private float ttlProgress; private TimerDrawable timerDrawable; private Paint timerPaint; private Paint timerPaint2; SharedResources sharedResources; public boolean isSavedDialog; public boolean isSavedDialogCell; public DialogCellTags tags; public final StoriesUtilities.AvatarStoryParams storyParams = new StoriesUtilities.AvatarStoryParams(false) { @Override public void openStory(long dialogId, Runnable onDone) { if (delegate == null) { return; } if (currentDialogFolderId != 0) { delegate.openHiddenStories(); } else { if (delegate != null) { delegate.openStory(DialogCell.this, onDone); } } } @Override public void onLongPress() { if (delegate == null) { return; } delegate.showChatPreview(DialogCell.this); } }; private Path thumbPath; private SpoilerEffect thumbSpoiler = new SpoilerEffect(); private boolean drawForwardIcon; private boolean visibleOnScreen = true; private boolean updateLayout; private boolean wasDrawnOnline; public void setMoving(boolean moving) { this.moving = moving; } public boolean isMoving() { return moving; } public void setForumTopic(TLRPC.TL_forumTopic topic, long dialog_id, MessageObject messageObject, boolean showTopicIconInName, boolean animated) { forumTopic = topic; isTopic = forumTopic != null; if (currentDialogId != dialog_id) { lastStatusDrawableParams = -1; } if (messageObject.topicIconDrawable[0] instanceof ForumBubbleDrawable) { ((ForumBubbleDrawable) messageObject.topicIconDrawable[0]).setColor(topic.icon_color); } currentDialogId = dialog_id; lastDialogChangedTime = System.currentTimeMillis(); message = messageObject; isDialogCell = false; this.showTopicIconInName = showTopicIconInName; if (messageObject != null) { lastMessageDate = messageObject.messageOwner.date; currentEditDate = messageObject != null ? messageObject.messageOwner.edit_date : 0; markUnread = false; messageId = messageObject != null ? messageObject.getId() : 0; lastUnreadState = messageObject != null && messageObject.isUnread(); } if (message != null) { lastSendState = message.messageOwner.send_state; } if (!animated) { lastStatusDrawableParams = -1; } if (topic != null) { groupMessages = topic.groupedMessages; } if (forumTopic != null && forumTopic.id == 1) { if (archivedChatsDrawable != null) { archivedChatsDrawable.setCell(this); } } update(0, animated); } public void setRightFragmentOpenedProgress(float rightFragmentOpenedProgress) { if (this.rightFragmentOpenedProgress != rightFragmentOpenedProgress) { this.rightFragmentOpenedProgress = rightFragmentOpenedProgress; invalidate(); } } public void setIsTransitionSupport(boolean isTransitionSupport) { this.isTransitionSupport = isTransitionSupport; } public float collapseOffset = 0; public void checkHeight() { if (getMeasuredHeight() > 0 && getMeasuredHeight() != computeHeight()) { requestLayout(); } } public void setSharedResources(SharedResources sharedResources) { this.sharedResources = sharedResources; } public void setVisible(boolean visibleOnScreen) { if (this.visibleOnScreen == visibleOnScreen) { return; } this.visibleOnScreen = visibleOnScreen; if (visibleOnScreen) { invalidate(); } } public static class FixedWidthSpan extends ReplacementSpan { private int width; public FixedWidthSpan(int w) { width = w; } @Override public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { if (fm == null) { fm = paint.getFontMetricsInt(); } if (fm != null) { int h = fm.descent - fm.ascent; fm.bottom = fm.descent = 1 - h; fm.top = fm.ascent = -1; } return width; } @Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { } } public static class CustomDialog { public String name; public String message; public int id; public int unread_count; public boolean pinned; public boolean muted; public int type; public int date; public boolean verified; public boolean isMedia; public int sent = -1; } private int paintIndex; private int currentAccount; private CustomDialog customDialog; private long currentDialogId; private int currentDialogFolderId; private int currentDialogFolderDialogsCount; private int currentEditDate; public boolean isDialogCell; private int lastMessageDate; private int unreadCount; private boolean markUnread; private int mentionCount; private int reactionMentionCount; private boolean lastUnreadState; private int lastSendState; private boolean dialogMuted; private boolean topicMuted; private boolean drawUnmute; private float dialogMutedProgress; private boolean hasUnmutedTopics = false; private MessageObject message; private boolean isForum; private ArrayList<MessageObject> groupMessages; private boolean clearingDialog; private CharSequence lastMessageString; private int dialogsType; private int folderId; private int messageId; private boolean archiveHidden; protected boolean forbidVerified; protected boolean forbidDraft; private float cornerProgress; private long lastUpdateTime; private float onlineProgress; private float chatCallProgress; private float innerProgress; private int progressStage; private float clipProgress; private int topClip; private int bottomClip; protected float translationX; private boolean isSliding; private RLottieDrawable translationDrawable; private boolean translationAnimationStarted; private boolean drawRevealBackground; private float currentRevealProgress; private float currentRevealBounceProgress; private float archiveBackgroundProgress; protected boolean overrideSwipeAction = false; protected int overrideSwipeActionBackgroundColorKey; protected int overrideSwipeActionRevealBackgroundColorKey; protected String overrideSwipeActionStringKey; protected int overrideSwipeActionStringId; protected RLottieDrawable overrideSwipeActionDrawable; private int thumbsCount; private boolean hasVideoThumb; private Paint thumbBackgroundPaint; private boolean[] thumbImageSeen = new boolean[3]; private ImageReceiver[] thumbImage = new ImageReceiver[3]; private boolean[] drawPlay = new boolean[3]; private boolean[] drawSpoiler = new boolean[3]; public ImageReceiver avatarImage = new ImageReceiver(this); private AvatarDrawable avatarDrawable = new AvatarDrawable(); private boolean animatingArchiveAvatar; private float animatingArchiveAvatarProgress; private BounceInterpolator interpolator = new BounceInterpolator(); protected PullForegroundDrawable archivedChatsDrawable; private TLRPC.User user; private TLRPC.Chat chat; private TLRPC.EncryptedChat encryptedChat; private CharSequence lastPrintString; private int printingStringType; private boolean draftVoice; private TLRPC.DraftMessage draftMessage; private final AnimatedFloat premiumBlockedT = new AnimatedFloat(this, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); private boolean premiumBlocked; public boolean isBlocked() { return premiumBlocked; } protected CheckBox2 checkBox; public boolean useForceThreeLines; public boolean useSeparator; public boolean fullSeparator; public boolean fullSeparator2; private boolean useMeForMyMessages; private boolean hasCall; private boolean showTtl; private int nameLeft; private int nameWidth; private StaticLayout nameLayout; private boolean nameLayoutFits; private float nameLayoutTranslateX; private boolean nameLayoutEllipsizeLeft; private boolean nameLayoutEllipsizeByGradient; private Paint fadePaint; private Paint fadePaintBack; private boolean drawNameLock; private int nameMuteLeft; private int nameLockLeft; private int nameLockTop; private int timeLeft; private int timeTop; private StaticLayout timeLayout; private int lock2Left; private boolean promoDialog; private boolean drawCheck1; private boolean drawCheck2; private boolean drawClock; private int checkDrawLeft; private int checkDrawLeft1; private int clockDrawLeft; private int checkDrawTop; private int halfCheckDrawLeft; private int tagsLeft, tagsRight; private int messageTop; private int messageLeft; private int buttonLeft; private int typingLeft; private StaticLayout messageLayout; private StaticLayout typingLayout; private int buttonTop; private StaticLayout buttonLayout; private Stack<SpoilerEffect> spoilersPool = new Stack<>(); private List<SpoilerEffect> spoilers = new ArrayList<>(); private Stack<SpoilerEffect> spoilersPool2 = new Stack<>(); private List<SpoilerEffect> spoilers2 = new ArrayList<>(); private AnimatedEmojiSpan.EmojiGroupedSpans animatedEmojiStack, animatedEmojiStack2, animatedEmojiStack3, animatedEmojiStackName; private int messageNameTop; private int messageNameLeft; private StaticLayout messageNameLayout; private boolean drawError; private int errorTop; private int errorLeft; private boolean attachedToWindow; private float reorderIconProgress; private boolean drawReorder; private boolean drawPinBackground; private boolean drawPin; private boolean drawPinForced; private int pinTop; private int pinLeft; protected int translateY; protected float xOffset; private boolean drawCount; private boolean drawCount2 = true; private int countTop; private int countLeft; private int countWidth; private int countWidthOld; private int countLeftOld; private boolean countAnimationIncrement; private ValueAnimator countAnimator; private ValueAnimator reactionsMentionsAnimator; private float countChangeProgress = 1f; private float reactionsMentionsChangeProgress = 1f; private StaticLayout countLayout; private StaticLayout countOldLayout; private StaticLayout countAnimationStableLayout; private StaticLayout countAnimationInLayout; private boolean drawMention; private boolean drawReactionMention; private int mentionLeft; private int reactionMentionLeft; private int mentionWidth; private StaticLayout mentionLayout; private boolean drawVerified; private boolean drawPremium; private AnimatedEmojiDrawable.SwapAnimatedEmojiDrawable emojiStatus; private int drawScam; private boolean isSelected; private RectF rect = new RectF(); private DialogsAdapter.DialogsPreloader preloader; private Path counterPath; private RectF counterPathRect; private int animateToStatusDrawableParams; private int animateFromStatusDrawableParams; private int lastStatusDrawableParams = -1; private float statusDrawableProgress; private boolean statusDrawableAnimationInProgress; private ValueAnimator statusDrawableAnimator; long lastDialogChangedTime; private int statusDrawableLeft; private DialogsActivity parentFragment; private StaticLayout swipeMessageTextLayout; private int swipeMessageTextId; private int swipeMessageWidth; private int readOutboxMaxId = -1; private final DialogUpdateHelper updateHelper = new DialogUpdateHelper(); public static class BounceInterpolator implements Interpolator { public float getInterpolation(float t) { if (t < 0.33f) { return 0.1f * (t / 0.33f); } else { t -= 0.33f; if (t < 0.33f) { return 0.1f - 0.15f * (t / 0.34f); } else { t -= 0.34f; return -0.05f + 0.05f * (t / 0.33f); } } } } public DialogCell(DialogsActivity fragment, Context context, boolean needCheck, boolean forceThreeLines) { this(fragment, context, needCheck, forceThreeLines, UserConfig.selectedAccount, null); } private final Theme.ResourcesProvider resourcesProvider; public DialogCell(DialogsActivity fragment, Context context, boolean needCheck, boolean forceThreeLines, int account, Theme.ResourcesProvider resourcesProvider) { super(context); storyParams.allowLongress = true; this.resourcesProvider = resourcesProvider; parentFragment = fragment; Theme.createDialogsResources(context); avatarImage.setRoundRadius(dp(28)); for (int i = 0; i < thumbImage.length; ++i) { thumbImage[i] = new ImageReceiver(this); thumbImage[i].ignoreNotifications = true; thumbImage[i].setRoundRadius(dp(2)); thumbImage[i].setAllowLoadingOnAttachedOnly(true); } useForceThreeLines = forceThreeLines; currentAccount = account; emojiStatus = new AnimatedEmojiDrawable.SwapAnimatedEmojiDrawable(this, dp(22)); avatarImage.setAllowLoadingOnAttachedOnly(true); } public void setDialog(TLRPC.Dialog dialog, int type, int folder) { if (currentDialogId != dialog.id) { if (statusDrawableAnimator != null) { statusDrawableAnimator.removeAllListeners(); statusDrawableAnimator.cancel(); } statusDrawableAnimationInProgress = false; lastStatusDrawableParams = -1; } currentDialogId = dialog.id; lastDialogChangedTime = System.currentTimeMillis(); isDialogCell = true; if (dialog instanceof TLRPC.TL_dialogFolder) { TLRPC.TL_dialogFolder dialogFolder = (TLRPC.TL_dialogFolder) dialog; currentDialogFolderId = dialogFolder.folder.id; if (archivedChatsDrawable != null) { archivedChatsDrawable.setCell(this); } } else { currentDialogFolderId = 0; } dialogsType = type; showPremiumBlocked(dialogsType == DialogsActivity.DIALOGS_TYPE_FORWARD); if (tags == null) { tags = new DialogCellTags(); } folderId = folder; messageId = 0; if (update(0, false)) { requestLayout(); } checkOnline(); checkGroupCall(); checkChatTheme(); checkTtl(); } protected boolean drawLock2() { return false; } public void setDialog(CustomDialog dialog) { customDialog = dialog; messageId = 0; update(0); checkOnline(); checkGroupCall(); checkChatTheme(); checkTtl(); } private void checkOnline() { if (user != null) { TLRPC.User newUser = MessagesController.getInstance(currentAccount).getUser(user.id); if (newUser != null) { user = newUser; } } boolean isOnline = isOnline(); onlineProgress = isOnline ? 1.0f : 0.0f; } private boolean isOnline() { if (isForumCell()) { return false; } if (user == null || user.self) { return false; } if (user.status != null && user.status.expires <= 0) { if (MessagesController.getInstance(currentAccount).onlinePrivacy.containsKey(user.id)) { return true; } } if (user.status != null && user.status.expires > ConnectionsManager.getInstance(currentAccount).getCurrentTime()) { return true; } return false; } private void checkGroupCall() { hasCall = chat != null && chat.call_active && chat.call_not_empty; chatCallProgress = hasCall ? 1.0f : 0.0f; } private void checkTtl() { showTtl = ttlPeriod > 0 && !hasCall && !isOnline() && !(checkBox != null && checkBox.isChecked()); ttlProgress = showTtl ? 1.0f : 0.0f; } private void checkChatTheme() { if (message != null && message.messageOwner != null && message.messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme && lastUnreadState) { TLRPC.TL_messageActionSetChatTheme setThemeAction = (TLRPC.TL_messageActionSetChatTheme) message.messageOwner.action; ChatThemeController.getInstance(currentAccount).setDialogTheme(currentDialogId, setThemeAction.emoticon,false); } } public void setDialog(long dialog_id, MessageObject messageObject, int date, boolean useMe, boolean animated) { if (currentDialogId != dialog_id) { lastStatusDrawableParams = -1; } currentDialogId = dialog_id; lastDialogChangedTime = System.currentTimeMillis(); message = messageObject; useMeForMyMessages = useMe; isDialogCell = false; lastMessageDate = date; currentEditDate = messageObject != null ? messageObject.messageOwner.edit_date : 0; unreadCount = 0; markUnread = false; messageId = messageObject != null ? messageObject.getId() : 0; mentionCount = 0; reactionMentionCount = 0; lastUnreadState = messageObject != null && messageObject.isUnread(); if (message != null) { lastSendState = message.messageOwner.send_state; } update(0, animated); } public long getDialogId() { return currentDialogId; } public int getMessageId() { return messageId; } public void setPreloader(DialogsAdapter.DialogsPreloader preloader) { this.preloader = preloader; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); isSliding = false; drawRevealBackground = false; currentRevealProgress = 0.0f; attachedToWindow = false; reorderIconProgress = getIsPinned() && drawReorder ? 1.0f : 0.0f; avatarImage.onDetachedFromWindow(); for (int i = 0; i < thumbImage.length; ++i) { thumbImage[i].onDetachedFromWindow(); } if (translationDrawable != null) { translationDrawable.stop(); translationDrawable.setProgress(0.0f); translationDrawable.setCallback(null); translationDrawable = null; translationAnimationStarted = false; } if (preloader != null) { preloader.remove(currentDialogId); } if (emojiStatus != null) { emojiStatus.detach(); } AnimatedEmojiSpan.release(this, animatedEmojiStack); AnimatedEmojiSpan.release(this, animatedEmojiStack2); AnimatedEmojiSpan.release(this, animatedEmojiStack3); AnimatedEmojiSpan.release(this, animatedEmojiStackName); storyParams.onDetachFromWindow(); canvasButton = null; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); avatarImage.onAttachedToWindow(); for (int i = 0; i < thumbImage.length; ++i) { thumbImage[i].onAttachedToWindow(); } resetPinnedArchiveState(); animatedEmojiStack = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStack, messageLayout); animatedEmojiStack2 = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStack2, messageNameLayout); animatedEmojiStack3 = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStack3, buttonLayout); animatedEmojiStackName = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStackName, nameLayout); if (emojiStatus != null) { emojiStatus.attach(); } } public void resetPinnedArchiveState() { archiveHidden = SharedConfig.archiveHidden; archiveBackgroundProgress = archiveHidden ? 0.0f : 1.0f; avatarDrawable.setArchivedAvatarHiddenProgress(archiveBackgroundProgress); clipProgress = 0.0f; isSliding = false; reorderIconProgress = getIsPinned() && drawReorder ? 1.0f : 0.0f; attachedToWindow = true; cornerProgress = 0.0f; setTranslationX(0); setTranslationY(0); if (emojiStatus != null && attachedToWindow) { emojiStatus.attach(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (checkBox != null) { checkBox.measure( MeasureSpec.makeMeasureSpec(dp(24), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(dp(24), MeasureSpec.EXACTLY) ); } if (isTopic) { setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), dp((useForceThreeLines || SharedConfig.useThreeLinesLayout ? heightThreeLines : heightDefault) + (hasTags() && (!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) ? (isForumCell() ? addForumHeightForTags : addHeightForTags) : 0)) + (useSeparator ? 1 : 0)); checkTwoLinesForName(); } setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), computeHeight()); topClip = 0; bottomClip = getMeasuredHeight(); } private int computeHeight() { int height; if (isForumCell() && !isTransitionSupport && !collapsed) { height = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 86 : 91); if (useSeparator) { height += 1; } if (hasTags()) { height += dp(addForumHeightForTags); } } else { height = getCollapsedHeight(); } return height; } private int getCollapsedHeight() { int height = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? heightThreeLines : heightDefault); if (useSeparator) { height += 1; } if (twoLinesForName) { height += dp(20); } if (hasTags() && (!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell())) { height += dp(isForumCell() ? addForumHeightForTags : addHeightForTags); } return height; } private void checkTwoLinesForName() { twoLinesForName = false; if (isTopic && !hasTags()) { buildLayout(); if (nameIsEllipsized) { twoLinesForName = true; buildLayout(); } } } int lastSize; @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { if (currentDialogId == 0 && customDialog == null) { return; } if (checkBox != null) { int paddingStart = dp(messagePaddingStart - (useForceThreeLines || SharedConfig.useThreeLinesLayout ? 29 : 27)); int x, y; if (inPreviewMode) { x = dp(8);//LocaleController.isRTL ? (right - left) - paddingStart : paddingStart; y = (getMeasuredHeight() - checkBox.getMeasuredHeight()) >> 1; } else { x = LocaleController.isRTL ? (right - left) - paddingStart : paddingStart; y = dp(chekBoxPaddingTop + (useForceThreeLines || SharedConfig.useThreeLinesLayout ? 6 : 0)); } checkBox.layout(x, y, x + checkBox.getMeasuredWidth(), y + checkBox.getMeasuredHeight()); } int size = getMeasuredHeight() + getMeasuredWidth() << 16; if (size != lastSize || updateLayout) { updateLayout = false; lastSize = size; try { buildLayout(); } catch (Exception e) { FileLog.e(e); } } } public boolean isUnread() { return (unreadCount != 0 || markUnread) && !dialogMuted; } public boolean getHasUnread() { return (unreadCount != 0 || markUnread); } public boolean getIsMuted() { return dialogMuted; } public boolean getIsPinned() { return drawPin || drawPinForced; } public void setPinForced(boolean value) { drawPinForced = value; if (getMeasuredWidth() > 0 && getMeasuredHeight() > 0) { buildLayout(); } invalidate(); } private CharSequence formatArchivedDialogNames() { final MessagesController messagesController = MessagesController.getInstance(currentAccount); ArrayList<TLRPC.Dialog> dialogs = messagesController.getDialogs(currentDialogFolderId); currentDialogFolderDialogsCount = dialogs.size(); SpannableStringBuilder builder = new SpannableStringBuilder(); for (int a = 0, N = dialogs.size(); a < N; a++) { TLRPC.Dialog dialog = dialogs.get(a); TLRPC.User currentUser = null; TLRPC.Chat currentChat = null; if (messagesController.isHiddenByUndo(dialog.id)) { continue; } if (DialogObject.isEncryptedDialog(dialog.id)) { TLRPC.EncryptedChat encryptedChat = messagesController.getEncryptedChat(DialogObject.getEncryptedChatId(dialog.id)); if (encryptedChat != null) { currentUser = messagesController.getUser(encryptedChat.user_id); } } else { if (DialogObject.isUserDialog(dialog.id)) { currentUser = messagesController.getUser(dialog.id); } else { currentChat = messagesController.getChat(-dialog.id); } } String title; if (currentChat != null) { title = currentChat.title.replace('\n', ' '); } else if (currentUser != null) { if (UserObject.isDeleted(currentUser)) { title = LocaleController.getString("HiddenName", R.string.HiddenName); } else { title = ContactsController.formatName(currentUser.first_name, currentUser.last_name).replace('\n', ' '); } } else { continue; } if (builder.length() > 0) { builder.append(", "); } int boldStart = builder.length(); int boldEnd = boldStart + title.length(); builder.append(title); if (dialog.unread_count > 0) { builder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, Theme.getColor(Theme.key_chats_nameArchived, resourcesProvider)), boldStart, boldEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } if (builder.length() > 150) { break; } } if (MessagesController.getInstance(currentAccount).storiesController.getTotalStoriesCount(true) > 0) { int totalCount; totalCount = Math.max(1, MessagesController.getInstance(currentAccount).storiesController.getTotalStoriesCount(true)); if (builder.length() > 0) { builder.append(", "); } builder.append(LocaleController.formatPluralString("Stories", totalCount)); } return Emoji.replaceEmoji(builder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), dp(17), false); } public boolean hasTags() { return tags != null && !tags.isEmpty(); } public boolean separateMessageNameLine() { return (useForceThreeLines || SharedConfig.useThreeLinesLayout) && !hasTags(); } int thumbSize; public void buildLayout() { if (isTransitionSupport) { return; } if (isDialogCell) { boolean needUpdate = updateHelper.update(); if (!needUpdate && currentDialogFolderId == 0 && encryptedChat == null) { return; } } if (useForceThreeLines || SharedConfig.useThreeLinesLayout) { Theme.dialogs_namePaint[0].setTextSize(dp(17)); Theme.dialogs_nameEncryptedPaint[0].setTextSize(dp(17)); Theme.dialogs_messagePaint[0].setTextSize(dp(16)); Theme.dialogs_messagePrintingPaint[0].setTextSize(dp(16)); Theme.dialogs_namePaint[1].setTextSize(dp(16)); Theme.dialogs_nameEncryptedPaint[1].setTextSize(dp(16)); Theme.dialogs_messagePaint[1].setTextSize(dp(15)); Theme.dialogs_messagePrintingPaint[1].setTextSize(dp(15)); Theme.dialogs_messagePaint[1].setColor(Theme.dialogs_messagePaint[1].linkColor = Theme.getColor(Theme.key_chats_message_threeLines, resourcesProvider)); paintIndex = 1; thumbSize = 18; } else { Theme.dialogs_namePaint[0].setTextSize(dp(17)); Theme.dialogs_nameEncryptedPaint[0].setTextSize(dp(17)); Theme.dialogs_messagePaint[0].setTextSize(dp(16)); Theme.dialogs_messagePrintingPaint[0].setTextSize(dp(16)); Theme.dialogs_messagePaint[0].setColor(Theme.dialogs_messagePaint[0].linkColor = Theme.getColor(Theme.key_chats_message, resourcesProvider)); paintIndex = 0; thumbSize = 19; } currentDialogFolderDialogsCount = 0; CharSequence nameString = ""; String timeString = ""; String countString = null; String mentionString = null; CharSequence messageString = ""; CharSequence typingString = ""; CharSequence messageNameString = null; CharSequence printingString = null; CharSequence buttonString = null; if (!isForumCell() && (isDialogCell || isTopic)) { printingString = MessagesController.getInstance(currentAccount).getPrintingString(currentDialogId, getTopicId(), true); } currentMessagePaint = Theme.dialogs_messagePaint[paintIndex]; boolean checkMessage = true; drawNameLock = false; drawVerified = false; drawPremium = false; drawForwardIcon = false; drawScam = 0; drawPinBackground = false; thumbsCount = 0; hasVideoThumb = false; nameLayoutEllipsizeByGradient = false; int offsetName = 0; boolean showChecks = !UserObject.isUserSelf(user) && !useMeForMyMessages; boolean drawTime = true; printingStringType = -1; int printingStringReplaceIndex = -1; if (!isForumCell()) { buttonLayout = null; } int messageFormatType; if (Build.VERSION.SDK_INT >= 18) { if ((!useForceThreeLines && !SharedConfig.useThreeLinesLayout || currentDialogFolderId != 0) || isForumCell() || hasTags()) { //1 - "%2$s: \u2068%1$s\u2069"; messageFormatType = 1; hasNameInMessage = true; } else { //2 - "\u2068%1$s\u2069"; messageFormatType = 2; hasNameInMessage = false; } } else { if ((!useForceThreeLines && !SharedConfig.useThreeLinesLayout || currentDialogFolderId != 0) || isForumCell() || hasTags()) { //3 - "%2$s: %1$s"; messageFormatType = 3; hasNameInMessage = true; } else { //4 - "%1$s"; messageFormatType = 4; hasNameInMessage = false; } } if (message != null) { message.updateTranslation(); } CharSequence msgText = message != null ? message.messageText : null; if (msgText instanceof Spannable) { Spannable sp = new SpannableStringBuilder(msgText); for (Object span : sp.getSpans(0, sp.length(), URLSpanNoUnderlineBold.class)) sp.removeSpan(span); for (Object span : sp.getSpans(0, sp.length(), URLSpanNoUnderline.class)) sp.removeSpan(span); msgText = sp; } lastMessageString = msgText; if (customDialog != null) { if (customDialog.type == 2) { drawNameLock = true; if (useForceThreeLines || SharedConfig.useThreeLinesLayout) { nameLockTop = dp(12.5f); if (!LocaleController.isRTL) { nameLockLeft = dp(messagePaddingStart + 6); nameLeft = dp(messagePaddingStart + 10) + Theme.dialogs_lockDrawable.getIntrinsicWidth(); } else { nameLockLeft = getMeasuredWidth() - dp(messagePaddingStart + 6) - Theme.dialogs_lockDrawable.getIntrinsicWidth(); nameLeft = dp(22); } } else { nameLockTop = dp(16.5f); if (!LocaleController.isRTL) { nameLockLeft = dp(messagePaddingStart + 4); nameLeft = dp(messagePaddingStart + 8) + Theme.dialogs_lockDrawable.getIntrinsicWidth(); } else { nameLockLeft = getMeasuredWidth() - dp(messagePaddingStart + 4) - Theme.dialogs_lockDrawable.getIntrinsicWidth(); nameLeft = dp(18); } } } else { drawVerified = !forbidVerified && customDialog.verified; if (useForceThreeLines || SharedConfig.useThreeLinesLayout) { if (!LocaleController.isRTL) { nameLeft = dp(messagePaddingStart + 6); } else { nameLeft = dp(22); } } else { if (!LocaleController.isRTL) { nameLeft = dp(messagePaddingStart + 4); } else { nameLeft = dp(18); } } } if (customDialog.type == 1) { messageNameString = LocaleController.getString("FromYou", R.string.FromYou); checkMessage = false; SpannableStringBuilder stringBuilder; if (customDialog.isMedia) { currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex]; stringBuilder = formatInternal(messageFormatType, message.messageText, null); stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_attachMessage, resourcesProvider), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { String mess = customDialog.message; if (mess.length() > 150) { mess = mess.substring(0, 150); } if (useForceThreeLines || SharedConfig.useThreeLinesLayout) { stringBuilder = formatInternal(messageFormatType, mess, messageNameString); } else { stringBuilder = formatInternal(messageFormatType, mess.replace('\n', ' '), messageNameString); } } messageString = Emoji.replaceEmoji(stringBuilder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), dp(20), false); } else { messageString = customDialog.message; if (customDialog.isMedia) { currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex]; } } timeString = LocaleController.stringForMessageListDate(customDialog.date); if (customDialog.unread_count != 0) { drawCount = true; countString = String.format("%d", customDialog.unread_count); } else { drawCount = false; } if (customDialog.sent == SENT_STATE_PROGRESS) { drawClock = true; drawCheck1 = false; drawCheck2 = false; } else if (customDialog.sent == SENT_STATE_READ) { drawCheck1 = true; drawCheck2 = true; drawClock = false; } else if (customDialog.sent == SENT_STATE_SENT) { drawCheck1 = false; drawCheck2 = true; drawClock = false; } else { drawClock = false; drawCheck1 = false; drawCheck2 = false; } drawError = false; nameString = customDialog.name; } else { if (useForceThreeLines || SharedConfig.useThreeLinesLayout) { if (!LocaleController.isRTL) { nameLeft = dp(messagePaddingStart + 6); } else { nameLeft = dp(22); } } else { if (!LocaleController.isRTL) { nameLeft = dp(messagePaddingStart + 4); } else { nameLeft = dp(18); } } if (encryptedChat != null) { if (currentDialogFolderId == 0) { drawNameLock = true; if (useForceThreeLines || SharedConfig.useThreeLinesLayout) { nameLockTop = dp(12.5f); if (!LocaleController.isRTL) { nameLockLeft = dp(messagePaddingStart + 6); nameLeft = dp(messagePaddingStart + 10) + Theme.dialogs_lockDrawable.getIntrinsicWidth(); } else { nameLockLeft = getMeasuredWidth() - dp(messagePaddingStart + 6) - Theme.dialogs_lockDrawable.getIntrinsicWidth(); nameLeft = dp(22); } } else { nameLockTop = dp(16.5f); if (!LocaleController.isRTL) { nameLockLeft = dp(messagePaddingStart + 4); nameLeft = dp(messagePaddingStart + 8) + Theme.dialogs_lockDrawable.getIntrinsicWidth(); } else { nameLockLeft = getMeasuredWidth() - dp(messagePaddingStart + 4) - Theme.dialogs_lockDrawable.getIntrinsicWidth(); nameLeft = dp(18); } } } } else { if (currentDialogFolderId == 0) { if (chat != null) { if (chat.scam) { drawScam = 1; Theme.dialogs_scamDrawable.checkText(); } else if (chat.fake) { drawScam = 2; Theme.dialogs_fakeDrawable.checkText(); } else if (DialogObject.getEmojiStatusDocumentId(chat.emoji_status) != 0) { drawPremium = true; nameLayoutEllipsizeByGradient = true; emojiStatus.center = LocaleController.isRTL; emojiStatus.set(DialogObject.getEmojiStatusDocumentId(chat.emoji_status), false); } else { drawVerified = !forbidVerified && chat.verified; } } else if (user != null) { if (user.scam) { drawScam = 1; Theme.dialogs_scamDrawable.checkText(); } else if (user.fake) { drawScam = 2; Theme.dialogs_fakeDrawable.checkText(); } else { drawVerified =!forbidVerified && user.verified; } drawPremium = MessagesController.getInstance(currentAccount).isPremiumUser(user) && UserConfig.getInstance(currentAccount).clientUserId != user.id && user.id != 0; if (drawPremium) { Long emojiStatusId = UserObject.getEmojiStatusDocumentId(user); emojiStatus.center = LocaleController.isRTL; if (emojiStatusId != null) { nameLayoutEllipsizeByGradient = true; emojiStatus.set(emojiStatusId, false); } else { nameLayoutEllipsizeByGradient = true; emojiStatus.set(PremiumGradient.getInstance().premiumStarDrawableMini, false); } } } } } int lastDate = lastMessageDate; if (lastMessageDate == 0 && message != null) { lastDate = message.messageOwner.date; } if (isTopic) { draftVoice = MediaDataController.getInstance(currentAccount).getDraftVoice(currentDialogId, getTopicId()) != null; draftMessage = !draftVoice ? MediaDataController.getInstance(currentAccount).getDraft(currentDialogId, getTopicId()) : null; if (draftMessage != null && TextUtils.isEmpty(draftMessage.message)) { draftMessage = null; } } else if (isDialogCell || isSavedDialogCell) { draftVoice = MediaDataController.getInstance(currentAccount).getDraftVoice(currentDialogId, getTopicId()) != null; draftMessage = !draftVoice ? MediaDataController.getInstance(currentAccount).getDraft(currentDialogId, 0) : null; } else { draftVoice = false; draftMessage = null; } if ((draftVoice || draftMessage != null) && (!draftVoice && draftMessage != null && TextUtils.isEmpty(draftMessage.message) && (draftMessage.reply_to == null || draftMessage.reply_to.reply_to_msg_id == 0) || draftMessage != null && lastDate > draftMessage.date && unreadCount != 0) || ChatObject.isChannel(chat) && !chat.megagroup && !chat.creator && (chat.admin_rights == null || !chat.admin_rights.post_messages) || chat != null && (chat.left || chat.kicked) || forbidDraft || ChatObject.isForum(chat) && !isTopic) { draftMessage = null; draftVoice = false; } if (isForumCell()) { draftMessage = null; draftVoice = false; needEmoji = true; updateMessageThumbs(); messageNameString = getMessageNameString(); messageString = formatTopicsNames(); String restrictionReason = message != null ? MessagesController.getRestrictionReason(message.messageOwner.restriction_reason) : null; buttonString = message != null ? getMessageStringFormatted(messageFormatType, restrictionReason, messageNameString, true) : ""; if (applyName && buttonString.length() >= 0 && messageNameString != null) { SpannableStringBuilder spannableStringBuilder = SpannableStringBuilder.valueOf(buttonString); spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_name, resourcesProvider), 0, Math.min(spannableStringBuilder.length(), messageNameString.length() + 1), 0); buttonString = spannableStringBuilder; } currentMessagePaint = Theme.dialogs_messagePaint[paintIndex]; } else { if (printingString != null) { lastPrintString = printingString; printingStringType = MessagesController.getInstance(currentAccount).getPrintingStringType(currentDialogId, getTopicId()); StatusDrawable statusDrawable = Theme.getChatStatusDrawable(printingStringType); int startPadding = 0; if (statusDrawable != null) { startPadding = statusDrawable.getIntrinsicWidth() + dp(3); } SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); printingString = TextUtils.replace(printingString, new String[]{"..."}, new String[]{""}); if (printingStringType == 5) { printingStringReplaceIndex = printingString.toString().indexOf("**oo**"); } if (printingStringReplaceIndex >= 0) { spannableStringBuilder.append(printingString).setSpan(new FixedWidthSpan(Theme.getChatStatusDrawable(printingStringType).getIntrinsicWidth()), printingStringReplaceIndex, printingStringReplaceIndex + 6, 0); } else { spannableStringBuilder.append(" ").append(printingString).setSpan(new FixedWidthSpan(startPadding), 0, 1, 0); } typingString = spannableStringBuilder; checkMessage = false; } else { lastPrintString = null; printingStringType = -1; } if (draftVoice || draftMessage != null) { checkMessage = false; messageNameString = LocaleController.getString("Draft", R.string.Draft); if (draftMessage != null && TextUtils.isEmpty(draftMessage.message)) { if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && !hasTags()) { messageString = ""; } else { SpannableStringBuilder stringBuilder = SpannableStringBuilder.valueOf(messageNameString); stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_draft, resourcesProvider), 0, messageNameString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); messageString = stringBuilder; } } else { String mess; if (draftVoice) { mess = LocaleController.getString(R.string.AttachAudio); } else if (draftMessage != null) { mess = draftMessage.message; if (mess.length() > 150) { mess = mess.substring(0, 150); } } else { mess = ""; } Spannable messSpan = new SpannableStringBuilder(mess); if (draftMessage != null) { MediaDataController.addTextStyleRuns(draftMessage, messSpan, TextStyleSpan.FLAG_STYLE_SPOILER | TextStyleSpan.FLAG_STYLE_STRIKE); if (draftMessage != null && draftMessage.entities != null) { MediaDataController.addAnimatedEmojiSpans(draftMessage.entities, messSpan, currentMessagePaint == null ? null : currentMessagePaint.getFontMetricsInt()); } } else if (draftVoice) { messSpan.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_actionMessage, resourcesProvider), 0, messSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } SpannableStringBuilder stringBuilder = formatInternal(messageFormatType, AndroidUtilities.replaceNewLines(messSpan), messageNameString); if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || hasTags()) { stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_draft, resourcesProvider), 0, messageNameString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } messageString = Emoji.replaceEmoji(stringBuilder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), dp(20), false); } } else { if (clearingDialog) { currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex]; messageString = LocaleController.getString("HistoryCleared", R.string.HistoryCleared); } else if (message == null) { if (currentDialogFolderId != 0) { messageString = formatArchivedDialogNames(); } else if (encryptedChat != null) { currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex]; if (encryptedChat instanceof TLRPC.TL_encryptedChatRequested) { messageString = LocaleController.getString("EncryptionProcessing", R.string.EncryptionProcessing); } else if (encryptedChat instanceof TLRPC.TL_encryptedChatWaiting) { messageString = LocaleController.formatString("AwaitingEncryption", R.string.AwaitingEncryption, UserObject.getFirstName(user)); } else if (encryptedChat instanceof TLRPC.TL_encryptedChatDiscarded) { messageString = LocaleController.getString("EncryptionRejected", R.string.EncryptionRejected); } else if (encryptedChat instanceof TLRPC.TL_encryptedChat) { if (encryptedChat.admin_id == UserConfig.getInstance(currentAccount).getClientUserId()) { messageString = LocaleController.formatString("EncryptedChatStartedOutgoing", R.string.EncryptedChatStartedOutgoing, UserObject.getFirstName(user)); } else { messageString = LocaleController.getString("EncryptedChatStartedIncoming", R.string.EncryptedChatStartedIncoming); } } } else { if (dialogsType == DialogsActivity.DIALOGS_TYPE_FORWARD && UserObject.isUserSelf(user)) { messageString = LocaleController.getString(parentFragment != null && parentFragment.isQuote ? R.string.SavedMessagesInfoQuote : R.string.SavedMessagesInfo); showChecks = false; drawTime = false; } else { messageString = ""; } } } else { String restrictionReason = MessagesController.getRestrictionReason(message.messageOwner.restriction_reason); TLRPC.User fromUser = null; TLRPC.Chat fromChat = null; long fromId = message.getFromChatId(); if (DialogObject.isUserDialog(fromId)) { fromUser = MessagesController.getInstance(currentAccount).getUser(fromId); } else { fromChat = MessagesController.getInstance(currentAccount).getChat(-fromId); } drawCount2 = true; boolean lastMessageIsReaction = false; if (dialogsType == 0 && currentDialogId > 0 && message.isOutOwner() && message.messageOwner.reactions != null && message.messageOwner.reactions.recent_reactions != null && !message.messageOwner.reactions.recent_reactions.isEmpty() && reactionMentionCount > 0) { TLRPC.MessagePeerReaction lastReaction = message.messageOwner.reactions.recent_reactions.get(0); if (lastReaction.unread && lastReaction.peer_id.user_id != 0 &&lastReaction.peer_id.user_id != UserConfig.getInstance(currentAccount).clientUserId) { lastMessageIsReaction = true; ReactionsLayoutInBubble.VisibleReaction visibleReaction = ReactionsLayoutInBubble.VisibleReaction.fromTLReaction(lastReaction.reaction); currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex]; if (visibleReaction.emojicon != null) { messageString = LocaleController.formatString("ReactionInDialog", R.string.ReactionInDialog, visibleReaction.emojicon); } else { String string = LocaleController.formatString("ReactionInDialog", R.string.ReactionInDialog, "**reaction**"); int i = string.indexOf("**reaction**"); string = string.replace("**reaction**", "d"); SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(string); spannableStringBuilder.setSpan(new AnimatedEmojiSpan(visibleReaction.documentId, currentMessagePaint == null ? null : currentMessagePaint.getFontMetricsInt()), i, i + 1, 0); messageString = spannableStringBuilder; } } } if (lastMessageIsReaction) { } else if (dialogsType == DialogsActivity.DIALOGS_TYPE_ADD_USERS_TO) { if (chat != null) { if (ChatObject.isChannel(chat) && !chat.megagroup) { if (chat.participants_count != 0) { messageString = LocaleController.formatPluralStringComma("Subscribers", chat.participants_count); } else { if (!ChatObject.isPublic(chat)) { messageString = LocaleController.getString("ChannelPrivate", R.string.ChannelPrivate).toLowerCase(); } else { messageString = LocaleController.getString("ChannelPublic", R.string.ChannelPublic).toLowerCase(); } } } else { if (chat.participants_count != 0) { messageString = LocaleController.formatPluralStringComma("Members", chat.participants_count); } else { if (chat.has_geo) { messageString = LocaleController.getString("MegaLocation", R.string.MegaLocation); } else if (!ChatObject.isPublic(chat)) { messageString = LocaleController.getString("MegaPrivate", R.string.MegaPrivate).toLowerCase(); } else { messageString = LocaleController.getString("MegaPublic", R.string.MegaPublic).toLowerCase(); } } } } else { messageString = ""; } drawCount2 = false; showChecks = false; drawTime = false; } else if (dialogsType == DialogsActivity.DIALOGS_TYPE_FORWARD && UserObject.isUserSelf(user)) { messageString = LocaleController.getString(parentFragment != null && parentFragment.isQuote ? R.string.SavedMessagesInfoQuote : R.string.SavedMessagesInfo); showChecks = false; drawTime = false; } else if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout && currentDialogFolderId != 0) { checkMessage = false; messageString = formatArchivedDialogNames(); } else if (message.messageOwner instanceof TLRPC.TL_messageService && (!MessageObject.isTopicActionMessage(message) || message.messageOwner.action instanceof TLRPC.TL_messageActionTopicCreate)) { if (ChatObject.isChannelAndNotMegaGroup(chat) && (message.messageOwner.action instanceof TLRPC.TL_messageActionChannelMigrateFrom)) { messageString = ""; showChecks = false; } else { messageString = msgText; } currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex]; if (message.type == MessageObject.TYPE_SUGGEST_PHOTO) { updateMessageThumbs(); messageString = applyThumbs(messageString); } } else { needEmoji = true; updateMessageThumbs(); String triedMessageName = null; if (!isSavedDialog && user != null && user.self && !message.isOutOwner()) { triedMessageName = getMessageNameString(); } if (isSavedDialog && user != null && !user.self && message != null && message.isOutOwner() || triedMessageName != null || chat != null && chat.id > 0 && fromChat == null && (!ChatObject.isChannel(chat) || ChatObject.isMegagroup(chat)) && !ForumUtilities.isTopicCreateMessage(message)) { messageNameString = triedMessageName != null ? triedMessageName : getMessageNameString(); if (chat != null && chat.forum && !isTopic && !useFromUserAsAvatar) { CharSequence topicName = MessagesController.getInstance(currentAccount).getTopicsController().getTopicIconName(chat, message, currentMessagePaint); if (!TextUtils.isEmpty(topicName)) { SpannableStringBuilder arrowSpan = new SpannableStringBuilder("-"); ColoredImageSpan coloredImageSpan = new ColoredImageSpan(ContextCompat.getDrawable(ApplicationLoader.applicationContext, R.drawable.msg_mini_forumarrow).mutate()); coloredImageSpan.setColorKey(useForceThreeLines || SharedConfig.useThreeLinesLayout ? -1 : Theme.key_chats_nameMessage); arrowSpan.setSpan(coloredImageSpan, 0, 1, 0); SpannableStringBuilder nameSpannableString = new SpannableStringBuilder(); nameSpannableString.append(messageNameString).append(arrowSpan).append(topicName); messageNameString = nameSpannableString; } } checkMessage = false; SpannableStringBuilder stringBuilder = getMessageStringFormatted(messageFormatType, restrictionReason, messageNameString, false); int thumbInsertIndex = 0; if (!useFromUserAsAvatar && (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || currentDialogFolderId != 0 && stringBuilder.length() > 0)) { try { stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_nameMessage, resourcesProvider), 0, thumbInsertIndex = messageNameString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); offsetName = thumbInsertIndex; } catch (Exception e) { FileLog.e(e); } } messageString = Emoji.replaceEmoji(stringBuilder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), dp(20), false); if (message.hasHighlightedWords()) { CharSequence messageH = AndroidUtilities.highlightText(messageString, message.highlightedWords, resourcesProvider); if (messageH != null) { messageString = messageH; } } if (thumbsCount > 0) { if (!(messageString instanceof SpannableStringBuilder)) { messageString = new SpannableStringBuilder(messageString); } checkMessage = false; SpannableStringBuilder builder = (SpannableStringBuilder) messageString; if (thumbInsertIndex >= builder.length()) { builder.append(" "); builder.setSpan(new FixedWidthSpan(dp(thumbsCount * (thumbSize + 2) - 2 + 5)), builder.length() - 1, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { builder.insert(thumbInsertIndex, " "); builder.setSpan(new FixedWidthSpan(dp(thumbsCount * (thumbSize + 2) - 2 + 5)), thumbInsertIndex, thumbInsertIndex + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } } else { if (!TextUtils.isEmpty(restrictionReason)) { messageString = restrictionReason; } else if (MessageObject.isTopicActionMessage(message)) { if (message.messageTextShort != null && (!(message.messageOwner.action instanceof TLRPC.TL_messageActionTopicCreate) || !isTopic)) { messageString = message.messageTextShort; } else { messageString = message.messageText; } if (message.topicIconDrawable[0] instanceof ForumBubbleDrawable) { TLRPC.TL_forumTopic topic = MessagesController.getInstance(currentAccount).getTopicsController().findTopic(-message.getDialogId(), MessageObject.getTopicId(currentAccount, message.messageOwner, true)); if (topic != null) { ((ForumBubbleDrawable) message.topicIconDrawable[0]).setColor(topic.icon_color); } } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && message.messageOwner.media.photo instanceof TLRPC.TL_photoEmpty && message.messageOwner.media.ttl_seconds != 0) { messageString = LocaleController.getString("AttachPhotoExpired", R.string.AttachPhotoExpired); } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaDocument && (message.messageOwner.media.document instanceof TLRPC.TL_documentEmpty || message.messageOwner.media.document == null) && message.messageOwner.media.ttl_seconds != 0) { if (message.messageOwner.media.voice) { messageString = LocaleController.getString(R.string.AttachVoiceExpired); } else if (message.messageOwner.media.round) { messageString = LocaleController.getString(R.string.AttachRoundExpired); } else { messageString = LocaleController.getString(R.string.AttachVideoExpired); } } else if (getCaptionMessage() != null) { MessageObject message = getCaptionMessage(); String emoji; if (!needEmoji) { emoji = ""; } else if (message.isVideo()) { emoji = "\uD83D\uDCF9 "; } else if (message.isVoice()) { emoji = "\uD83C\uDFA4 "; } else if (message.isMusic()) { emoji = "\uD83C\uDFA7 "; } else if (message.isPhoto()) { emoji = "\uD83D\uDDBC "; } else { emoji = "\uD83D\uDCCE "; } if (message.hasHighlightedWords() && !TextUtils.isEmpty(message.messageOwner.message)) { CharSequence text = message.messageTrimmedToHighlight; int w = getMeasuredWidth() - dp(messagePaddingStart + 23 + 24); if (hasNameInMessage) { if (!TextUtils.isEmpty(messageNameString)) { w -= currentMessagePaint.measureText(messageNameString.toString()); } w -= currentMessagePaint.measureText(": "); } if (w > 0) { text = AndroidUtilities.ellipsizeCenterEnd(text, message.highlightedWords.get(0), w, currentMessagePaint, 130).toString(); } messageString = new SpannableStringBuilder(emoji).append(text); } else { SpannableStringBuilder msgBuilder = new SpannableStringBuilder(message.caption); if (message != null && message.messageOwner != null) { if (message != null) { message.spoilLoginCode(); } MediaDataController.addTextStyleRuns(message.messageOwner.entities, message.caption, msgBuilder, TextStyleSpan.FLAG_STYLE_SPOILER | TextStyleSpan.FLAG_STYLE_STRIKE); MediaDataController.addAnimatedEmojiSpans(message.messageOwner.entities, msgBuilder, currentMessagePaint == null ? null : currentMessagePaint.getFontMetricsInt()); } messageString = new SpannableStringBuilder(emoji).append(msgBuilder); } } else if (thumbsCount > 1) { if (hasVideoThumb) { messageString = LocaleController.formatPluralString("Media", groupMessages == null ? 0 : groupMessages.size()); } else { messageString = LocaleController.formatPluralString("Photos", groupMessages == null ? 0 : groupMessages.size()); } currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex]; } else { if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGiveaway) { boolean isChannel; if (message.messageOwner.fwd_from != null && message.messageOwner.fwd_from.from_id instanceof TLRPC.TL_peerChannel) { isChannel = ChatObject.isChannelAndNotMegaGroup(message.messageOwner.fwd_from.from_id.channel_id, currentAccount); } else { isChannel = ChatObject.isChannelAndNotMegaGroup(chat); } messageString = LocaleController.getString(isChannel ? R.string.BoostingGiveawayChannelStarted : R.string.BoostingGiveawayGroupStarted); } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGiveawayResults) { messageString = LocaleController.getString("BoostingGiveawayResults", R.string.BoostingGiveawayResults); } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media; if (mediaPoll.poll.question != null && mediaPoll.poll.question.entities != null) { SpannableStringBuilder questionText = new SpannableStringBuilder(mediaPoll.poll.question.text); MediaDataController.addTextStyleRuns(mediaPoll.poll.question.entities, mediaPoll.poll.question.text, questionText); MediaDataController.addAnimatedEmojiSpans(mediaPoll.poll.question.entities, questionText, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt()); messageString = new SpannableStringBuilder("\uD83D\uDCCA ").append(questionText); } else { messageString = "\uD83D\uDCCA " + mediaPoll.poll.question.text; } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) { messageString = "\uD83C\uDFAE " + message.messageOwner.media.game.title; } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice) { messageString = message.messageOwner.media.title; } else if (message.type == MessageObject.TYPE_MUSIC) { messageString = String.format("\uD83C\uDFA7 %s - %s", message.getMusicAuthor(), message.getMusicTitle()); } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaStory && message.messageOwner.media.via_mention) { if (message.isOut()) { long did = message.getDialogId(); String username = ""; TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); if (user != null) { username = UserObject.getFirstName(user); int index; if ((index = username.indexOf(' ')) >= 0) { username = username.substring(0, index); } } messageString = LocaleController.formatString("StoryYouMentionInDialog", R.string.StoryYouMentionInDialog, username); } else { messageString = LocaleController.getString("StoryMentionInDialog", R.string.StoryMentionInDialog); } } else { if (message.hasHighlightedWords() && !TextUtils.isEmpty(message.messageOwner.message)){ messageString = message.messageTrimmedToHighlight; if (message.messageTrimmedToHighlight != null) { messageString = message.messageTrimmedToHighlight; } int w = getMeasuredWidth() - dp(messagePaddingStart + 23 ); messageString = AndroidUtilities.ellipsizeCenterEnd(messageString, message.highlightedWords.get(0), w, currentMessagePaint, 130); } else { SpannableStringBuilder stringBuilder = new SpannableStringBuilder(msgText); if (message != null) { message.spoilLoginCode(); } MediaDataController.addTextStyleRuns(message, stringBuilder, TextStyleSpan.FLAG_STYLE_SPOILER | TextStyleSpan.FLAG_STYLE_STRIKE); if (message != null && message.messageOwner != null) { MediaDataController.addAnimatedEmojiSpans(message.messageOwner.entities, stringBuilder, currentMessagePaint == null ? null : currentMessagePaint.getFontMetricsInt()); } messageString = stringBuilder; } AndroidUtilities.highlightText(messageString, message.highlightedWords, resourcesProvider); } if (message.messageOwner.media != null && !message.isMediaEmpty()) { currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex]; } } if (message.isReplyToStory()) { SpannableStringBuilder builder = new SpannableStringBuilder(messageString); builder.insert(0, "d "); builder.setSpan(new ColoredImageSpan(ContextCompat.getDrawable(getContext(), R.drawable.msg_mini_replystory).mutate()), 0, 1, 0); messageString = builder; } if (thumbsCount > 0) { if (message.hasHighlightedWords() && !TextUtils.isEmpty(message.messageOwner.message)) { messageString = message.messageTrimmedToHighlight; if (message.messageTrimmedToHighlight != null) { messageString = message.messageTrimmedToHighlight; } int w = getMeasuredWidth() - dp(messagePaddingStart + 23 + (thumbSize + 2) * thumbsCount - 2 + 5); messageString = AndroidUtilities.ellipsizeCenterEnd(messageString, message.highlightedWords.get(0), w, currentMessagePaint, 130).toString(); } else { if (messageString.length() > 150) { messageString = messageString.subSequence(0, 150); } messageString = AndroidUtilities.replaceNewLines(messageString); } if (!(messageString instanceof SpannableStringBuilder)) { messageString = new SpannableStringBuilder(messageString); } checkMessage = false; SpannableStringBuilder builder = (SpannableStringBuilder) messageString; builder.insert(0, " "); builder.setSpan(new FixedWidthSpan(dp((thumbSize + 2) * thumbsCount - 2 + 5)), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); Emoji.replaceEmoji(builder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), dp(17), false); if (message.hasHighlightedWords()) { CharSequence s = AndroidUtilities.highlightText(builder, message.highlightedWords, resourcesProvider); if (s != null) { messageString = s; } } } if (message.isForwarded() && message.needDrawForwarded()) { drawForwardIcon = true; SpannableStringBuilder builder = new SpannableStringBuilder(messageString); builder.insert(0, "d "); ColoredImageSpan coloredImageSpan = new ColoredImageSpan(ContextCompat.getDrawable(getContext(), R.drawable.mini_forwarded).mutate()); coloredImageSpan.setAlpha(0.9f); builder.setSpan(coloredImageSpan, 0, 1, 0); messageString = builder; } } } if (currentDialogFolderId != 0) { messageNameString = formatArchivedDialogNames(); } } } } if (draftMessage != null) { timeString = LocaleController.stringForMessageListDate(draftMessage.date); } else if (lastMessageDate != 0) { timeString = LocaleController.stringForMessageListDate(lastMessageDate); } else if (message != null) { timeString = LocaleController.stringForMessageListDate(message.messageOwner.date); } if (message == null || isSavedDialog) { drawCheck1 = false; drawCheck2 = false; drawClock = message != null && message.isSending() && currentDialogId == UserConfig.getInstance(currentAccount).getClientUserId(); drawCount = false; drawMention = false; drawReactionMention = false; drawError = false; } else { if (currentDialogFolderId != 0) { if (unreadCount + mentionCount > 0) { if (unreadCount > mentionCount) { drawCount = true; drawMention = false; countString = String.format("%d", unreadCount + mentionCount); } else { drawCount = false; drawMention = true; mentionString = String.format("%d", unreadCount + mentionCount); } } else { drawCount = false; drawMention = false; } drawReactionMention = false; } else { if (clearingDialog) { drawCount = false; showChecks = false; } else if (unreadCount != 0 && (unreadCount != 1 || unreadCount != mentionCount || message == null || !message.messageOwner.mentioned)) { drawCount = true; countString = String.format("%d", unreadCount); } else if (markUnread) { drawCount = true; countString = ""; } else { drawCount = false; } if (mentionCount != 0) { drawMention = true; mentionString = "@"; } else { drawMention = false; } if (reactionMentionCount > 0) { drawReactionMention = true; } else { drawReactionMention = false; } } if (message.isOut() && draftMessage == null && showChecks && !(message.messageOwner.action instanceof TLRPC.TL_messageActionHistoryClear)) { if (message.isSending()) { drawCheck1 = false; drawCheck2 = false; drawClock = true; drawError = false; } else if (message.isSendError()) { drawCheck1 = false; drawCheck2 = false; drawClock = false; drawError = true; drawCount = false; drawMention = false; } else if (message.isSent()) { if (forumTopic != null) { drawCheck1 = forumTopic.read_outbox_max_id >= message.getId(); } else if (isDialogCell) { drawCheck1 = (readOutboxMaxId > 0 && readOutboxMaxId >= message.getId()) || !message.isUnread() || ChatObject.isChannel(chat) && !chat.megagroup; } else { drawCheck1 = !message.isUnread() || ChatObject.isChannel(chat) && !chat.megagroup; } drawCheck2 = true; drawClock = false; drawError = false; } } else { drawCheck1 = false; drawCheck2 = false; drawClock = false; drawError = false; } } promoDialog = false; MessagesController messagesController = MessagesController.getInstance(currentAccount); if (dialogsType == DialogsActivity.DIALOGS_TYPE_DEFAULT && messagesController.isPromoDialog(currentDialogId, true)) { drawPinBackground = true; promoDialog = true; if (messagesController.promoDialogType == MessagesController.PROMO_TYPE_PROXY) { timeString = LocaleController.getString("UseProxySponsor", R.string.UseProxySponsor); } else if (messagesController.promoDialogType == MessagesController.PROMO_TYPE_PSA) { timeString = LocaleController.getString("PsaType_" + messagesController.promoPsaType); if (TextUtils.isEmpty(timeString)) { timeString = LocaleController.getString("PsaTypeDefault", R.string.PsaTypeDefault); } if (!TextUtils.isEmpty(messagesController.promoPsaMessage)) { messageString = messagesController.promoPsaMessage; thumbsCount = 0; } } } if (currentDialogFolderId != 0) { nameString = LocaleController.getString("ArchivedChats", R.string.ArchivedChats); } else { if (chat != null) { if (useFromUserAsAvatar) { if (topicIconInName == null) { topicIconInName = new Drawable[1]; } topicIconInName[0] = null; nameString = MessagesController.getInstance(currentAccount).getTopicsController().getTopicIconName(chat, message, currentMessagePaint, topicIconInName); if (nameString == null) { nameString = ""; } } else if (isTopic) { if (topicIconInName == null) { topicIconInName = new Drawable[1]; } topicIconInName[0] = null; nameString = showTopicIconInName ? ForumUtilities.getTopicSpannedName(forumTopic, Theme.dialogs_namePaint[paintIndex], topicIconInName, false) : forumTopic.title; } else { nameString = chat.title; } } else if (user != null) { if (UserObject.isReplyUser(user)) { nameString = LocaleController.getString("RepliesTitle", R.string.RepliesTitle); } else if (UserObject.isAnonymous(user)) { nameString = LocaleController.getString(R.string.AnonymousForward); } else if (UserObject.isUserSelf(user)) { if (isSavedDialog) { nameString = LocaleController.getString(R.string.MyNotes); } else if (useMeForMyMessages) { nameString = LocaleController.getString("FromYou", R.string.FromYou); } else { if (dialogsType == DialogsActivity.DIALOGS_TYPE_FORWARD) { drawPinBackground = true; } nameString = LocaleController.getString("SavedMessages", R.string.SavedMessages); } } else { nameString = UserObject.getUserName(user); } } if (nameString != null && nameString.length() == 0) { nameString = LocaleController.getString("HiddenName", R.string.HiddenName); } } } int timeWidth; if (drawTime) { timeWidth = (int) Math.ceil(Theme.dialogs_timePaint.measureText(timeString)); timeLayout = new StaticLayout(timeString, Theme.dialogs_timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); if (!LocaleController.isRTL) { timeLeft = getMeasuredWidth() - dp(15) - timeWidth; } else { timeLeft = dp(15); } } else { timeWidth = 0; timeLayout = null; timeLeft = 0; } int timeLeftOffset = 0; if (drawLock2()) { if (LocaleController.isRTL) { lock2Left = timeLeft + timeWidth + dp(4); } else { lock2Left = timeLeft - Theme.dialogs_lock2Drawable.getIntrinsicWidth() - dp(4); } timeLeftOffset += Theme.dialogs_lock2Drawable.getIntrinsicWidth() + dp(4); timeWidth += timeLeftOffset; } if (!LocaleController.isRTL) { nameWidth = getMeasuredWidth() - nameLeft - dp(14 + 8) - timeWidth; } else { nameWidth = getMeasuredWidth() - nameLeft - dp(messagePaddingStart + 5 + 8) - timeWidth; nameLeft += timeWidth; } if (drawNameLock) { nameWidth -= dp(LocaleController.isRTL ? 8 : 4) + Theme.dialogs_lockDrawable.getIntrinsicWidth(); } if (drawClock) { int w = Theme.dialogs_clockDrawable.getIntrinsicWidth() + dp(5); nameWidth -= w; if (!LocaleController.isRTL) { clockDrawLeft = timeLeft - timeLeftOffset - w; } else { clockDrawLeft = timeLeft + timeWidth + dp(5); nameLeft += w; } } else if (drawCheck2) { int w = Theme.dialogs_checkDrawable.getIntrinsicWidth() + dp(5); nameWidth -= w; if (drawCheck1) { nameWidth -= Theme.dialogs_halfCheckDrawable.getIntrinsicWidth() - dp(8); if (!LocaleController.isRTL) { halfCheckDrawLeft = timeLeft - timeLeftOffset - w; checkDrawLeft = halfCheckDrawLeft - dp(5.5f); } else { checkDrawLeft = timeLeft + timeWidth + dp(5); halfCheckDrawLeft = checkDrawLeft + dp(5.5f); nameLeft += w + Theme.dialogs_halfCheckDrawable.getIntrinsicWidth() - dp(8); } } else { if (!LocaleController.isRTL) { checkDrawLeft1 = timeLeft - timeLeftOffset - w; } else { checkDrawLeft1 = timeLeft + timeWidth + dp(5); nameLeft += w; } } } if (drawPremium && emojiStatus.getDrawable() != null) { int w = dp(6 + 24 + 6); nameWidth -= w; if (LocaleController.isRTL) { nameLeft += w; } } else if ((dialogMuted || drawUnmute) && !drawVerified && drawScam == 0) { int w = dp(6) + Theme.dialogs_muteDrawable.getIntrinsicWidth(); nameWidth -= w; if (LocaleController.isRTL) { nameLeft += w; } } else if (drawVerified) { int w = dp(6) + Theme.dialogs_verifiedDrawable.getIntrinsicWidth(); nameWidth -= w; if (LocaleController.isRTL) { nameLeft += w; } } else if (drawPremium) { int w = dp(6 + 24 + 6); nameWidth -= w; if (LocaleController.isRTL) { nameLeft += w; } } else if (drawScam != 0) { int w = dp(6) + (drawScam == 1 ? Theme.dialogs_scamDrawable : Theme.dialogs_fakeDrawable).getIntrinsicWidth(); nameWidth -= w; if (LocaleController.isRTL) { nameLeft += w; } } try { int ellipsizeWidth = nameWidth - dp(12); if (ellipsizeWidth < 0) { ellipsizeWidth = 0; } if (nameString instanceof String) { nameString = ((String) nameString).replace('\n', ' '); } CharSequence nameStringFinal = nameString; if (nameLayoutEllipsizeByGradient) { nameLayoutFits = nameStringFinal.length() == TextUtils.ellipsize(nameStringFinal, Theme.dialogs_namePaint[paintIndex], ellipsizeWidth, TextUtils.TruncateAt.END).length(); ellipsizeWidth += dp(48); } nameIsEllipsized = Theme.dialogs_namePaint[paintIndex].measureText(nameStringFinal.toString()) > ellipsizeWidth; if (!twoLinesForName) { nameStringFinal = TextUtils.ellipsize(nameStringFinal, Theme.dialogs_namePaint[paintIndex], ellipsizeWidth, TextUtils.TruncateAt.END); } nameStringFinal = Emoji.replaceEmoji(nameStringFinal, Theme.dialogs_namePaint[paintIndex].getFontMetricsInt(), dp(20), false); if (message != null && message.hasHighlightedWords()) { CharSequence s = AndroidUtilities.highlightText(nameStringFinal, message.highlightedWords, resourcesProvider); if (s != null) { nameStringFinal = s; } } if (twoLinesForName) { nameLayout = StaticLayoutEx.createStaticLayout(nameStringFinal, Theme.dialogs_namePaint[paintIndex], ellipsizeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false, TextUtils.TruncateAt.END, ellipsizeWidth, 2); } else { nameLayout = new StaticLayout(nameStringFinal, Theme.dialogs_namePaint[paintIndex], Math.max(ellipsizeWidth, nameWidth), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } nameLayoutTranslateX = nameLayoutEllipsizeByGradient && nameLayout.isRtlCharAt(0) ? -dp(36) : 0; nameLayoutEllipsizeLeft = nameLayout.isRtlCharAt(0); } catch (Exception e) { FileLog.e(e); } animatedEmojiStackName = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStackName, nameLayout); int messageWidth; int avatarLeft; int avatarTop; int thumbLeft; if (useForceThreeLines || SharedConfig.useThreeLinesLayout) { avatarTop = dp(11); messageNameTop = dp(32); timeTop = dp(13); errorTop = dp(43); pinTop = dp(43); countTop = dp(43); checkDrawTop = dp(13); messageWidth = getMeasuredWidth() - dp(messagePaddingStart + 21); if (LocaleController.isRTL) { buttonLeft = typingLeft = messageLeft = messageNameLeft = dp(16); avatarLeft = getMeasuredWidth() - dp(56 + avatarStart); thumbLeft = avatarLeft - dp(13 + 18); } else { buttonLeft = typingLeft = messageLeft = messageNameLeft = dp(messagePaddingStart + 6); avatarLeft = dp(avatarStart); thumbLeft = avatarLeft + dp(56 + 13); } storyParams.originalAvatarRect.set(avatarLeft, avatarTop, avatarLeft + dp(56), avatarTop + dp(56)); for (int i = 0; i < thumbImage.length; ++i) { thumbImage[i].setImageCoords(thumbLeft + (thumbSize + 2) * i, avatarTop + dp(31) + (twoLinesForName ? dp(20) : 0) - (!(useForceThreeLines || SharedConfig.useThreeLinesLayout) && tags != null && !tags.isEmpty() ? dp(9) : 0), dp(18), dp(18)); } } else { avatarTop = dp(9); messageNameTop = dp(31); timeTop = dp(16); errorTop = dp(39); pinTop = dp(39); countTop = isTopic ? dp(36) : dp(39); checkDrawTop = dp(17); messageWidth = getMeasuredWidth() - dp(messagePaddingStart + 23 - (LocaleController.isRTL ? 0 : 12)); if (LocaleController.isRTL) { buttonLeft = typingLeft = messageLeft = messageNameLeft = dp(22); avatarLeft = getMeasuredWidth() - dp(54 + avatarStart); thumbLeft = avatarLeft - dp(11 + (thumbsCount * (thumbSize + 2) - 2)); } else { buttonLeft = typingLeft = messageLeft = messageNameLeft = dp(messagePaddingStart + 4); avatarLeft = dp(avatarStart); thumbLeft = avatarLeft + dp(56 + 11); } storyParams.originalAvatarRect.set(avatarLeft, avatarTop, avatarLeft + dp(54), avatarTop + dp(54)); for (int i = 0; i < thumbImage.length; ++i) { thumbImage[i].setImageCoords(thumbLeft + (thumbSize + 2) * i, avatarTop + dp(30) + (twoLinesForName ? dp(20) : 0) - (!(useForceThreeLines || SharedConfig.useThreeLinesLayout) && tags != null && !tags.isEmpty() ? dp(9) : 0), dp(thumbSize), dp(thumbSize)); } } if (LocaleController.isRTL) { tagsRight = getMeasuredWidth() - dp(messagePaddingStart); tagsLeft = dp(64); } else { tagsLeft = messageLeft; tagsRight = getMeasuredWidth() - dp(64); } if (twoLinesForName) { messageNameTop += dp(20); } if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && tags != null && !tags.isEmpty()) { timeTop -= dp(6); checkDrawTop -= dp(6); } if (getIsPinned()) { if (!LocaleController.isRTL) { pinLeft = getMeasuredWidth() - Theme.dialogs_pinnedDrawable.getIntrinsicWidth() - dp(14); } else { pinLeft = dp(14); } } if (drawError) { int w = dp(23 + 8); messageWidth -= w; if (!LocaleController.isRTL) { errorLeft = getMeasuredWidth() - dp(23 + 11); } else { errorLeft = dp(11); messageLeft += w; typingLeft += w; buttonLeft += w; messageNameLeft += w; } } else if (countString != null || mentionString != null || drawReactionMention) { if (countString != null) { countWidth = Math.max(dp(12), (int) Math.ceil(Theme.dialogs_countTextPaint.measureText(countString))); countLayout = new StaticLayout(countString, Theme.dialogs_countTextPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); int w = countWidth + dp(18); messageWidth -= w; if (!LocaleController.isRTL) { countLeft = getMeasuredWidth() - countWidth - dp(20); } else { countLeft = dp(20); messageLeft += w; typingLeft += w; buttonLeft += w; messageNameLeft += w; } drawCount = true; } else { countWidth = 0; } if (mentionString != null) { if (currentDialogFolderId != 0) { mentionWidth = Math.max(dp(12), (int) Math.ceil(Theme.dialogs_countTextPaint.measureText(mentionString))); mentionLayout = new StaticLayout(mentionString, Theme.dialogs_countTextPaint, mentionWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); } else { mentionWidth = dp(12); } int w = mentionWidth + dp(18); messageWidth -= w; if (!LocaleController.isRTL) { mentionLeft = getMeasuredWidth() - mentionWidth - dp(20) - (countWidth != 0 ? countWidth + dp(18) : 0); } else { mentionLeft = dp(20) + (countWidth != 0 ? countWidth + dp(18) : 0); messageLeft += w; typingLeft += w; buttonLeft += w; messageNameLeft += w; } drawMention = true; } else { mentionWidth = 0; } if (drawReactionMention) { int w = dp(24); messageWidth -= w; if (!LocaleController.isRTL) { reactionMentionLeft = getMeasuredWidth() - dp(32); if (drawMention) { reactionMentionLeft -= (mentionWidth != 0 ? (mentionWidth + dp(18)) : 0); } if (drawCount) { reactionMentionLeft -= (countWidth != 0 ? countWidth + dp(18) : 0); } } else { reactionMentionLeft = dp(20); if (drawMention) { reactionMentionLeft += (mentionWidth != 0 ? (mentionWidth + dp(18)) : 0); } if (drawCount) { reactionMentionLeft += (countWidth != 0 ? (countWidth + dp(18)) : 0); } messageLeft += w; typingLeft += w; buttonLeft += w; messageNameLeft += w; } } } else { if (getIsPinned()) { int w = Theme.dialogs_pinnedDrawable.getIntrinsicWidth() + dp(8); messageWidth -= w; if (LocaleController.isRTL) { messageLeft += w; typingLeft += w; buttonLeft += w; messageNameLeft += w; } } drawCount = false; drawMention = false; } if (checkMessage) { if (messageString == null) { messageString = ""; } CharSequence mess = messageString; if (mess.length() > 150) { mess = mess.subSequence(0, 150); } if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || hasTags() || messageNameString != null) { mess = AndroidUtilities.replaceNewLines(mess); } else { mess = AndroidUtilities.replaceTwoNewLinesToOne(mess); } messageString = Emoji.replaceEmoji(mess, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), dp(17), false); if (message != null) { CharSequence s = AndroidUtilities.highlightText(messageString, message.highlightedWords, resourcesProvider); if (s != null) { messageString = s; } } } messageWidth = Math.max(dp(12), messageWidth); buttonTop = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 58 : 62); if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) { buttonTop -= dp(isForumCell() ? 10 : 12); } if (isForumCell()) { messageTop = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 34 : 39); for (int i = 0; i < thumbImage.length; ++i) { thumbImage[i].setImageY(buttonTop); } } else if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && !hasTags() && messageNameString != null && (currentDialogFolderId == 0 || currentDialogFolderDialogsCount == 1)) { try { if (message != null && message.hasHighlightedWords()) { CharSequence s = AndroidUtilities.highlightText(messageNameString, message.highlightedWords, resourcesProvider); if (s != null) { messageNameString = s; } } messageNameLayout = StaticLayoutEx.createStaticLayout(messageNameString, Theme.dialogs_messageNamePaint, messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false, TextUtils.TruncateAt.END, messageWidth, 1); } catch (Exception e) { FileLog.e(e); } messageTop = dp(32 + 19); int yoff = nameIsEllipsized && isTopic ? dp(20) : 0; for (int i = 0; i < thumbImage.length; ++i) { thumbImage[i].setImageY(avatarTop + yoff + dp(40)); } } else { messageNameLayout = null; if (useForceThreeLines || SharedConfig.useThreeLinesLayout) { messageTop = dp(32); int yoff = nameIsEllipsized && isTopic ? dp(20) : 0; for (int i = 0; i < thumbImage.length; ++i) { thumbImage[i].setImageY(avatarTop + yoff + dp(21)); } } else { messageTop = dp(39); } } if (twoLinesForName) { messageTop += dp(20); } animatedEmojiStack2 = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStack2, messageNameLayout); try { buttonCreated = false; if (!TextUtils.isEmpty(buttonString)) { buttonString = Emoji.replaceEmoji(buttonString, currentMessagePaint.getFontMetricsInt(), dp(17), false); CharSequence buttonStringFinal = TextUtils.ellipsize(buttonString, currentMessagePaint, messageWidth - dp(26), TextUtils.TruncateAt.END); buttonLayout = new StaticLayout(buttonStringFinal, currentMessagePaint, messageWidth - dp(20), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); spoilersPool2.addAll(spoilers2); spoilers2.clear(); SpoilerEffect.addSpoilers(this, buttonLayout, spoilersPool2, spoilers2); } else { buttonLayout = null; } } catch (Exception e) { } animatedEmojiStack3 = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStack3, buttonLayout); try { if (!TextUtils.isEmpty(typingString)) { if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && !hasTags()) { typingLayout = StaticLayoutEx.createStaticLayout(typingString, Theme.dialogs_messagePrintingPaint[paintIndex], messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, dp(1), false, TextUtils.TruncateAt.END, messageWidth, typingString != null ? 1 : 2); } else { typingString = TextUtils.ellipsize(typingString, currentMessagePaint, messageWidth - dp(12), TextUtils.TruncateAt.END); typingLayout = new StaticLayout(typingString, Theme.dialogs_messagePrintingPaint[paintIndex], messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } } } catch (Exception e) { FileLog.e(e); } try { CharSequence messageStringFinal; // Removing links and bold spans to get rid of underlining and boldness if (messageString instanceof Spannable) { Spannable messageStringSpannable = (Spannable) messageString; for (Object span : messageStringSpannable.getSpans(0, messageStringSpannable.length(), Object.class)) { if (span instanceof ClickableSpan || span instanceof CodeHighlighting.Span || !isFolderCell() && span instanceof TypefaceSpan || span instanceof CodeHighlighting.ColorSpan || span instanceof QuoteSpan || span instanceof QuoteSpan.QuoteStyleSpan || (span instanceof StyleSpan && ((StyleSpan) span).getStyle() == android.graphics.Typeface.BOLD)) { messageStringSpannable.removeSpan(span); } } } if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && !hasTags() && currentDialogFolderId != 0 && currentDialogFolderDialogsCount > 1) { messageStringFinal = messageNameString; messageNameString = null; currentMessagePaint = Theme.dialogs_messagePaint[paintIndex]; } else if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || hasTags() || messageNameString != null) { if (!isForumCell() && messageString instanceof Spanned && ((Spanned) messageString).getSpans(0, messageString.length(), FixedWidthSpan.class).length <= 0) { messageStringFinal = TextUtils.ellipsize(messageString, currentMessagePaint, messageWidth - dp(12 + (thumbsCount * (thumbSize + 2) - 2) + 5), TextUtils.TruncateAt.END); } else { messageStringFinal = TextUtils.ellipsize(messageString, currentMessagePaint, messageWidth - dp(12), TextUtils.TruncateAt.END); } } else { messageStringFinal = messageString; } Layout.Alignment align = isForum && LocaleController.isRTL ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_NORMAL; if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && !hasTags()) { if (thumbsCount > 0 && messageNameString != null) { messageWidth += dp(5); } messageLayout = StaticLayoutEx.createStaticLayout(messageStringFinal, currentMessagePaint, messageWidth, align, 1.0f, dp(1), false, TextUtils.TruncateAt.END, messageWidth, messageNameString != null ? 1 : 2); } else { if (thumbsCount > 0) { messageWidth += dp((thumbsCount * (thumbSize + 2) - 2) + 5); if (LocaleController.isRTL && !isForumCell()) { messageLeft -= dp((thumbsCount * (thumbSize + 2) - 2) + 5); } } messageLayout = new StaticLayout(messageStringFinal, currentMessagePaint, messageWidth, align, 1.0f, 0.0f, false); } spoilersPool.addAll(spoilers); spoilers.clear(); SpoilerEffect.addSpoilers(this, messageLayout, -2, -2, spoilersPool, spoilers); } catch (Exception e) { messageLayout = null; FileLog.e(e); } animatedEmojiStack = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStack, messageLayout); double widthpx; float left; if (LocaleController.isRTL) { if (nameLayout != null && nameLayout.getLineCount() > 0) { left = nameLayout.getLineLeft(0); widthpx = Math.ceil(nameLayout.getLineWidth(0)); nameLeft += dp(12); if (nameLayoutEllipsizeByGradient) { widthpx = Math.min(nameWidth, widthpx); } if ((dialogMuted || drawUnmute) && !drawVerified && drawScam == 0) { nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - dp(6) - Theme.dialogs_muteDrawable.getIntrinsicWidth()); } else if (drawVerified) { nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - dp(6) - Theme.dialogs_verifiedDrawable.getIntrinsicWidth()); } else if (drawPremium) { nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx - left) - dp(24)); } else if (drawScam != 0) { nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - dp(6) - (drawScam == 1 ? Theme.dialogs_scamDrawable : Theme.dialogs_fakeDrawable).getIntrinsicWidth()); } else { nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - dp(6) - Theme.dialogs_muteDrawable.getIntrinsicWidth()); } if (left == 0) { if (widthpx < nameWidth) { nameLeft += (nameWidth - widthpx); } } } if (messageLayout != null) { int lineCount = messageLayout.getLineCount(); if (lineCount > 0) { int w = Integer.MAX_VALUE; for (int a = 0; a < lineCount; a++) { left = messageLayout.getLineLeft(a); if (left == 0) { widthpx = Math.ceil(messageLayout.getLineWidth(a)); w = Math.min(w, (int) (messageWidth - widthpx)); } else { w = 0; break; } } if (w != Integer.MAX_VALUE) { messageLeft += w; } } } if (typingLayout != null) { int lineCount = typingLayout.getLineCount(); if (lineCount > 0) { int w = Integer.MAX_VALUE; for (int a = 0; a < lineCount; a++) { left = typingLayout.getLineLeft(a); if (left == 0) { widthpx = Math.ceil(typingLayout.getLineWidth(a)); w = Math.min(w, (int) (messageWidth - widthpx)); } else { w = 0; break; } } if (w != Integer.MAX_VALUE) { typingLeft += w; } } } if (messageNameLayout != null && messageNameLayout.getLineCount() > 0) { left = messageNameLayout.getLineLeft(0); if (left == 0) { widthpx = Math.ceil(messageNameLayout.getLineWidth(0)); if (widthpx < messageWidth) { messageNameLeft += (messageWidth - widthpx); } } } if (buttonLayout != null) { int lineCount = buttonLayout.getLineCount(); if (lineCount > 0) { int rightpad = Integer.MAX_VALUE; for (int a = 0; a < lineCount; a++) { rightpad = (int) Math.min(rightpad, buttonLayout.getWidth() - buttonLayout.getLineRight(a)); } buttonLeft += rightpad; } } } else { if (nameLayout != null && nameLayout.getLineCount() > 0) { left = nameLayout.getLineRight(0); if (nameLayoutEllipsizeByGradient) { left = Math.min(nameWidth, left); } if (left == nameWidth) { widthpx = Math.ceil(nameLayout.getLineWidth(0)); if (nameLayoutEllipsizeByGradient) { widthpx = Math.min(nameWidth, widthpx); // widthpx -= dp(36); // left += dp(36); } if (widthpx < nameWidth) { nameLeft -= (nameWidth - widthpx); } } if ((dialogMuted || true) || drawUnmute || drawVerified || drawPremium || drawScam != 0) { nameMuteLeft = (int) (nameLeft + left + dp(6)); } } if (messageLayout != null) { int lineCount = messageLayout.getLineCount(); if (lineCount > 0) { left = Integer.MAX_VALUE; for (int a = 0; a < lineCount; a++) { left = Math.min(left, messageLayout.getLineLeft(a)); } messageLeft -= left; } } if (buttonLayout != null) { int lineCount = buttonLayout.getLineCount(); if (lineCount > 0) { left = Integer.MAX_VALUE; for (int a = 0; a < lineCount; a++) { left = Math.min(left, buttonLayout.getLineLeft(a)); } buttonLeft -= left; } } if (typingLayout != null) { int lineCount = typingLayout.getLineCount(); if (lineCount > 0) { left = Integer.MAX_VALUE; for (int a = 0; a < lineCount; a++) { left = Math.min(left, typingLayout.getLineLeft(a)); } typingLeft -= left; } } if (messageNameLayout != null && messageNameLayout.getLineCount() > 0) { messageNameLeft -= messageNameLayout.getLineLeft(0); } } if (typingLayout != null && printingStringType >= 0 && typingLayout.getText().length() > 0) { float x1, x2; if (printingStringReplaceIndex >= 0 && printingStringReplaceIndex + 1 < typingLayout.getText().length() ){ x1 = typingLayout.getPrimaryHorizontal(printingStringReplaceIndex); x2 = typingLayout.getPrimaryHorizontal(printingStringReplaceIndex + 1); } else { x1 = typingLayout.getPrimaryHorizontal(0); x2 = typingLayout.getPrimaryHorizontal(1); } if (x1 < x2) { statusDrawableLeft = (int) (typingLeft + x1); } else { statusDrawableLeft = (int) (typingLeft + x2 + dp(3)); } } updateThumbsPosition(); } private SpannableStringBuilder formatInternal(int messageFormatType, CharSequence s1, CharSequence s2) { SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); switch (messageFormatType) { case 1: //"%2$s: \u2068%1$s\u2069" spannableStringBuilder.append(s2).append(": \u2068").append(s1).append("\u2069"); break; case 2: //"\u2068%1$s\u2069" spannableStringBuilder.append("\u2068").append(s1).append("\u2069"); break; case 3: //"%2$s: %1$s" spannableStringBuilder.append(s2).append(": ").append(s1); break; case 4: //"%1$s" spannableStringBuilder.append(s1); break; } return spannableStringBuilder; } private void updateThumbsPosition() { if (thumbsCount > 0) { StaticLayout layout = isForumCell() ? buttonLayout : messageLayout; int left = isForumCell() ? buttonLeft : messageLeft; if (layout == null) { return; } try { CharSequence text = layout.getText(); if (text instanceof Spanned) { FixedWidthSpan[] spans = ((Spanned) text).getSpans(0, text.length(), FixedWidthSpan.class); if (spans != null && spans.length > 0) { int spanOffset = ((Spanned) text).getSpanStart(spans[0]); if (spanOffset < 0) { spanOffset = 0; } float x1 = layout.getPrimaryHorizontal(spanOffset); float x2 = layout.getPrimaryHorizontal(spanOffset + 1); int offset = (int) Math.ceil(Math.min(x1, x2)); if (offset != 0 && !drawForwardIcon) { offset += dp(3); } for (int i = 0; i < thumbsCount; ++i) { thumbImage[i].setImageX(left + offset + dp((thumbSize + 2) * i)); thumbImageSeen[i] = true; } } else { for (int i = 0; i < 3; ++i) { thumbImageSeen[i] = false; } } } } catch (Exception e) { FileLog.e(e); } } } private CharSequence applyThumbs(CharSequence string) { if (thumbsCount > 0) { SpannableStringBuilder builder = SpannableStringBuilder.valueOf(string); builder.insert(0, " "); builder.setSpan(new FixedWidthSpan(dp((thumbSize + 2) * thumbsCount - 2 + 5)), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return builder; } return string; } int topMessageTopicStartIndex; int topMessageTopicEndIndex; private CharSequence formatTopicsNames() { ForumFormattedNames forumFormattedNames = null; if (sharedResources != null) { forumFormattedNames = sharedResources.formattedTopicNames.get(getDialogId()); } if (forumFormattedNames == null) { forumFormattedNames = new ForumFormattedNames(); if (sharedResources != null) { sharedResources.formattedTopicNames.put(getDialogId(), forumFormattedNames); } } forumFormattedNames.formatTopicsNames(currentAccount, message, chat); topMessageTopicStartIndex = forumFormattedNames.topMessageTopicStartIndex; topMessageTopicEndIndex = forumFormattedNames.topMessageTopicEndIndex; lastTopicMessageUnread = forumFormattedNames.lastTopicMessageUnread; return forumFormattedNames.formattedNames; } public boolean isForumCell() { return !isDialogFolder() && chat != null && chat.forum && !isTopic; } private void drawCheckStatus(Canvas canvas, boolean drawClock, boolean drawCheck1, boolean drawCheck2, boolean moveCheck, float alpha) { if (alpha == 0 && !moveCheck) { return; } float scale = 0.5f + 0.5f * alpha; if (drawClock) { setDrawableBounds(Theme.dialogs_clockDrawable, clockDrawLeft, checkDrawTop); if (alpha != 1f) { canvas.save(); canvas.scale(scale, scale, Theme.dialogs_clockDrawable.getBounds().centerX(), Theme.dialogs_halfCheckDrawable.getBounds().centerY()); Theme.dialogs_clockDrawable.setAlpha((int) (255 * alpha)); } Theme.dialogs_clockDrawable.draw(canvas); if (alpha != 1f) { canvas.restore(); Theme.dialogs_clockDrawable.setAlpha(255); } invalidate(); } else if (drawCheck2) { if (drawCheck1) { setDrawableBounds(Theme.dialogs_halfCheckDrawable, halfCheckDrawLeft, checkDrawTop); if (moveCheck) { canvas.save(); canvas.scale(scale, scale, Theme.dialogs_halfCheckDrawable.getBounds().centerX(), Theme.dialogs_halfCheckDrawable.getBounds().centerY()); Theme.dialogs_halfCheckDrawable.setAlpha((int) (255 * alpha)); } if (!moveCheck && alpha != 0) { canvas.save(); canvas.scale(scale, scale, Theme.dialogs_halfCheckDrawable.getBounds().centerX(), Theme.dialogs_halfCheckDrawable.getBounds().centerY()); Theme.dialogs_halfCheckDrawable.setAlpha((int) (255 * alpha)); Theme.dialogs_checkReadDrawable.setAlpha((int) (255 * alpha)); } Theme.dialogs_halfCheckDrawable.draw(canvas); if (moveCheck) { canvas.restore(); canvas.save(); canvas.translate(dp(4) * (1f - alpha), 0); } setDrawableBounds(Theme.dialogs_checkReadDrawable, checkDrawLeft, checkDrawTop); Theme.dialogs_checkReadDrawable.draw(canvas); if (moveCheck) { canvas.restore(); Theme.dialogs_halfCheckDrawable.setAlpha(255); } if (!moveCheck && alpha != 0) { canvas.restore(); Theme.dialogs_halfCheckDrawable.setAlpha(255); Theme.dialogs_checkReadDrawable.setAlpha(255); } } else { setDrawableBounds(Theme.dialogs_checkDrawable, checkDrawLeft1, checkDrawTop); if (alpha != 1f) { canvas.save(); canvas.scale(scale, scale, Theme.dialogs_checkDrawable.getBounds().centerX(), Theme.dialogs_halfCheckDrawable.getBounds().centerY()); Theme.dialogs_checkDrawable.setAlpha((int) (255 * alpha)); } Theme.dialogs_checkDrawable.draw(canvas); if (alpha != 1f) { canvas.restore(); Theme.dialogs_checkDrawable.setAlpha(255); } } } } public boolean isPointInsideAvatar(float x, float y) { if (!LocaleController.isRTL) { return x >= 0 && x < dp(60); } else { return x >= getMeasuredWidth() - dp(60) && x < getMeasuredWidth(); } } public void setDialogSelected(boolean value) { if (isSelected != value) { invalidate(); } isSelected = value; } public boolean checkCurrentDialogIndex(boolean frozen) { return false; } public void animateArchiveAvatar() { if (avatarDrawable.getAvatarType() != AvatarDrawable.AVATAR_TYPE_ARCHIVED) { return; } animatingArchiveAvatar = true; animatingArchiveAvatarProgress = 0.0f; Theme.dialogs_archiveAvatarDrawable.setProgress(0.0f); Theme.dialogs_archiveAvatarDrawable.start(); invalidate(); } public void setChecked(boolean checked, boolean animated) { if (checkBox == null && !checked) { return; } if (checkBox == null) { checkBox = new CheckBox2(getContext(), 21, resourcesProvider) { @Override public void invalidate() { super.invalidate(); DialogCell.this.invalidate(); } }; checkBox.setColor(-1, Theme.key_windowBackgroundWhite, Theme.key_checkboxCheck); checkBox.setDrawUnchecked(false); checkBox.setDrawBackgroundAsArc(3); addView(checkBox); } checkBox.setChecked(checked, animated); checkTtl(); } private MessageObject findFolderTopMessage() { if (parentFragment == null) { return null; } MessageObject maxMessage = null; ArrayList<TLRPC.Dialog> dialogs = parentFragment.getDialogsArray(currentAccount, dialogsType, currentDialogFolderId, false); if (dialogs != null && !dialogs.isEmpty()) { for (int a = 0, N = dialogs.size(); a < N; a++) { TLRPC.Dialog dialog = dialogs.get(a); LongSparseArray<ArrayList<MessageObject>> dialogMessage = MessagesController.getInstance(currentAccount).dialogMessage; if (dialogMessage != null) { ArrayList<MessageObject> groupMessages = dialogMessage.get(dialog.id); MessageObject object = groupMessages != null && !groupMessages.isEmpty() ? groupMessages.get(0) : null; if (object != null && (maxMessage == null || object.messageOwner.date > maxMessage.messageOwner.date)) { maxMessage = object; } if (dialog.pinnedNum == 0 && maxMessage != null) { break; } } } } return maxMessage; } public boolean isFolderCell() { return currentDialogFolderId != 0; } public boolean update(int mask) { return update(mask, true); } public boolean update(int mask, boolean animated) { boolean requestLayout = false; boolean rebuildLayout = false; boolean invalidate = false; boolean oldIsForumCell = isForumCell(); drawAvatarSelector = false; ttlPeriod = 0; if (customDialog != null) { lastMessageDate = customDialog.date; lastUnreadState = customDialog.unread_count != 0; unreadCount = customDialog.unread_count; drawPin = customDialog.pinned; dialogMuted = customDialog.muted; hasUnmutedTopics = false; avatarDrawable.setInfo(customDialog.id, customDialog.name, null); avatarImage.setImage(null, "50_50", avatarDrawable, null, 0); for (int i = 0; i < thumbImage.length; ++i) { thumbImage[i].setImageBitmap((BitmapDrawable) null); } avatarImage.setRoundRadius(dp(28)); drawUnmute = false; } else { int oldUnreadCount = unreadCount; boolean oldHasReactionsMentions = reactionMentionCount != 0; boolean oldMarkUnread = markUnread; hasUnmutedTopics = false; readOutboxMaxId = -1; if (isDialogCell) { TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(currentDialogId); if (dialog != null) { readOutboxMaxId = dialog.read_outbox_max_id; ttlPeriod = dialog.ttl_period; if (mask == 0) { clearingDialog = MessagesController.getInstance(currentAccount).isClearingDialog(dialog.id); groupMessages = MessagesController.getInstance(currentAccount).dialogMessage.get(dialog.id); message = groupMessages != null && groupMessages.size() > 0 ? groupMessages.get(0) : null; lastUnreadState = message != null && message.isUnread(); TLRPC.Chat localChat = MessagesController.getInstance(currentAccount).getChat(-dialog.id); boolean isForumCell = localChat != null && localChat.forum && !isTopic; if (localChat != null && localChat.forum) { int[] counts = MessagesController.getInstance(currentAccount).getTopicsController().getForumUnreadCount(localChat.id); unreadCount = counts[0]; mentionCount = counts[1]; reactionMentionCount = counts[2]; hasUnmutedTopics = counts[3] != 0; } else if (dialog instanceof TLRPC.TL_dialogFolder) { unreadCount = MessagesStorage.getInstance(currentAccount).getArchiveUnreadCount(); mentionCount = 0; reactionMentionCount = 0; } else { unreadCount = dialog.unread_count; mentionCount = dialog.unread_mentions_count; reactionMentionCount = dialog.unread_reactions_count; } markUnread = dialog.unread_mark; currentEditDate = message != null ? message.messageOwner.edit_date : 0; lastMessageDate = dialog.last_message_date; if (dialogsType == 7 || dialogsType == 8) { MessagesController.DialogFilter filter = MessagesController.getInstance(currentAccount).selectedDialogFilter[dialogsType == 8 ? 1 : 0]; drawPin = filter != null && filter.pinnedDialogs.indexOfKey(dialog.id) >= 0; } else { drawPin = currentDialogFolderId == 0 && dialog.pinned; } if (message != null) { lastSendState = message.messageOwner.send_state; } } } else { unreadCount = 0; mentionCount = 0; reactionMentionCount = 0; currentEditDate = 0; lastMessageDate = 0; clearingDialog = false; } drawAvatarSelector = currentDialogId != 0 && currentDialogId == RightSlidingDialogContainer.fragmentDialogId; } else { drawPin = false; } if (forumTopic != null) { unreadCount = forumTopic.unread_count; mentionCount = forumTopic.unread_mentions_count; reactionMentionCount = forumTopic.unread_reactions_count; } if (dialogsType == DialogsActivity.DIALOGS_TYPE_ADD_USERS_TO) { drawPin = false; } if (tags != null) { final boolean tagsWereEmpty = tags.isEmpty(); if (tags.update(currentAccount, dialogsType, currentDialogId)) { if (tagsWereEmpty != tags.isEmpty()) { rebuildLayout = true; requestLayout = true; } invalidate = true; } } if (mask != 0) { boolean continueUpdate = false; if (user != null && !MessagesController.isSupportUser(user) && !user.bot && (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { user = MessagesController.getInstance(currentAccount).getUser(user.id); if (wasDrawnOnline != isOnline()) { invalidate = true; } } if ((mask & MessagesController.UPDATE_MASK_EMOJI_STATUS) != 0) { if (user != null) { user = MessagesController.getInstance(currentAccount).getUser(user.id); if (user != null && DialogObject.getEmojiStatusDocumentId(user.emoji_status) != 0) { nameLayoutEllipsizeByGradient = true; emojiStatus.set(DialogObject.getEmojiStatusDocumentId(user.emoji_status), animated); } else { nameLayoutEllipsizeByGradient = true; emojiStatus.set(PremiumGradient.getInstance().premiumStarDrawableMini, animated); } invalidate = true; } if (chat != null) { chat = MessagesController.getInstance(currentAccount).getChat(chat.id); if (chat != null && DialogObject.getEmojiStatusDocumentId(chat.emoji_status) != 0) { nameLayoutEllipsizeByGradient = true; emojiStatus.set(DialogObject.getEmojiStatusDocumentId(chat.emoji_status), animated); } else { nameLayoutEllipsizeByGradient = true; emojiStatus.set(PremiumGradient.getInstance().premiumStarDrawableMini, animated); } invalidate = true; } } if (isDialogCell || isTopic) { if ((mask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) { CharSequence printString = MessagesController.getInstance(currentAccount).getPrintingString(currentDialogId, getTopicId(), true); if (lastPrintString != null && printString == null || lastPrintString == null && printString != null || lastPrintString != null && !lastPrintString.equals(printString)) { continueUpdate = true; } } } if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_MESSAGE_TEXT) != 0) { if (message != null && message.messageText != lastMessageString) { continueUpdate = true; } } if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_CHAT) != 0 && chat != null) { TLRPC.Chat newChat = MessagesController.getInstance(currentAccount).getChat(chat.id); if ((newChat != null && newChat.call_active && newChat.call_not_empty) != hasCall) { continueUpdate = true; } } if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_AVATAR) != 0) { if (chat == null) { continueUpdate = true; } } if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_NAME) != 0) { if (chat == null) { continueUpdate = true; } } if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0) { if (user == null) { continueUpdate = true; } } if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0) { if (user == null) { continueUpdate = true; } } if (!continueUpdate) { if (message != null && lastUnreadState != message.isUnread()) { lastUnreadState = message.isUnread(); continueUpdate = true; } if (isDialogCell) { TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(currentDialogId); int newCount; int newMentionCount; int newReactionCout = 0; TLRPC.Chat localChat = dialog == null ? null : MessagesController.getInstance(currentAccount).getChat(-dialog.id); if (localChat != null && localChat.forum) { int[] counts = MessagesController.getInstance(currentAccount).getTopicsController().getForumUnreadCount(localChat.id); newCount = counts[0]; newMentionCount = counts[1]; newReactionCout = counts[2]; hasUnmutedTopics = counts[3] != 0; } else if (dialog instanceof TLRPC.TL_dialogFolder) { newCount = MessagesStorage.getInstance(currentAccount).getArchiveUnreadCount(); newMentionCount = 0; } else if (dialog != null) { newCount = dialog.unread_count; newMentionCount = dialog.unread_mentions_count; newReactionCout = dialog.unread_reactions_count; } else { newCount = 0; newMentionCount = 0; } if (dialog != null && (unreadCount != newCount || markUnread != dialog.unread_mark || mentionCount != newMentionCount || reactionMentionCount != newReactionCout)) { unreadCount = newCount; mentionCount = newMentionCount; markUnread = dialog.unread_mark; reactionMentionCount = newReactionCout; continueUpdate = true; } } } if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_SEND_STATE) != 0) { if (message != null && lastSendState != message.messageOwner.send_state) { lastSendState = message.messageOwner.send_state; continueUpdate = true; } } if (!continueUpdate) { //if (invalidate) { invalidate(); // } return requestLayout; } } user = null; chat = null; encryptedChat = null; long dialogId; if (currentDialogFolderId != 0) { dialogMuted = false; drawUnmute = false; message = findFolderTopMessage(); if (message != null) { dialogId = message.getDialogId(); } else { dialogId = 0; } } else { drawUnmute = false; if (forumTopic != null) { boolean allDialogMuted = MessagesController.getInstance(currentAccount).isDialogMuted(currentDialogId, 0); topicMuted = MessagesController.getInstance(currentAccount).isDialogMuted(currentDialogId, forumTopic.id); if (allDialogMuted == topicMuted) { dialogMuted = false; drawUnmute = false; } else { dialogMuted = topicMuted; drawUnmute = !topicMuted; } } else { dialogMuted = isDialogCell && MessagesController.getInstance(currentAccount).isDialogMuted(currentDialogId, getTopicId()); } dialogId = currentDialogId; } if (dialogId != 0) { if (DialogObject.isEncryptedDialog(dialogId)) { encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); if (encryptedChat != null) { user = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id); } } else if (DialogObject.isUserDialog(dialogId)) { user = MessagesController.getInstance(currentAccount).getUser(dialogId); } else { chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (!isDialogCell && chat != null && chat.migrated_to != null) { TLRPC.Chat chat2 = MessagesController.getInstance(currentAccount).getChat(chat.migrated_to.channel_id); if (chat2 != null) { chat = chat2; } } } if (useMeForMyMessages && user != null && message.isOutOwner()) { user = MessagesController.getInstance(currentAccount).getUser(UserConfig.getInstance(currentAccount).clientUserId); } } if (currentDialogFolderId != 0) { Theme.dialogs_archiveAvatarDrawable.setCallback(this); avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_ARCHIVED); avatarImage.setImage(null, null, avatarDrawable, null, user, 0); } else { if (useFromUserAsAvatar && message != null) { avatarDrawable.setInfo(currentAccount, message.getFromPeerObject()); avatarImage.setForUserOrChat(message.getFromPeerObject(), avatarDrawable); } else if (user != null) { avatarDrawable.setInfo(currentAccount, user); if (UserObject.isReplyUser(user)) { avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_REPLIES); avatarImage.setImage(null, null, avatarDrawable, null, user, 0); } else if (UserObject.isAnonymous(user)) { avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_ANONYMOUS); avatarImage.setImage(null, null, avatarDrawable, null, user, 0); } else if (UserObject.isUserSelf(user) && isSavedDialog) { avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_MY_NOTES); avatarImage.setImage(null, null, avatarDrawable, null, user, 0); } else if (UserObject.isUserSelf(user) && !useMeForMyMessages) { avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_SAVED); avatarImage.setImage(null, null, avatarDrawable, null, user, 0); } else { avatarImage.setForUserOrChat(user, avatarDrawable, null, true, VectorAvatarThumbDrawable.TYPE_SMALL, false); } } else if (chat != null) { avatarDrawable.setInfo(currentAccount, chat); avatarImage.setForUserOrChat(chat, avatarDrawable); } } if (animated && (oldUnreadCount != unreadCount || oldMarkUnread != markUnread) && (!isDialogCell || (System.currentTimeMillis() - lastDialogChangedTime) > 100)) { if (countAnimator != null) { countAnimator.cancel(); } countAnimator = ValueAnimator.ofFloat(0, 1f); countAnimator.addUpdateListener(valueAnimator -> { countChangeProgress = (float) valueAnimator.getAnimatedValue(); invalidate(); }); countAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { countChangeProgress = 1f; countOldLayout = null; countAnimationStableLayout = null; countAnimationInLayout = null; invalidate(); } }); if ((oldUnreadCount == 0 || markUnread) && !(!markUnread && oldMarkUnread)) { countAnimator.setDuration(220); countAnimator.setInterpolator(new OvershootInterpolator()); } else if (unreadCount == 0) { countAnimator.setDuration(150); countAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); } else { countAnimator.setDuration(430); countAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); } if (drawCount && drawCount2 && countLayout != null) { String oldStr = String.format("%d", oldUnreadCount); String newStr = String.format("%d", unreadCount); if (oldStr.length() == newStr.length()) { SpannableStringBuilder oldSpannableStr = new SpannableStringBuilder(oldStr); SpannableStringBuilder newSpannableStr = new SpannableStringBuilder(newStr); SpannableStringBuilder stableStr = new SpannableStringBuilder(newStr); for (int i = 0; i < oldStr.length(); i++) { if (oldStr.charAt(i) == newStr.charAt(i)) { oldSpannableStr.setSpan(new EmptyStubSpan(), i, i + 1, 0); newSpannableStr.setSpan(new EmptyStubSpan(), i, i + 1, 0); } else { stableStr.setSpan(new EmptyStubSpan(), i, i + 1, 0); } } int countOldWidth = Math.max(dp(12), (int) Math.ceil(Theme.dialogs_countTextPaint.measureText(oldStr))); countOldLayout = new StaticLayout(oldSpannableStr, Theme.dialogs_countTextPaint, countOldWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); countAnimationStableLayout = new StaticLayout(stableStr, Theme.dialogs_countTextPaint, countOldWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); countAnimationInLayout = new StaticLayout(newSpannableStr, Theme.dialogs_countTextPaint, countOldWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); } else { countOldLayout = countLayout; } } countWidthOld = countWidth; countLeftOld = countLeft; countAnimationIncrement = unreadCount > oldUnreadCount; countAnimator.start(); } boolean newHasReactionsMentions = reactionMentionCount != 0; if (animated && (newHasReactionsMentions != oldHasReactionsMentions)) { if (reactionsMentionsAnimator != null) { reactionsMentionsAnimator.cancel(); } reactionsMentionsChangeProgress = 0; reactionsMentionsAnimator = ValueAnimator.ofFloat(0, 1f); reactionsMentionsAnimator.addUpdateListener(valueAnimator -> { reactionsMentionsChangeProgress = (float) valueAnimator.getAnimatedValue(); invalidate(); }); reactionsMentionsAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { reactionsMentionsChangeProgress = 1f; invalidate(); } }); if (newHasReactionsMentions) { reactionsMentionsAnimator.setDuration(220); reactionsMentionsAnimator.setInterpolator(new OvershootInterpolator()); } else { reactionsMentionsAnimator.setDuration(150); reactionsMentionsAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); } reactionsMentionsAnimator.start(); } avatarImage.setRoundRadius(chat != null && chat.forum && currentDialogFolderId == 0 && !useFromUserAsAvatar || !isSavedDialog && user != null && user.self && MessagesController.getInstance(currentAccount).savedViewAsChats ? dp(16) : dp(28)); } if (!isTopic && (getMeasuredWidth() != 0 || getMeasuredHeight() != 0)) { rebuildLayout = true; } if (!invalidate) { boolean currentStoriesIsEmpty = storyParams.currentState == StoriesUtilities.STATE_EMPTY; boolean newStateStoriesIsEmpty = StoriesUtilities.getPredictiveUnreadState(MessagesController.getInstance(currentAccount).getStoriesController(), getDialogId()) == StoriesUtilities.STATE_EMPTY; if (!newStateStoriesIsEmpty || (!currentStoriesIsEmpty && newStateStoriesIsEmpty)) { invalidate = true; } } if (!animated) { dialogMutedProgress = (dialogMuted || drawUnmute) ? 1f : 0f; if (countAnimator != null) { countAnimator.cancel(); } } // if (invalidate) { invalidate(); // } if (isForumCell() != oldIsForumCell) { requestLayout = true; } if (rebuildLayout) { if (attachedToWindow) { buildLayout(); } else { updateLayout = true; } } updatePremiumBlocked(animated); return requestLayout; } private int getTopicId() { return forumTopic == null ? 0 : forumTopic.id; } @Override public float getTranslationX() { return translationX; } @Override public void setTranslationX(float value) { if (value == translationX) { return; } translationX = value; if (translationDrawable != null && translationX == 0) { translationDrawable.setProgress(0.0f); translationAnimationStarted = false; archiveHidden = SharedConfig.archiveHidden; currentRevealProgress = 0; isSliding = false; } if (translationX != 0) { isSliding = true; } else { currentRevealBounceProgress = 0f; currentRevealProgress = 0f; drawRevealBackground = false; } if (isSliding && !swipeCanceled) { boolean prevValue = drawRevealBackground; drawRevealBackground = Math.abs(translationX) >= getMeasuredWidth() * 0.45f; if (prevValue != drawRevealBackground && archiveHidden == SharedConfig.archiveHidden) { try { performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); } catch (Exception ignore) {} } } invalidate(); } @SuppressLint("DrawAllocation") @Override protected void onDraw(Canvas canvas) { if (currentDialogId == 0 && customDialog == null) { return; } if (!visibleOnScreen && !drawingForBlur) { return; } boolean needInvalidate = false; if (drawArchive && (currentDialogFolderId != 0 || isTopic && forumTopic != null && forumTopic.id == 1) && archivedChatsDrawable != null && archivedChatsDrawable.outProgress == 0.0f && translationX == 0.0f) { if (!drawingForBlur) { canvas.save(); canvas.translate(0, -translateY - rightFragmentOffset); canvas.clipRect(0, 0, getMeasuredWidth(), getMeasuredHeight()); archivedChatsDrawable.draw(canvas); canvas.restore(); } return; } if (clipProgress != 0.0f && Build.VERSION.SDK_INT != 24) { canvas.save(); canvas.clipRect(0, topClip * clipProgress, getMeasuredWidth(), getMeasuredHeight() - (int) (bottomClip * clipProgress)); } int backgroundColor = 0; if (translationX != 0 || cornerProgress != 0.0f) { canvas.save(); canvas.translate(0, -translateY); String swipeMessage; int revealBackgroundColor; int swipeMessageStringId; if (overrideSwipeAction) { backgroundColor = Theme.getColor(overrideSwipeActionBackgroundColorKey, resourcesProvider); revealBackgroundColor = Theme.getColor(overrideSwipeActionRevealBackgroundColorKey, resourcesProvider); swipeMessage = LocaleController.getString(overrideSwipeActionStringKey, swipeMessageStringId = overrideSwipeActionStringId); translationDrawable = overrideSwipeActionDrawable; } else if (currentDialogFolderId != 0) { if (archiveHidden) { backgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider); revealBackgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider); swipeMessage = LocaleController.getString("UnhideFromTop", swipeMessageStringId = R.string.UnhideFromTop); translationDrawable = Theme.dialogs_unpinArchiveDrawable; } else { backgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider); revealBackgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider); swipeMessage = LocaleController.getString("HideOnTop", swipeMessageStringId = R.string.HideOnTop); translationDrawable = Theme.dialogs_pinArchiveDrawable; } } else { if (promoDialog) { backgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider); revealBackgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider); swipeMessage = LocaleController.getString("PsaHide", swipeMessageStringId = R.string.PsaHide); translationDrawable = Theme.dialogs_hidePsaDrawable; } else if (folderId == 0) { backgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider); revealBackgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider); if (SharedConfig.getChatSwipeAction(currentAccount) == SwipeGestureSettingsView.SWIPE_GESTURE_MUTE) { if (dialogMuted) { swipeMessage = LocaleController.getString("SwipeUnmute", swipeMessageStringId = R.string.SwipeUnmute); translationDrawable = Theme.dialogs_swipeUnmuteDrawable; } else { swipeMessage = LocaleController.getString("SwipeMute", swipeMessageStringId = R.string.SwipeMute); translationDrawable = Theme.dialogs_swipeMuteDrawable; } } else if (SharedConfig.getChatSwipeAction(currentAccount) == SwipeGestureSettingsView.SWIPE_GESTURE_DELETE) { swipeMessage = LocaleController.getString("SwipeDeleteChat", swipeMessageStringId = R.string.SwipeDeleteChat); backgroundColor = Theme.getColor(Theme.key_dialogSwipeRemove, resourcesProvider); translationDrawable = Theme.dialogs_swipeDeleteDrawable; } else if (SharedConfig.getChatSwipeAction(currentAccount) == SwipeGestureSettingsView.SWIPE_GESTURE_READ) { if (unreadCount > 0 || markUnread) { swipeMessage = LocaleController.getString("SwipeMarkAsRead", swipeMessageStringId = R.string.SwipeMarkAsRead); translationDrawable = Theme.dialogs_swipeReadDrawable; } else { swipeMessage = LocaleController.getString("SwipeMarkAsUnread", swipeMessageStringId = R.string.SwipeMarkAsUnread); translationDrawable = Theme.dialogs_swipeUnreadDrawable; } } else if (SharedConfig.getChatSwipeAction(currentAccount) == SwipeGestureSettingsView.SWIPE_GESTURE_PIN) { if (getIsPinned()) { swipeMessage = LocaleController.getString("SwipeUnpin", swipeMessageStringId = R.string.SwipeUnpin); translationDrawable = Theme.dialogs_swipeUnpinDrawable; } else { swipeMessage = LocaleController.getString("SwipePin", swipeMessageStringId = R.string.SwipePin); translationDrawable = Theme.dialogs_swipePinDrawable; } } else { swipeMessage = LocaleController.getString("Archive", swipeMessageStringId = R.string.Archive); translationDrawable = Theme.dialogs_archiveDrawable; } } else { backgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider); revealBackgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider); swipeMessage = LocaleController.getString("Unarchive", swipeMessageStringId = R.string.Unarchive); translationDrawable = Theme.dialogs_unarchiveDrawable; } } if (swipeCanceled && lastDrawTranslationDrawable != null) { translationDrawable = lastDrawTranslationDrawable; swipeMessageStringId = lastDrawSwipeMessageStringId; } else { lastDrawTranslationDrawable = translationDrawable; lastDrawSwipeMessageStringId = swipeMessageStringId; } if (!translationAnimationStarted && Math.abs(translationX) > dp(43)) { translationAnimationStarted = true; translationDrawable.setProgress(0.0f); translationDrawable.setCallback(this); translationDrawable.start(); } float tx = getMeasuredWidth() + translationX; if (currentRevealProgress < 1.0f) { Theme.dialogs_pinnedPaint.setColor(backgroundColor); canvas.drawRect(tx - dp(8), 0, getMeasuredWidth(), getMeasuredHeight(), Theme.dialogs_pinnedPaint); if (currentRevealProgress == 0) { if (Theme.dialogs_archiveDrawableRecolored) { Theme.dialogs_archiveDrawable.setLayerColor("Arrow.**", Theme.getNonAnimatedColor(Theme.key_chats_archiveBackground)); Theme.dialogs_archiveDrawableRecolored = false; } if (Theme.dialogs_hidePsaDrawableRecolored) { Theme.dialogs_hidePsaDrawable.beginApplyLayerColors(); Theme.dialogs_hidePsaDrawable.setLayerColor("Line 1.**", Theme.getNonAnimatedColor(Theme.key_chats_archiveBackground)); Theme.dialogs_hidePsaDrawable.setLayerColor("Line 2.**", Theme.getNonAnimatedColor(Theme.key_chats_archiveBackground)); Theme.dialogs_hidePsaDrawable.setLayerColor("Line 3.**", Theme.getNonAnimatedColor(Theme.key_chats_archiveBackground)); Theme.dialogs_hidePsaDrawable.commitApplyLayerColors(); Theme.dialogs_hidePsaDrawableRecolored = false; } } } int drawableX = getMeasuredWidth() - dp(43) - translationDrawable.getIntrinsicWidth() / 2; int drawableY = (getMeasuredHeight() - dp(54)) / 2; int drawableCx = drawableX + translationDrawable.getIntrinsicWidth() / 2; int drawableCy = drawableY + translationDrawable.getIntrinsicHeight() / 2; if (currentRevealProgress > 0.0f) { canvas.save(); canvas.clipRect(tx - dp(8), 0, getMeasuredWidth(), getMeasuredHeight()); Theme.dialogs_pinnedPaint.setColor(revealBackgroundColor); float rad = (float) Math.sqrt(drawableCx * drawableCx + (drawableCy - getMeasuredHeight()) * (drawableCy - getMeasuredHeight())); canvas.drawCircle(drawableCx, drawableCy, rad * AndroidUtilities.accelerateInterpolator.getInterpolation(currentRevealProgress), Theme.dialogs_pinnedPaint); canvas.restore(); if (!Theme.dialogs_archiveDrawableRecolored) { Theme.dialogs_archiveDrawable.setLayerColor("Arrow.**", Theme.getNonAnimatedColor(Theme.key_chats_archivePinBackground)); Theme.dialogs_archiveDrawableRecolored = true; } if (!Theme.dialogs_hidePsaDrawableRecolored) { Theme.dialogs_hidePsaDrawable.beginApplyLayerColors(); Theme.dialogs_hidePsaDrawable.setLayerColor("Line 1.**", Theme.getNonAnimatedColor(Theme.key_chats_archivePinBackground)); Theme.dialogs_hidePsaDrawable.setLayerColor("Line 2.**", Theme.getNonAnimatedColor(Theme.key_chats_archivePinBackground)); Theme.dialogs_hidePsaDrawable.setLayerColor("Line 3.**", Theme.getNonAnimatedColor(Theme.key_chats_archivePinBackground)); Theme.dialogs_hidePsaDrawable.commitApplyLayerColors(); Theme.dialogs_hidePsaDrawableRecolored = true; } } canvas.save(); canvas.translate(drawableX, drawableY); if (currentRevealBounceProgress != 0.0f && currentRevealBounceProgress != 1.0f) { float scale = 1.0f + interpolator.getInterpolation(currentRevealBounceProgress); canvas.scale(scale, scale, translationDrawable.getIntrinsicWidth() / 2, translationDrawable.getIntrinsicHeight() / 2); } setDrawableBounds(translationDrawable, 0, 0); translationDrawable.draw(canvas); canvas.restore(); canvas.clipRect(tx, 0, getMeasuredWidth(), getMeasuredHeight()); int width = (int) Math.ceil(Theme.dialogs_countTextPaint.measureText(swipeMessage)); if (swipeMessageTextId != swipeMessageStringId || swipeMessageWidth != getMeasuredWidth()) { swipeMessageTextId = swipeMessageStringId; swipeMessageWidth = getMeasuredWidth(); swipeMessageTextLayout = new StaticLayout(swipeMessage, Theme.dialogs_archiveTextPaint, Math.min(dp(80), width), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); if (swipeMessageTextLayout.getLineCount() > 1) { swipeMessageTextLayout = new StaticLayout(swipeMessage, Theme.dialogs_archiveTextPaintSmall, Math.min(dp(82), width), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); } } if (swipeMessageTextLayout != null) { canvas.save(); float yOffset = swipeMessageTextLayout.getLineCount() > 1 ? -dp(4) : 0; canvas.translate(getMeasuredWidth() - dp(43) - swipeMessageTextLayout.getWidth() / 2f, drawableY + dp(54 - 16) + yOffset); swipeMessageTextLayout.draw(canvas); canvas.restore(); } canvas.restore(); } else if (translationDrawable != null) { translationDrawable.stop(); translationDrawable.setProgress(0.0f); translationDrawable.setCallback(null); translationDrawable = null; translationAnimationStarted = false; } if (translationX != 0) { canvas.save(); canvas.translate(translationX, 0); } float cornersRadius = dp(8) * cornerProgress; if (isSelected) { rect.set(0, 0, getMeasuredWidth(), AndroidUtilities.lerp(getMeasuredHeight(), getCollapsedHeight(), rightFragmentOpenedProgress)); rect.offset(0, -translateY + collapseOffset); canvas.drawRoundRect(rect, cornersRadius, cornersRadius, Theme.dialogs_tabletSeletedPaint); } canvas.save(); canvas.translate(0, -rightFragmentOffset * rightFragmentOpenedProgress); if (currentDialogFolderId != 0 && (!SharedConfig.archiveHidden || archiveBackgroundProgress != 0)) { Theme.dialogs_pinnedPaint.setColor(AndroidUtilities.getOffsetColor(0, Theme.getColor(Theme.key_chats_pinnedOverlay, resourcesProvider), archiveBackgroundProgress, 1.0f)); Theme.dialogs_pinnedPaint.setAlpha((int) (Theme.dialogs_pinnedPaint.getAlpha() * (1f - rightFragmentOpenedProgress))); canvas.drawRect(-xOffset, 0, getMeasuredWidth(), getMeasuredHeight() - translateY, Theme.dialogs_pinnedPaint); } else if (getIsPinned() || drawPinBackground) { Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_chats_pinnedOverlay, resourcesProvider)); Theme.dialogs_pinnedPaint.setAlpha((int) (Theme.dialogs_pinnedPaint.getAlpha() * (1f - rightFragmentOpenedProgress))); canvas.drawRect(-xOffset, 0, getMeasuredWidth(), getMeasuredHeight() - translateY, Theme.dialogs_pinnedPaint); } canvas.restore(); updateHelper.updateAnimationValues(); if (collapseOffset != 0) { canvas.save(); canvas.translate(0, collapseOffset); } if (rightFragmentOpenedProgress != 1) { int restoreToCount = -1; if (rightFragmentOpenedProgress != 0) { float startAnimationProgress = Utilities.clamp(rightFragmentOpenedProgress / 0.4f, 1f, 0); if (SharedConfig.getDevicePerformanceClass() >= SharedConfig.PERFORMANCE_CLASS_HIGH) { restoreToCount = canvas.saveLayerAlpha(dp(RightSlidingDialogContainer.getRightPaddingSize() + 1) - dp(8) * (1f - startAnimationProgress), 0, getMeasuredWidth(), getMeasuredHeight(), (int) (255 * (1f - rightFragmentOpenedProgress)), Canvas.ALL_SAVE_FLAG); } else { restoreToCount = canvas.save(); canvas.clipRect(dp(RightSlidingDialogContainer.getRightPaddingSize() + 1) - dp(8) * (1f - startAnimationProgress), 0, getMeasuredWidth(), getMeasuredHeight()); } canvas.translate(-(getMeasuredWidth() - dp(74)) * 0.7f * rightFragmentOpenedProgress, 0); } if (translationX != 0 || cornerProgress != 0.0f) { canvas.save(); Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider)); rect.set(getMeasuredWidth() - dp(64), 0, getMeasuredWidth(), getMeasuredHeight()); rect.offset(0, -translateY); canvas.drawRoundRect(rect, cornersRadius, cornersRadius, Theme.dialogs_pinnedPaint); if (isSelected) { canvas.drawRoundRect(rect, cornersRadius, cornersRadius, Theme.dialogs_tabletSeletedPaint); } if (currentDialogFolderId != 0 && (!SharedConfig.archiveHidden || archiveBackgroundProgress != 0)) { Theme.dialogs_pinnedPaint.setColor(AndroidUtilities.getOffsetColor(0, Theme.getColor(Theme.key_chats_pinnedOverlay, resourcesProvider), archiveBackgroundProgress, 1.0f)); Theme.dialogs_pinnedPaint.setAlpha((int) (Theme.dialogs_pinnedPaint.getAlpha() * (1f - rightFragmentOpenedProgress))); canvas.drawRoundRect(rect, cornersRadius, cornersRadius, Theme.dialogs_pinnedPaint); } else if (getIsPinned() || drawPinBackground) { Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_chats_pinnedOverlay, resourcesProvider)); Theme.dialogs_pinnedPaint.setAlpha((int) (Theme.dialogs_pinnedPaint.getAlpha() * (1f - rightFragmentOpenedProgress))); canvas.drawRoundRect(rect, cornersRadius, cornersRadius, Theme.dialogs_pinnedPaint); } canvas.restore(); } if (translationX != 0) { if (cornerProgress < 1.0f) { cornerProgress += 16f / 150.0f; if (cornerProgress > 1.0f) { cornerProgress = 1.0f; } needInvalidate = true; } } else if (cornerProgress > 0.0f) { cornerProgress -= 16f / 150.0f; if (cornerProgress < 0.0f) { cornerProgress = 0.0f; } needInvalidate = true; } if (drawNameLock) { setDrawableBounds(Theme.dialogs_lockDrawable, nameLockLeft, nameLockTop); Theme.dialogs_lockDrawable.draw(canvas); } int nameTop = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 13); if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) { nameTop -= dp(isForumCell() ? 8 : 9); } if (nameLayout != null) { if (nameLayoutEllipsizeByGradient && !nameLayoutFits) { if (nameLayoutEllipsizeLeft && fadePaint == null) { fadePaint = new Paint(); fadePaint.setShader(new LinearGradient(0, 0, dp(24), 0, new int[]{0xffffffff, 0}, new float[]{0f, 1f}, Shader.TileMode.CLAMP)); fadePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); } else if (fadePaintBack == null) { fadePaintBack = new Paint(); fadePaintBack.setShader(new LinearGradient(0, 0, dp(24), 0, new int[]{0, 0xffffffff}, new float[]{0f, 1f}, Shader.TileMode.CLAMP)); fadePaintBack.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); } canvas.saveLayerAlpha(0, 0, getMeasuredWidth(), getMeasuredHeight(), 255, Canvas.ALL_SAVE_FLAG); canvas.clipRect(nameLeft, 0, nameLeft + nameWidth, getMeasuredHeight()); } if (currentDialogFolderId != 0) { Theme.dialogs_namePaint[paintIndex].setColor(Theme.dialogs_namePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_nameArchived, resourcesProvider)); } else if (encryptedChat != null || customDialog != null && customDialog.type == 2) { Theme.dialogs_namePaint[paintIndex].setColor(Theme.dialogs_namePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_secretName, resourcesProvider)); } else { Theme.dialogs_namePaint[paintIndex].setColor(Theme.dialogs_namePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_name, resourcesProvider)); } canvas.save(); canvas.translate(nameLeft + nameLayoutTranslateX, nameTop); SpoilerEffect.layoutDrawMaybe(nameLayout, canvas); AnimatedEmojiSpan.drawAnimatedEmojis(canvas, nameLayout, animatedEmojiStackName, -.075f, null, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(0, nameLayout.getPaint().getColor())); canvas.restore(); if (nameLayoutEllipsizeByGradient && !nameLayoutFits) { canvas.save(); if (nameLayoutEllipsizeLeft) { canvas.translate(nameLeft, 0); canvas.drawRect(0, 0, dp(24), getMeasuredHeight(), fadePaint); } else { canvas.translate(nameLeft + nameWidth - dp(24), 0); canvas.drawRect(0, 0, dp(24), getMeasuredHeight(), fadePaintBack); } canvas.restore(); canvas.restore(); } } if (timeLayout != null && currentDialogFolderId == 0) { canvas.save(); canvas.translate(timeLeft, timeTop); SpoilerEffect.layoutDrawMaybe(timeLayout, canvas); canvas.restore(); } if (drawLock2()) { Theme.dialogs_lock2Drawable.setBounds( lock2Left, timeTop + (timeLayout.getHeight() - Theme.dialogs_lock2Drawable.getIntrinsicHeight()) / 2, lock2Left + Theme.dialogs_lock2Drawable.getIntrinsicWidth(), timeTop + (timeLayout.getHeight() - Theme.dialogs_lock2Drawable.getIntrinsicHeight()) / 2 + Theme.dialogs_lock2Drawable.getIntrinsicHeight() ); Theme.dialogs_lock2Drawable.draw(canvas); } if (messageNameLayout != null && !isForumCell()) { if (currentDialogFolderId != 0) { Theme.dialogs_messageNamePaint.setColor(Theme.dialogs_messageNamePaint.linkColor = Theme.getColor(Theme.key_chats_nameMessageArchived_threeLines, resourcesProvider)); } else if (draftMessage != null) { Theme.dialogs_messageNamePaint.setColor(Theme.dialogs_messageNamePaint.linkColor = Theme.getColor(Theme.key_chats_draft, resourcesProvider)); } else { Theme.dialogs_messageNamePaint.setColor(Theme.dialogs_messageNamePaint.linkColor = Theme.getColor(Theme.key_chats_nameMessage_threeLines, resourcesProvider)); } canvas.save(); canvas.translate(messageNameLeft, messageNameTop); try { SpoilerEffect.layoutDrawMaybe(messageNameLayout, canvas); AnimatedEmojiSpan.drawAnimatedEmojis(canvas, messageNameLayout, animatedEmojiStack2, -.075f, null, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(1, messageNameLayout.getPaint().getColor())); } catch (Exception e) { FileLog.e(e); } canvas.restore(); } if (messageLayout != null) { if (currentDialogFolderId != 0) { if (chat != null) { Theme.dialogs_messagePaint[paintIndex].setColor(Theme.dialogs_messagePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_nameMessageArchived, resourcesProvider)); } else { Theme.dialogs_messagePaint[paintIndex].setColor(Theme.dialogs_messagePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_messageArchived, resourcesProvider)); } } else { Theme.dialogs_messagePaint[paintIndex].setColor(Theme.dialogs_messagePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_message, resourcesProvider)); } float top; float typingAnimationOffset = dp(14); if (updateHelper.typingOutToTop) { top = messageTop - typingAnimationOffset * updateHelper.typingProgres; } else { top = messageTop + typingAnimationOffset * updateHelper.typingProgres; } if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) { top -= dp(isForumCell() ? 10 : 11); } if (updateHelper.typingProgres != 1f) { canvas.save(); canvas.translate(messageLeft, top); int oldAlpha = messageLayout.getPaint().getAlpha(); messageLayout.getPaint().setAlpha((int) (oldAlpha * (1f - updateHelper.typingProgres))); if (!spoilers.isEmpty()) { try { canvas.save(); SpoilerEffect.clipOutCanvas(canvas, spoilers); SpoilerEffect.layoutDrawMaybe(messageLayout, canvas); AnimatedEmojiSpan.drawAnimatedEmojis(canvas, messageLayout, animatedEmojiStack, -.075f, spoilers, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(2, messageLayout.getPaint().getColor())); canvas.restore(); for (int i = 0; i < spoilers.size(); i++) { SpoilerEffect eff = spoilers.get(i); eff.setColor(messageLayout.getPaint().getColor()); eff.draw(canvas); } } catch (Exception e) { FileLog.e(e); } } else { SpoilerEffect.layoutDrawMaybe(messageLayout, canvas); AnimatedEmojiSpan.drawAnimatedEmojis(canvas, messageLayout, animatedEmojiStack, -.075f, null, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(2, messageLayout.getPaint().getColor())); } messageLayout.getPaint().setAlpha(oldAlpha); canvas.restore(); } canvas.save(); if (updateHelper.typingOutToTop) { top = messageTop + typingAnimationOffset * (1f - updateHelper.typingProgres); } else { top = messageTop - typingAnimationOffset * (1f - updateHelper.typingProgres); } if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) { top -= dp(isForumCell() ? 10 : 11); } canvas.translate(typingLeft, top); if (typingLayout != null && updateHelper.typingProgres > 0) { int oldAlpha = typingLayout.getPaint().getAlpha(); typingLayout.getPaint().setAlpha((int) (oldAlpha * updateHelper.typingProgres)); typingLayout.draw(canvas); typingLayout.getPaint().setAlpha(oldAlpha); } canvas.restore(); if (typingLayout != null && (printingStringType >= 0 || (updateHelper.typingProgres > 0 && updateHelper.lastKnownTypingType >= 0))) { int type = printingStringType >= 0 ? printingStringType : updateHelper.lastKnownTypingType; StatusDrawable statusDrawable = Theme.getChatStatusDrawable(type); if (statusDrawable != null) { canvas.save(); int color = Theme.getColor(Theme.key_chats_actionMessage); statusDrawable.setColor(ColorUtils.setAlphaComponent(color, (int) (Color.alpha(color) * updateHelper.typingProgres))); if (updateHelper.typingOutToTop) { top = messageTop + typingAnimationOffset * (1f - updateHelper.typingProgres); } else { top = messageTop - typingAnimationOffset * (1f - updateHelper.typingProgres); } if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) { top -= dp(isForumCell() ? 10 : 11); } if (type == 1 || type == 4) { canvas.translate(statusDrawableLeft, top + (type == 1 ? dp(1) : 0)); } else { canvas.translate(statusDrawableLeft, top + (dp(18) - statusDrawable.getIntrinsicHeight()) / 2f); } statusDrawable.draw(canvas); invalidate(); canvas.restore(); } } } if (buttonLayout != null) { canvas.save(); if (buttonBackgroundPaint == null) { buttonBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); } if (canvasButton == null) { canvasButton = new CanvasButton(this); canvasButton.setDelegate(() -> { if (delegate != null) { delegate.onButtonClicked(this); } }); canvasButton.setLongPress(() -> { if (delegate != null) { delegate.onButtonLongPress(this); } }); } if (lastTopicMessageUnread && topMessageTopicEndIndex != topMessageTopicStartIndex && (dialogsType == DialogsActivity.DIALOGS_TYPE_DEFAULT || dialogsType == DialogsActivity.DIALOGS_TYPE_FOLDER1 || dialogsType == DialogsActivity.DIALOGS_TYPE_FOLDER2)) { canvasButton.setColor(ColorUtils.setAlphaComponent(currentMessagePaint.getColor(), Theme.isCurrentThemeDark() ? 36 : 26)); if (!buttonCreated) { canvasButton.rewind(); if (topMessageTopicEndIndex != topMessageTopicStartIndex && topMessageTopicEndIndex > 0) { float top = messageTop; if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) { top -= dp(isForumCell() ? 10 : 11); } AndroidUtilities.rectTmp.set(messageLeft + dp(2) + messageLayout.getPrimaryHorizontal(0), top, messageLeft + messageLayout.getPrimaryHorizontal(Math.min(messageLayout.getText().length(), topMessageTopicEndIndex)) - dp(3), buttonTop - dp(4)); AndroidUtilities.rectTmp.inset(-dp(8), -dp(4)); if (AndroidUtilities.rectTmp.right > AndroidUtilities.rectTmp.left) { canvasButton.addRect(AndroidUtilities.rectTmp); } } float buttonLayoutLeft = buttonLayout.getLineLeft(0); AndroidUtilities.rectTmp.set(buttonLeft + buttonLayoutLeft + dp(2), buttonTop + dp(2), buttonLeft + buttonLayoutLeft + buttonLayout.getLineWidth(0) + dp(12), buttonTop + buttonLayout.getHeight()); AndroidUtilities.rectTmp.inset(-dp(8), -dp(3)); canvasButton.addRect(AndroidUtilities.rectTmp); } canvasButton.draw(canvas); Theme.dialogs_forum_arrowDrawable.setAlpha(125); setDrawableBounds(Theme.dialogs_forum_arrowDrawable, AndroidUtilities.rectTmp.right - dp(18), AndroidUtilities.rectTmp.top + (AndroidUtilities.rectTmp.height() - Theme.dialogs_forum_arrowDrawable.getIntrinsicHeight()) / 2f); Theme.dialogs_forum_arrowDrawable.draw(canvas); } canvas.translate(buttonLeft, buttonTop); if (!spoilers2.isEmpty()) { try { canvas.save(); SpoilerEffect.clipOutCanvas(canvas, spoilers2); SpoilerEffect.layoutDrawMaybe(buttonLayout, canvas); AnimatedEmojiSpan.drawAnimatedEmojis(canvas, buttonLayout, animatedEmojiStack3, -.075f, spoilers2, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(3, buttonLayout.getPaint().getColor())); canvas.restore(); for (int i = 0; i < spoilers2.size(); i++) { SpoilerEffect eff = spoilers2.get(i); eff.setColor(buttonLayout.getPaint().getColor()); eff.draw(canvas); } } catch (Exception e) { FileLog.e(e); } } else { SpoilerEffect.layoutDrawMaybe(buttonLayout, canvas); AnimatedEmojiSpan.drawAnimatedEmojis(canvas, buttonLayout, animatedEmojiStack3, -.075f, null, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(3, buttonLayout.getPaint().getColor())); } canvas.restore(); } if (currentDialogFolderId == 0) { int currentStatus = (drawClock ? 1 : 0) + (drawCheck1 ? 2 : 0) + (drawCheck2 ? 4 : 0); if (lastStatusDrawableParams >= 0 && lastStatusDrawableParams != currentStatus && !statusDrawableAnimationInProgress) { createStatusDrawableAnimator(lastStatusDrawableParams, currentStatus); } if (statusDrawableAnimationInProgress) { currentStatus = animateToStatusDrawableParams; } boolean drawClock = (currentStatus & 1) != 0; boolean drawCheck1 = (currentStatus & 2) != 0; boolean drawCheck2 = (currentStatus & 4) != 0; if (statusDrawableAnimationInProgress) { boolean outDrawClock = (animateFromStatusDrawableParams & 1) != 0; boolean outDrawCheck1 = (animateFromStatusDrawableParams & 2) != 0; boolean outDrawCheck2 = (animateFromStatusDrawableParams & 4) != 0; if (!drawClock && !outDrawClock && outDrawCheck2 && !outDrawCheck1 && drawCheck1 && drawCheck2) { drawCheckStatus(canvas, drawClock, drawCheck1, drawCheck2, true, statusDrawableProgress); } else { drawCheckStatus(canvas, outDrawClock, outDrawCheck1, outDrawCheck2, false, 1f - statusDrawableProgress); drawCheckStatus(canvas, drawClock, drawCheck1, drawCheck2, false, statusDrawableProgress); } } else { drawCheckStatus(canvas, drawClock, drawCheck1, drawCheck2, false,1f); } lastStatusDrawableParams = (this.drawClock ? 1 : 0) + (this.drawCheck1 ? 2 : 0) + (this.drawCheck2 ? 4 : 0); } boolean drawMuted = drawUnmute || dialogMuted; if (dialogsType != 2 && (drawMuted || dialogMutedProgress > 0) && !drawVerified && drawScam == 0 && !drawPremium) { if (drawMuted && dialogMutedProgress != 1f) { dialogMutedProgress += 16 / 150f; if (dialogMutedProgress > 1f) { dialogMutedProgress = 1f; } else { invalidate(); } } else if (!drawMuted && dialogMutedProgress != 0f) { dialogMutedProgress -= 16 / 150f; if (dialogMutedProgress < 0f) { dialogMutedProgress = 0f; } else { invalidate(); } } float muteX = nameMuteLeft - dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 0 : 1); float muteY = dp(SharedConfig.useThreeLinesLayout ? 13.5f : 17.5f); if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) { muteY -= dp(isForumCell() ? 8 : 9); } setDrawableBounds(Theme.dialogs_muteDrawable, muteX, muteY); setDrawableBounds(Theme.dialogs_unmuteDrawable, muteX, muteY); if (dialogMutedProgress != 1f) { canvas.save(); canvas.scale(dialogMutedProgress, dialogMutedProgress, Theme.dialogs_muteDrawable.getBounds().centerX(), Theme.dialogs_muteDrawable.getBounds().centerY()); if (drawUnmute) { Theme.dialogs_unmuteDrawable.setAlpha((int) (255 * dialogMutedProgress)); Theme.dialogs_unmuteDrawable.draw(canvas); Theme.dialogs_unmuteDrawable.setAlpha(255); } else { Theme.dialogs_muteDrawable.setAlpha((int) (255 * dialogMutedProgress)); Theme.dialogs_muteDrawable.draw(canvas); Theme.dialogs_muteDrawable.setAlpha(255); } canvas.restore(); } else { if (drawUnmute) { Theme.dialogs_unmuteDrawable.draw(canvas); } else { Theme.dialogs_muteDrawable.draw(canvas); } } } else if (drawVerified) { float y = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 13.5f : 16.5f); if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) { y -= dp(9); } setDrawableBounds(Theme.dialogs_verifiedDrawable, nameMuteLeft - dp(1), y); setDrawableBounds(Theme.dialogs_verifiedCheckDrawable, nameMuteLeft - dp(1), y); Theme.dialogs_verifiedDrawable.draw(canvas); Theme.dialogs_verifiedCheckDrawable.draw(canvas); } else if (drawPremium) { int y = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 12.5f : 15.5f); if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) { y -= dp(9); } if (emojiStatus != null) { emojiStatus.setBounds( nameMuteLeft - dp(2), y - dp(4), nameMuteLeft + dp(20), y - dp(4) + dp(22) ); emojiStatus.setColor(Theme.getColor(Theme.key_chats_verifiedBackground, resourcesProvider)); emojiStatus.draw(canvas); } else { Drawable premiumDrawable = PremiumGradient.getInstance().premiumStarDrawableMini; setDrawableBounds(premiumDrawable, nameMuteLeft - dp(1), dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 12.5f : 15.5f)); premiumDrawable.draw(canvas); } } else if (drawScam != 0) { int y = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 12 : 15); if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) { y -= dp(9); } setDrawableBounds((drawScam == 1 ? Theme.dialogs_scamDrawable : Theme.dialogs_fakeDrawable), nameMuteLeft, y); (drawScam == 1 ? Theme.dialogs_scamDrawable : Theme.dialogs_fakeDrawable).draw(canvas); } if (drawReorder || reorderIconProgress != 0) { Theme.dialogs_reorderDrawable.setAlpha((int) (reorderIconProgress * 255)); setDrawableBounds(Theme.dialogs_reorderDrawable, pinLeft, pinTop); Theme.dialogs_reorderDrawable.draw(canvas); } if (drawError) { Theme.dialogs_errorDrawable.setAlpha((int) ((1.0f - reorderIconProgress) * 255)); rect.set(errorLeft, errorTop, errorLeft + dp(23), errorTop + dp(23)); canvas.drawRoundRect(rect, 11.5f * AndroidUtilities.density, 11.5f * AndroidUtilities.density, Theme.dialogs_errorPaint); setDrawableBounds(Theme.dialogs_errorDrawable, errorLeft + dp(5.5f), errorTop + dp(5)); Theme.dialogs_errorDrawable.draw(canvas); } else if ((drawCount || drawMention) && drawCount2 || countChangeProgress != 1f || drawReactionMention || reactionsMentionsChangeProgress != 1f) { boolean drawCounterMuted; if (isTopic) { drawCounterMuted = topicMuted; } else { drawCounterMuted = chat != null && chat.forum && forumTopic == null ? !hasUnmutedTopics : dialogMuted; } drawCounter(canvas, drawCounterMuted, countTop, countLeft, countLeftOld, 1f, false); if (drawMention) { Theme.dialogs_countPaint.setAlpha((int) ((1.0f - reorderIconProgress) * 255)); int x = mentionLeft - dp(5.5f); rect.set(x, countTop, x + mentionWidth + dp(11), countTop + dp(23)); Paint paint = drawCounterMuted && folderId != 0 ? Theme.dialogs_countGrayPaint : Theme.dialogs_countPaint; canvas.drawRoundRect(rect, 11.5f * AndroidUtilities.density, 11.5f * AndroidUtilities.density, paint); if (mentionLayout != null) { Theme.dialogs_countTextPaint.setAlpha((int) ((1.0f - reorderIconProgress) * 255)); canvas.save(); canvas.translate(mentionLeft, countTop + dp(4)); mentionLayout.draw(canvas); canvas.restore(); } else { Theme.dialogs_mentionDrawable.setAlpha((int) ((1.0f - reorderIconProgress) * 255)); setDrawableBounds(Theme.dialogs_mentionDrawable, mentionLeft - dp(2), countTop + dp(3.2f), dp(16), dp(16)); Theme.dialogs_mentionDrawable.draw(canvas); } } if (drawReactionMention || reactionsMentionsChangeProgress != 1f) { Theme.dialogs_reactionsCountPaint.setAlpha((int) ((1.0f - reorderIconProgress) * 255)); int x = reactionMentionLeft - dp(5.5f); rect.set(x, countTop, x + dp(23), countTop + dp(23)); Paint paint = Theme.dialogs_reactionsCountPaint; canvas.save(); if (reactionsMentionsChangeProgress != 1f) { float s = drawReactionMention ? reactionsMentionsChangeProgress : (1f - reactionsMentionsChangeProgress); canvas.scale(s, s, rect.centerX(), rect.centerY()); } canvas.drawRoundRect(rect, 11.5f * AndroidUtilities.density, 11.5f * AndroidUtilities.density, paint); Theme.dialogs_reactionsMentionDrawable.setAlpha((int) ((1.0f - reorderIconProgress) * 255)); setDrawableBounds(Theme.dialogs_reactionsMentionDrawable, reactionMentionLeft - dp(2), countTop + dp(3.8f), dp(16), dp(16)); Theme.dialogs_reactionsMentionDrawable.draw(canvas); canvas.restore(); } } else if (getIsPinned()) { Theme.dialogs_pinnedDrawable.setAlpha((int) ((1.0f - reorderIconProgress) * 255)); setDrawableBounds(Theme.dialogs_pinnedDrawable, pinLeft, pinTop); Theme.dialogs_pinnedDrawable.draw(canvas); } if (thumbsCount > 0 && updateHelper.typingProgres != 1f) { float alpha = 1f; if (updateHelper.typingProgres > 0) { alpha = (1f - updateHelper.typingProgres); canvas.saveLayerAlpha(0, 0, getWidth(), getHeight(), (int) (255 * alpha), Canvas.ALL_SAVE_FLAG); float top; if (updateHelper.typingOutToTop) { top = -dp(14) * updateHelper.typingProgres; } else { top = dp(14) * updateHelper.typingProgres; } canvas.translate(0, top); } for (int i = 0; i < thumbsCount; ++i) { if (!thumbImageSeen[i]) { continue; } if (thumbBackgroundPaint == null) { thumbBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); thumbBackgroundPaint.setShadowLayer(dp(1.34f), 0, dp(0.34f), 0x18000000); thumbBackgroundPaint.setColor(0x00000000); } AndroidUtilities.rectTmp.set( thumbImage[i].getImageX(), thumbImage[i].getImageY(), thumbImage[i].getImageX2(), thumbImage[i].getImageY2() ); canvas.drawRoundRect( AndroidUtilities.rectTmp, thumbImage[i].getRoundRadius()[0], thumbImage[i].getRoundRadius()[1], thumbBackgroundPaint ); thumbImage[i].draw(canvas); if (drawSpoiler[i]) { if (thumbPath == null) { thumbPath = new Path(); } else { thumbPath.rewind(); } thumbPath.addRoundRect(AndroidUtilities.rectTmp, thumbImage[i].getRoundRadius()[0], thumbImage[i].getRoundRadius()[1], Path.Direction.CW); canvas.save(); canvas.clipPath(thumbPath); int sColor = Color.WHITE; thumbSpoiler.setColor(ColorUtils.setAlphaComponent(sColor, (int) (Color.alpha(sColor) * 0.325f))); thumbSpoiler.setBounds((int) thumbImage[i].getImageX(), (int) thumbImage[i].getImageY(), (int) thumbImage[i].getImageX2(), (int) thumbImage[i].getImageY2()); thumbSpoiler.draw(canvas); invalidate(); canvas.restore(); } if (drawPlay[i]) { int x = (int) (thumbImage[i].getCenterX() - Theme.dialogs_playDrawable.getIntrinsicWidth() / 2); int y = (int) (thumbImage[i].getCenterY() - Theme.dialogs_playDrawable.getIntrinsicHeight() / 2); setDrawableBounds(Theme.dialogs_playDrawable, x, y); Theme.dialogs_playDrawable.draw(canvas); } } if (updateHelper.typingProgres > 0) { canvas.restore(); } } if (tags != null && !tags.isEmpty()) { canvas.save(); canvas.translate(tagsLeft, getMeasuredHeight() - dp(21.66f) - (useSeparator ? 1 : 0)); tags.draw(canvas, tagsRight - tagsLeft); canvas.restore(); } if (restoreToCount != -1) { canvas.restoreToCount(restoreToCount); } } if (animatingArchiveAvatar) { canvas.save(); float scale = 1.0f + interpolator.getInterpolation(animatingArchiveAvatarProgress / 170.0f); canvas.scale(scale, scale, avatarImage.getCenterX(), avatarImage.getCenterY()); } if (drawAvatar && (!(isTopic && forumTopic != null && forumTopic.id == 1) || archivedChatsDrawable == null || !archivedChatsDrawable.isDraw())) { storyParams.drawHiddenStoriesAsSegments = currentDialogFolderId != 0; StoriesUtilities.drawAvatarWithStory(currentDialogId, canvas, avatarImage, storyParams); } if (animatingArchiveAvatar) { canvas.restore(); } if (avatarImage.getVisible()) { if (drawAvatarOverlays(canvas)) { needInvalidate = true; } } if (rightFragmentOpenedProgress > 0 && currentDialogFolderId == 0) { boolean drawCounterMuted; if (isTopic) { drawCounterMuted = topicMuted; } else { drawCounterMuted = chat != null && chat.forum && forumTopic == null ? !hasUnmutedTopics : dialogMuted; } int countLeftLocal = (int) (storyParams.originalAvatarRect.left + storyParams.originalAvatarRect.width() - countWidth - dp(5f)); int countLeftOld = (int) (storyParams.originalAvatarRect.left + storyParams.originalAvatarRect.width() - countWidthOld - dp(5f)); int countTop = (int) (avatarImage.getImageY() + storyParams.originalAvatarRect.height() - dp(22)); drawCounter(canvas, drawCounterMuted, countTop, countLeftLocal, countLeftOld, rightFragmentOpenedProgress, true); } if (collapseOffset != 0) { canvas.restore(); } if (translationX != 0) { canvas.restore(); } if (drawArchive && (currentDialogFolderId != 0 || isTopic && forumTopic != null && forumTopic.id == 1) && translationX == 0 && archivedChatsDrawable != null) { canvas.save(); canvas.translate(0, -translateY - rightFragmentOffset * rightFragmentOpenedProgress); canvas.clipRect(0, 0, getMeasuredWidth(), getMeasuredHeight()); archivedChatsDrawable.draw(canvas); canvas.restore(); } if (useSeparator) { int left; if (fullSeparator || currentDialogFolderId != 0 && archiveHidden && !fullSeparator2 || fullSeparator2 && !archiveHidden) { left = 0; } else { left = dp(messagePaddingStart); } if (rightFragmentOpenedProgress != 1) { int alpha = Theme.dividerPaint.getAlpha(); if (rightFragmentOpenedProgress != 0) { Theme.dividerPaint.setAlpha((int) (alpha * (1f - rightFragmentOpenedProgress))); } float y = getMeasuredHeight() - 1 - rightFragmentOffset * rightFragmentOpenedProgress; if (LocaleController.isRTL) { canvas.drawLine(0, y, getMeasuredWidth() - left, y, Theme.dividerPaint); } else { canvas.drawLine(left, y, getMeasuredWidth(), y, Theme.dividerPaint); } if (rightFragmentOpenedProgress != 0) { Theme.dividerPaint.setAlpha(alpha); } } } if (clipProgress != 0.0f) { if (Build.VERSION.SDK_INT != 24) { canvas.restore(); } else { Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider)); canvas.drawRect(0, 0, getMeasuredWidth(), topClip * clipProgress, Theme.dialogs_pinnedPaint); canvas.drawRect(0, getMeasuredHeight() - (int) (bottomClip * clipProgress), getMeasuredWidth(), getMeasuredHeight(), Theme.dialogs_pinnedPaint); } } if (drawReorder || reorderIconProgress != 0.0f) { if (drawReorder) { if (reorderIconProgress < 1.0f) { reorderIconProgress += 16f / 170.0f; if (reorderIconProgress > 1.0f) { reorderIconProgress = 1.0f; } needInvalidate = true; } } else { if (reorderIconProgress > 0.0f) { reorderIconProgress -= 16f / 170.0f; if (reorderIconProgress < 0.0f) { reorderIconProgress = 0.0f; } needInvalidate = true; } } } if (archiveHidden) { if (archiveBackgroundProgress > 0.0f) { archiveBackgroundProgress -= 16f / 230.0f; if (archiveBackgroundProgress < 0.0f) { archiveBackgroundProgress = 0.0f; } if (avatarDrawable.getAvatarType() == AvatarDrawable.AVATAR_TYPE_ARCHIVED) { avatarDrawable.setArchivedAvatarHiddenProgress(CubicBezierInterpolator.EASE_OUT_QUINT.getInterpolation(archiveBackgroundProgress)); } needInvalidate = true; } } else { if (archiveBackgroundProgress < 1.0f) { archiveBackgroundProgress += 16f / 230.0f; if (archiveBackgroundProgress > 1.0f) { archiveBackgroundProgress = 1.0f; } if (avatarDrawable.getAvatarType() == AvatarDrawable.AVATAR_TYPE_ARCHIVED) { avatarDrawable.setArchivedAvatarHiddenProgress(CubicBezierInterpolator.EASE_OUT_QUINT.getInterpolation(archiveBackgroundProgress)); } needInvalidate = true; } } if (animatingArchiveAvatar) { animatingArchiveAvatarProgress += 16f; if (animatingArchiveAvatarProgress >= 170.0f) { animatingArchiveAvatarProgress = 170.0f; animatingArchiveAvatar = false; } needInvalidate = true; } if (drawRevealBackground) { if (currentRevealBounceProgress < 1.0f) { currentRevealBounceProgress += 16f / 170.0f; if (currentRevealBounceProgress > 1.0f) { currentRevealBounceProgress = 1.0f; needInvalidate = true; } } if (currentRevealProgress < 1.0f) { currentRevealProgress += 16f / 300.0f; if (currentRevealProgress > 1.0f) { currentRevealProgress = 1.0f; } needInvalidate = true; } } else { if (currentRevealBounceProgress == 1.0f) { currentRevealBounceProgress = 0.0f; needInvalidate = true; } if (currentRevealProgress > 0.0f) { currentRevealProgress -= 16f / 300.0f; if (currentRevealProgress < 0.0f) { currentRevealProgress = 0.0f; } needInvalidate = true; } } if (needInvalidate) { invalidate(); } } private PremiumGradient.PremiumGradientTools premiumGradient; private Drawable lockDrawable; public boolean drawAvatarOverlays(Canvas canvas) { boolean needInvalidate = false; float lockT = premiumBlockedT.set(premiumBlocked); if (lockT > 0) { float top = avatarImage.getCenterY() + dp(18); float left = avatarImage.getCenterX() + dp(18); canvas.save(); Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider)); canvas.drawCircle(left, top, dp(10 + 1.33f) * lockT, Theme.dialogs_onlineCirclePaint); if (premiumGradient == null) { premiumGradient = new PremiumGradient.PremiumGradientTools(Theme.key_premiumGradient1, Theme.key_premiumGradient2, -1, -1, -1, resourcesProvider); } premiumGradient.gradientMatrix((int) (left - dp(10)), (int) (top - dp(10)), (int) (left + dp(10)), (int) (top + dp(10)), 0, 0); canvas.drawCircle(left, top, dp(10) * lockT, premiumGradient.paint); if (lockDrawable == null) { lockDrawable = getContext().getResources().getDrawable(R.drawable.msg_mini_lock2).mutate(); lockDrawable.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN)); } lockDrawable.setBounds( (int) (left - lockDrawable.getIntrinsicWidth() / 2f * .875f * lockT), (int) (top - lockDrawable.getIntrinsicHeight() / 2f * .875f * lockT), (int) (left + lockDrawable.getIntrinsicWidth() / 2f * .875f * lockT), (int) (top + lockDrawable.getIntrinsicHeight() / 2f * .875f * lockT) ); lockDrawable.setAlpha((int) (0xFF * lockT)); lockDrawable.draw(canvas); canvas.restore(); return false; } if (isDialogCell && currentDialogFolderId == 0) { showTtl = ttlPeriod > 0 && !isOnline() && !hasCall; if (rightFragmentOpenedProgress != 1f && (showTtl || ttlProgress > 0)) { if (timerDrawable == null || (timerDrawable.getTime() != ttlPeriod && ttlPeriod > 0)) { timerDrawable = TimerDrawable.getTtlIconForDialogs(ttlPeriod); } if (timerPaint == null) { timerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); timerPaint2 = new Paint(Paint.ANTI_ALIAS_FLAG); timerPaint2.setColor(0x32000000); } int top = (int) (avatarImage.getImageY2() - dp(9)); int left; if (LocaleController.isRTL) { left = (int) (storyParams.originalAvatarRect.left + dp(9)); } else { left = (int) (storyParams.originalAvatarRect.right - dp(9)); } timerDrawable.setBounds( 0, 0, dp(22), dp(22) ); timerDrawable.setTime(ttlPeriod); if (avatarImage.updateThumbShaderMatrix()) { if (avatarImage.thumbShader != null) { timerPaint.setShader(avatarImage.thumbShader); } else if (avatarImage.staticThumbShader != null) { timerPaint.setShader(avatarImage.staticThumbShader); } } else { timerPaint.setShader(null); if (avatarImage.getBitmap() != null && !avatarImage.getBitmap().isRecycled()) { timerPaint.setColor(AndroidUtilities.getDominantColor(avatarImage.getBitmap())); } else if (avatarImage.getDrawable() instanceof VectorAvatarThumbDrawable){ VectorAvatarThumbDrawable vectorAvatarThumbDrawable = (VectorAvatarThumbDrawable) avatarImage.getDrawable(); timerPaint.setColor(vectorAvatarThumbDrawable.gradientTools.getAverageColor()); } else { timerPaint.setColor(avatarDrawable.getColor2()); } } canvas.save(); float s = ttlProgress * (1f - rightFragmentOpenedProgress); if (checkBox != null) { s *= 1f - checkBox.getProgress(); } canvas.scale(s, s, left, top); canvas.drawCircle(left, top, AndroidUtilities.dpf2(11f), timerPaint); canvas.drawCircle(left, top, AndroidUtilities.dpf2(11f), timerPaint2); canvas.save(); canvas.translate(left - AndroidUtilities.dpf2(11f), top - AndroidUtilities.dpf2(11f)); timerDrawable.draw(canvas); canvas.restore(); canvas.restore(); } if (user != null && !MessagesController.isSupportUser(user) && !user.bot) { boolean isOnline = isOnline(); wasDrawnOnline = isOnline; if (isOnline || onlineProgress != 0) { int top = (int) (storyParams.originalAvatarRect.bottom - dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 6 : 8)); int left; if (LocaleController.isRTL) { left = (int) (storyParams.originalAvatarRect.left + dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 6)); } else { left = (int) (storyParams.originalAvatarRect.right - dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 6)); } Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider)); canvas.drawCircle(left, top, dp(7) * onlineProgress, Theme.dialogs_onlineCirclePaint); Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_chats_onlineCircle, resourcesProvider)); canvas.drawCircle(left, top, dp(5) * onlineProgress, Theme.dialogs_onlineCirclePaint); if (isOnline) { if (onlineProgress < 1.0f) { onlineProgress += 16f / 150.0f; if (onlineProgress > 1.0f) { onlineProgress = 1.0f; } needInvalidate = true; } } else { if (onlineProgress > 0.0f) { onlineProgress -= 16f / 150.0f; if (onlineProgress < 0.0f) { onlineProgress = 0.0f; } needInvalidate = true; } } } } else if (chat != null) { hasCall = chat.call_active && chat.call_not_empty; if ((hasCall || chatCallProgress != 0) && rightFragmentOpenedProgress < 1f) { float checkProgress = checkBox != null && checkBox.isChecked() ? 1.0f - checkBox.getProgress() : 1.0f; int top = (int) (storyParams.originalAvatarRect.bottom - dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 6 : 8)); int left; if (LocaleController.isRTL) { left = (int) (storyParams.originalAvatarRect.left + dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 6)); } else { left = (int) (storyParams.originalAvatarRect.right - dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 6)); } if (rightFragmentOpenedProgress != 0) { canvas.save(); float scale = 1f - rightFragmentOpenedProgress; canvas.scale(scale, scale, left, top); } Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider)); canvas.drawCircle(left, top, dp(11) * chatCallProgress * checkProgress, Theme.dialogs_onlineCirclePaint); Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_chats_onlineCircle, resourcesProvider)); canvas.drawCircle(left, top, dp(9) * chatCallProgress * checkProgress, Theme.dialogs_onlineCirclePaint); Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider)); float size1; float size2; if (!LiteMode.isEnabled(LiteMode.FLAGS_CHAT)) { innerProgress = 0.65f; } if (progressStage == 0) { size1 = dp(1) + dp(4) * innerProgress; size2 = dp(3) - dp(2) * innerProgress; } else if (progressStage == 1) { size1 = dp(5) - dp(4) * innerProgress; size2 = dp(1) + dp(4) * innerProgress; } else if (progressStage == 2) { size1 = dp(1) + dp(2) * innerProgress; size2 = dp(5) - dp(4) * innerProgress; } else if (progressStage == 3) { size1 = dp(3) - dp(2) * innerProgress; size2 = dp(1) + dp(2) * innerProgress; } else if (progressStage == 4) { size1 = dp(1) + dp(4) * innerProgress; size2 = dp(3) - dp(2) * innerProgress; } else if (progressStage == 5) { size1 = dp(5) - dp(4) * innerProgress; size2 = dp(1) + dp(4) * innerProgress; } else if (progressStage == 6) { size1 = dp(1) + dp(4) * innerProgress; size2 = dp(5) - dp(4) * innerProgress; } else { size1 = dp(5) - dp(4) * innerProgress; size2 = dp(1) + dp(2) * innerProgress; } if (chatCallProgress < 1.0f || checkProgress < 1.0f) { canvas.save(); canvas.scale(chatCallProgress * checkProgress, chatCallProgress * checkProgress, left, top); } rect.set(left - dp(1), top - size1, left + dp(1), top + size1); canvas.drawRoundRect(rect, dp(1), dp(1), Theme.dialogs_onlineCirclePaint); rect.set(left - dp(5), top - size2, left - dp(3), top + size2); canvas.drawRoundRect(rect, dp(1), dp(1), Theme.dialogs_onlineCirclePaint); rect.set(left + dp(3), top - size2, left + dp(5), top + size2); canvas.drawRoundRect(rect, dp(1), dp(1), Theme.dialogs_onlineCirclePaint); if (chatCallProgress < 1.0f || checkProgress < 1.0f) { canvas.restore(); } if (LiteMode.isEnabled(LiteMode.FLAGS_CHAT)) { innerProgress += 16f / 400.0f; if (innerProgress >= 1.0f) { innerProgress = 0.0f; progressStage++; if (progressStage >= 8) { progressStage = 0; } } needInvalidate = true; } if (hasCall) { if (chatCallProgress < 1.0f) { chatCallProgress += 16f / 150.0f; if (chatCallProgress > 1.0f) { chatCallProgress = 1.0f; } } } else { if (chatCallProgress > 0.0f) { chatCallProgress -= 16f / 150.0f; if (chatCallProgress < 0.0f) { chatCallProgress = 0.0f; } } } if (rightFragmentOpenedProgress != 0) { canvas.restore(); } } } if (showTtl) { if (ttlProgress < 1.0f) { ttlProgress += 16f / 150.0f; needInvalidate = true; } } else { if (ttlProgress > 0.0f) { ttlProgress -= 16f / 150.0f; needInvalidate = true; } } ttlProgress = Utilities.clamp(ttlProgress, 1f, 0); } return needInvalidate; } private void drawCounter(Canvas canvas, boolean drawCounterMuted, int countTop, int countLeftLocal, int countLeftOld, float globalScale, boolean outline) { final boolean drawBubble = isForumCell() || isFolderCell(); if (drawCount && drawCount2 || countChangeProgress != 1f) { final float progressFinal = (unreadCount == 0 && !markUnread) ? 1f - countChangeProgress : countChangeProgress; Paint paint; int fillPaintAlpha = 255; boolean restoreCountTextPaint = false; if (outline) { if (counterPaintOutline == null) { counterPaintOutline = new Paint(); counterPaintOutline.setStyle(Paint.Style.STROKE); counterPaintOutline.setStrokeWidth(dp(2)); counterPaintOutline.setStrokeJoin(Paint.Join.ROUND); counterPaintOutline.setStrokeCap(Paint.Cap.ROUND); } int color = Theme.getColor(Theme.key_chats_pinnedOverlay); counterPaintOutline.setColor(ColorUtils.blendARGB( Theme.getColor(Theme.key_windowBackgroundWhite), ColorUtils.setAlphaComponent(color, 255), Color.alpha(color) / 255f )); } if (isTopic && forumTopic.read_inbox_max_id == 0) { if (topicCounterPaint == null) { topicCounterPaint = new Paint(); } paint = topicCounterPaint; int color = Theme.getColor(drawCounterMuted ? Theme.key_topics_unreadCounterMuted : Theme.key_topics_unreadCounter, resourcesProvider); paint.setColor(color); Theme.dialogs_countTextPaint.setColor(color); fillPaintAlpha = drawCounterMuted ? 30 : 40; restoreCountTextPaint = true; } else { paint = drawCounterMuted || currentDialogFolderId != 0 ? Theme.dialogs_countGrayPaint : Theme.dialogs_countPaint; } if (countOldLayout == null || unreadCount == 0) { StaticLayout drawLayout = unreadCount == 0 ? countOldLayout : countLayout; paint.setAlpha((int) ((1.0f - reorderIconProgress) * fillPaintAlpha)); Theme.dialogs_countTextPaint.setAlpha((int) ((1.0f - reorderIconProgress) * 255)); int x = countLeftLocal - dp(5.5f); rect.set(x, countTop, x + countWidth + dp(11), countTop + dp(23)); int restoreToCount = canvas.save(); if (globalScale != 1f) { canvas.scale(globalScale, globalScale, rect.centerX(), rect.centerY()); } if (progressFinal != 1f) { if (getIsPinned()) { Theme.dialogs_pinnedDrawable.setAlpha((int) ((1.0f - reorderIconProgress) * 255)); setDrawableBounds(Theme.dialogs_pinnedDrawable, pinLeft, pinTop); canvas.save(); canvas.scale(1f - progressFinal, 1f - progressFinal, Theme.dialogs_pinnedDrawable.getBounds().centerX(), Theme.dialogs_pinnedDrawable.getBounds().centerY()); Theme.dialogs_pinnedDrawable.draw(canvas); canvas.restore(); } canvas.scale(progressFinal, progressFinal, rect.centerX(), rect.centerY()); } if (drawBubble) { if (counterPath == null || counterPathRect == null || !counterPathRect.equals(rect)) { if (counterPathRect == null) { counterPathRect = new RectF(rect); } else { counterPathRect.set(rect); } if (counterPath == null) { counterPath = new Path(); } BubbleCounterPath.addBubbleRect(counterPath, counterPathRect, dp(11.5f)); } canvas.drawPath(counterPath, paint); if (outline) { canvas.drawPath(counterPath, counterPaintOutline); } } else { canvas.drawRoundRect(rect, dp(11.5f), dp(11.5f), paint); if (outline) { canvas.drawRoundRect(rect, dp(11.5f), dp(11.5f), counterPaintOutline); } } if (drawLayout != null) { canvas.save(); canvas.translate(countLeftLocal, countTop + dp(4)); drawLayout.draw(canvas); canvas.restore(); } canvas.restoreToCount(restoreToCount); } else { paint.setAlpha((int) ((1.0f - reorderIconProgress) * fillPaintAlpha)); Theme.dialogs_countTextPaint.setAlpha((int) ((1.0f - reorderIconProgress) * 255)); float progressHalf = progressFinal * 2; if (progressHalf > 1f) { progressHalf = 1f; } float countLeft = countLeftLocal * progressHalf + countLeftOld * (1f - progressHalf); float x = countLeft - dp(5.5f); rect.set(x, countTop, x + (countWidth * progressHalf) + (countWidthOld * (1f - progressHalf)) + dp(11), countTop + dp(23)); float scale = 1f; if (progressFinal <= 0.5f) { scale += 0.1f * CubicBezierInterpolator.EASE_OUT.getInterpolation(progressFinal * 2); } else { scale += 0.1f * CubicBezierInterpolator.EASE_IN.getInterpolation((1f - (progressFinal - 0.5f) * 2)); } canvas.save(); canvas.scale(scale * globalScale, scale * globalScale, rect.centerX(), rect.centerY()); if (drawBubble) { if (counterPath == null || counterPathRect == null || !counterPathRect.equals(rect)) { if (counterPathRect == null) { counterPathRect = new RectF(rect); } else { counterPathRect.set(rect); } if (counterPath == null) { counterPath = new Path(); } BubbleCounterPath.addBubbleRect(counterPath, counterPathRect, dp(11.5f)); } canvas.drawPath(counterPath, paint); if (outline) { canvas.drawPath(counterPath, counterPaintOutline); } } else { canvas.drawRoundRect(rect, dp(11.5f), dp(11.5f), paint); if (outline) { canvas.drawRoundRect(rect, dp(11.5f), dp(11.5f), counterPaintOutline); } } if (countAnimationStableLayout != null) { canvas.save(); canvas.translate(countLeft, countTop + dp(4)); countAnimationStableLayout.draw(canvas); canvas.restore(); } int textAlpha = Theme.dialogs_countTextPaint.getAlpha(); Theme.dialogs_countTextPaint.setAlpha((int) (textAlpha * progressHalf)); if (countAnimationInLayout != null) { canvas.save(); canvas.translate(countLeft, (countAnimationIncrement ? dp(13) : -dp(13)) * (1f - progressHalf) + countTop + dp(4)); countAnimationInLayout.draw(canvas); canvas.restore(); } else if (countLayout != null) { canvas.save(); canvas.translate(countLeft, (countAnimationIncrement ? dp(13) : -dp(13)) * (1f - progressHalf) + countTop + dp(4)); countLayout.draw(canvas); canvas.restore(); } if (countOldLayout != null) { Theme.dialogs_countTextPaint.setAlpha((int) (textAlpha * (1f - progressHalf))); canvas.save(); canvas.translate(countLeft, (countAnimationIncrement ? -dp(13) : dp(13)) * progressHalf + countTop + dp(4)); countOldLayout.draw(canvas); canvas.restore(); } Theme.dialogs_countTextPaint.setAlpha(textAlpha); canvas.restore(); } if (restoreCountTextPaint) { Theme.dialogs_countTextPaint.setColor(Theme.getColor(Theme.key_chats_unreadCounterText)); } } } private void createStatusDrawableAnimator(int lastStatusDrawableParams, int currentStatus) { statusDrawableProgress = 0f; statusDrawableAnimator = ValueAnimator.ofFloat(0,1f); statusDrawableAnimator.setDuration(220); statusDrawableAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); animateFromStatusDrawableParams = lastStatusDrawableParams; animateToStatusDrawableParams = currentStatus; statusDrawableAnimator.addUpdateListener(valueAnimator -> { statusDrawableProgress = (float) valueAnimator.getAnimatedValue(); invalidate(); }); statusDrawableAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { int currentStatus = (DialogCell.this.drawClock ? 1 : 0) + (DialogCell.this.drawCheck1 ? 2 : 0) + (DialogCell.this.drawCheck2 ? 4 : 0); if (animateToStatusDrawableParams != currentStatus) { createStatusDrawableAnimator(animateToStatusDrawableParams, currentStatus); } else { statusDrawableAnimationInProgress = false; DialogCell.this.lastStatusDrawableParams = animateToStatusDrawableParams; } invalidate(); } }); statusDrawableAnimationInProgress = true; statusDrawableAnimator.start(); } public void startOutAnimation() { if (archivedChatsDrawable != null) { if (isTopic) { archivedChatsDrawable.outCy = dp(10 + 14); archivedChatsDrawable.outCx = dp(10 + 14); archivedChatsDrawable.outRadius = 0; archivedChatsDrawable.outImageSize = 0; } else { archivedChatsDrawable.outCy = storyParams.originalAvatarRect.centerY(); archivedChatsDrawable.outCx = storyParams.originalAvatarRect.centerX(); archivedChatsDrawable.outRadius = storyParams.originalAvatarRect.width() / 2.0f; if (MessagesController.getInstance(currentAccount).getStoriesController().hasHiddenStories()) { archivedChatsDrawable.outRadius -= AndroidUtilities.dpf2(3.5f); } archivedChatsDrawable.outImageSize = avatarImage.getBitmapWidth(); } archivedChatsDrawable.startOutAnimation(); } } public void onReorderStateChanged(boolean reordering, boolean animated) { if (!getIsPinned() && reordering || drawReorder == reordering) { if (!getIsPinned()) { drawReorder = false; } return; } drawReorder = reordering; if (animated) { reorderIconProgress = drawReorder ? 0.0f : 1.0f; } else { reorderIconProgress = drawReorder ? 1.0f : 0.0f; } invalidate(); } public void setSliding(boolean value) { isSliding = value; } @Override public void invalidateDrawable(Drawable who) { if (who == translationDrawable || who == Theme.dialogs_archiveAvatarDrawable) { invalidate(who.getBounds()); } else { super.invalidateDrawable(who); } } @Override public boolean hasOverlappingRendering() { return false; } @Override public boolean performAccessibilityAction(int action, Bundle arguments) { if (action == R.id.acc_action_chat_preview && parentFragment != null) { parentFragment.showChatPreview(this); return true; } return super.performAccessibilityAction(action, arguments); } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); if (isFolderCell() && archivedChatsDrawable != null && SharedConfig.archiveHidden && archivedChatsDrawable.pullProgress == 0.0f) { info.setVisibleToUser(false); } else { info.addAction(AccessibilityNodeInfo.ACTION_CLICK); info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); if (!isFolderCell() && parentFragment != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { info.addAction(new AccessibilityNodeInfo.AccessibilityAction(R.id.acc_action_chat_preview, LocaleController.getString("AccActionChatPreview", R.string.AccActionChatPreview))); } } if (checkBox != null && checkBox.isChecked()) { info.setClassName("android.widget.CheckBox"); info.setCheckable(true); info.setChecked(true); } } @Override public void onPopulateAccessibilityEvent(AccessibilityEvent event) { super.onPopulateAccessibilityEvent(event); StringBuilder sb = new StringBuilder(); if (currentDialogFolderId == 1) { sb.append(LocaleController.getString("ArchivedChats", R.string.ArchivedChats)); sb.append(". "); } else { if (encryptedChat != null) { sb.append(LocaleController.getString("AccDescrSecretChat", R.string.AccDescrSecretChat)); sb.append(". "); } if (isTopic && forumTopic != null) { sb.append(LocaleController.getString("AccDescrTopic", R.string.AccDescrTopic)); sb.append(". "); sb.append(forumTopic.title); sb.append(". "); } else if (user != null) { if (UserObject.isReplyUser(user)) { sb.append(LocaleController.getString("RepliesTitle", R.string.RepliesTitle)); } else if (UserObject.isAnonymous(user)) { sb.append(LocaleController.getString(R.string.AnonymousForward)); } else { if (user.bot) { sb.append(LocaleController.getString("Bot", R.string.Bot)); sb.append(". "); } if (user.self) { sb.append(LocaleController.getString("SavedMessages", R.string.SavedMessages)); } else { sb.append(ContactsController.formatName(user.first_name, user.last_name)); } } sb.append(". "); } else if (chat != null) { if (chat.broadcast) { sb.append(LocaleController.getString("AccDescrChannel", R.string.AccDescrChannel)); } else { sb.append(LocaleController.getString("AccDescrGroup", R.string.AccDescrGroup)); } sb.append(". "); sb.append(chat.title); sb.append(". "); } } if (drawVerified) { sb.append(LocaleController.getString("AccDescrVerified", R.string.AccDescrVerified)); sb.append(". "); } if (dialogMuted) { sb.append(LocaleController.getString("AccDescrNotificationsMuted", R.string.AccDescrNotificationsMuted)); sb.append(". "); } if (isOnline()) { sb.append(LocaleController.getString("AccDescrUserOnline", R.string.AccDescrUserOnline)); sb.append(". "); } if (unreadCount > 0) { sb.append(LocaleController.formatPluralString("NewMessages", unreadCount)); sb.append(". "); } if (mentionCount > 0) { sb.append(LocaleController.formatPluralString("AccDescrMentionCount", mentionCount)); sb.append(". "); } if (reactionMentionCount > 0) { sb.append(LocaleController.getString("AccDescrMentionReaction", R.string.AccDescrMentionReaction)); sb.append(". "); } if (message == null || currentDialogFolderId != 0) { event.setContentDescription(sb); setContentDescription(sb); return; } int lastDate = lastMessageDate; if (lastMessageDate == 0) { lastDate = message.messageOwner.date; } String date = LocaleController.formatDateAudio(lastDate, true); if (message.isOut()) { sb.append(LocaleController.formatString("AccDescrSentDate", R.string.AccDescrSentDate, date)); } else { sb.append(LocaleController.formatString("AccDescrReceivedDate", R.string.AccDescrReceivedDate, date)); } sb.append(". "); if (chat != null && !message.isOut() && message.isFromUser() && message.messageOwner.action == null) { TLRPC.User fromUser = MessagesController.getInstance(currentAccount).getUser(message.messageOwner.from_id.user_id); if (fromUser != null) { sb.append(ContactsController.formatName(fromUser.first_name, fromUser.last_name)); sb.append(". "); } } if (encryptedChat == null) { StringBuilder messageString = new StringBuilder(); messageString.append(message.messageText); if (!message.isMediaEmpty()) { MessageObject captionMessage = getCaptionMessage(); if (captionMessage != null && !TextUtils.isEmpty(captionMessage.caption)) { if (messageString.length() > 0) { messageString.append(". "); } messageString.append(captionMessage.caption); } } int len = messageLayout == null ? -1 : messageLayout.getText().length(); if (len > 0) { int index = messageString.length(), b; if ((b = messageString.indexOf("\n", len)) < index && b >= 0) index = b; if ((b = messageString.indexOf("\t", len)) < index && b >= 0) index = b; if ((b = messageString.indexOf(" ", len)) < index && b >= 0) index = b; sb.append(messageString.substring(0, index)); } else { sb.append(messageString); } } event.setContentDescription(sb); setContentDescription(sb); } private MessageObject getCaptionMessage() { if (groupMessages == null) { if (message != null && message.caption != null) { return message; } return null; } MessageObject captionMessage = null; int hasCaption = 0; for (int i = 0; i < groupMessages.size(); ++i) { MessageObject msg = groupMessages.get(i); if (msg != null && msg.caption != null) { captionMessage = msg; if (!TextUtils.isEmpty(msg.caption)) { hasCaption++; } } } if (hasCaption > 1) { return null; } return captionMessage; } public void updateMessageThumbs() { if (message == null) { return; } String restrictionReason = MessagesController.getRestrictionReason(message.messageOwner.restriction_reason); if (groupMessages != null && groupMessages.size() > 1 && TextUtils.isEmpty(restrictionReason) && currentDialogFolderId == 0 && encryptedChat == null) { thumbsCount = 0; hasVideoThumb = false; Collections.sort(groupMessages, Comparator.comparingInt(MessageObject::getId)); for (int i = 0; i < Math.min(3, groupMessages.size()); ++i) { MessageObject message = groupMessages.get(i); if (message != null && !message.needDrawBluredPreview() && (message.isPhoto() || message.isNewGif() || message.isVideo() || message.isRoundVideo() || message.isStoryMedia())) { String type = message.isWebpage() ? message.messageOwner.media.webpage.type : null; if (!("app".equals(type) || "profile".equals(type) || "article".equals(type) || type != null && type.startsWith("telegram_"))) { setThumb(i, message); } } } } else if (message != null && currentDialogFolderId == 0) { thumbsCount = 0; hasVideoThumb = false; if (!message.needDrawBluredPreview() && (message.isPhoto() || message.isNewGif() || message.isVideo() || message.isRoundVideo() || message.isStoryMedia())) { String type = message.isWebpage() ? message.messageOwner.media.webpage.type : null; if (!("app".equals(type) || "profile".equals(type) || "article".equals(type) || type != null && type.startsWith("telegram_"))) { setThumb(0, message); } } } } private void setThumb(int index, MessageObject message) { ArrayList<TLRPC.PhotoSize> photoThumbs = message.photoThumbs; TLObject photoThumbsObject = message.photoThumbsObject; if (message.isStoryMedia()) { TL_stories.StoryItem storyItem = message.messageOwner.media.storyItem; if (storyItem != null && storyItem.media != null) { if (storyItem.media.document != null) { photoThumbs = storyItem.media.document.thumbs; photoThumbsObject = storyItem.media.document; } else if (storyItem.media.photo != null) { photoThumbs = storyItem.media.photo.sizes; photoThumbsObject = storyItem.media.photo; } } else { return; } } TLRPC.PhotoSize smallThumb = FileLoader.getClosestPhotoSizeWithSize(photoThumbs, 40); TLRPC.PhotoSize bigThumb = FileLoader.getClosestPhotoSizeWithSize(photoThumbs, AndroidUtilities.getPhotoSize()); if (smallThumb == bigThumb) { bigThumb = null; } TLRPC.PhotoSize selectedThumb = bigThumb; if (selectedThumb == null || DownloadController.getInstance(currentAccount).canDownloadMedia(message.messageOwner) == 0) { selectedThumb = smallThumb; } if (smallThumb != null) { hasVideoThumb = hasVideoThumb || (message.isVideo() || message.isRoundVideo()); if (thumbsCount < 3) { thumbsCount++; drawPlay[index] = (message.isVideo() || message.isRoundVideo()) && !message.hasMediaSpoilers(); drawSpoiler[index] = message.hasMediaSpoilers(); int size = message.type == MessageObject.TYPE_PHOTO && selectedThumb != null ? selectedThumb.size : 0; String filter = message.hasMediaSpoilers() ? "5_5_b" : "20_20"; thumbImage[index].setImage(ImageLocation.getForObject(selectedThumb, photoThumbsObject), filter, ImageLocation.getForObject(smallThumb, photoThumbsObject), filter, size, null, message, 0); thumbImage[index].setRoundRadius(message.isRoundVideo() ? dp(18) : dp(2)); needEmoji = false; } } } public String getMessageNameString() { if (message == null) { return null; } TLRPC.User user; TLRPC.User fromUser = null; TLRPC.Chat fromChat = null; long fromId = message.getFromChatId(); final long selfId = UserConfig.getInstance(currentAccount).getClientUserId(); if (!isSavedDialog && currentDialogId == selfId) { long savedDialogId = message.getSavedDialogId(); if (savedDialogId == selfId) { return null; } else if (savedDialogId != UserObject.ANONYMOUS) { if (message.messageOwner != null && message.messageOwner.fwd_from != null) { long fwdId = DialogObject.getPeerDialogId(message.messageOwner.fwd_from.saved_from_id); if (fwdId == 0) { fwdId = DialogObject.getPeerDialogId(message.messageOwner.fwd_from.from_id); } if (fwdId > 0 && fwdId != savedDialogId) { return null; } } fromId = savedDialogId; } } if (isSavedDialog && message.messageOwner != null && message.messageOwner.fwd_from != null) { fromId = DialogObject.getPeerDialogId(message.messageOwner.fwd_from.saved_from_id); if (fromId == 0) { fromId = DialogObject.getPeerDialogId(message.messageOwner.fwd_from.from_id); } } if (DialogObject.isUserDialog(fromId)) { fromUser = MessagesController.getInstance(currentAccount).getUser(fromId); } else { fromChat = MessagesController.getInstance(currentAccount).getChat(-fromId); } if (currentDialogId == selfId) { if (fromUser != null) { return UserObject.getFirstName(fromUser).replace("\n", ""); } else if (fromChat != null) { return fromChat.title.replace("\n", ""); } return null; } else if (message.isOutOwner()) { return LocaleController.getString("FromYou", R.string.FromYou); } else if (!isSavedDialog && message != null && message.messageOwner != null && message.messageOwner.from_id instanceof TLRPC.TL_peerUser && (user = MessagesController.getInstance(currentAccount).getUser(message.messageOwner.from_id.user_id)) != null) { return UserObject.getFirstName(user).replace("\n", ""); } else if (message != null && message.messageOwner != null && message.messageOwner.fwd_from != null && message.messageOwner.fwd_from.from_name != null) { return message.messageOwner.fwd_from.from_name; } else if (fromUser != null) { if (useForceThreeLines || SharedConfig.useThreeLinesLayout) { if (UserObject.isDeleted(fromUser)) { return LocaleController.getString("HiddenName", R.string.HiddenName); } else { return ContactsController.formatName(fromUser.first_name, fromUser.last_name).replace("\n", ""); } } else { return UserObject.getFirstName(fromUser).replace("\n", ""); } } else if (fromChat != null && fromChat.title != null) { return fromChat.title.replace("\n", ""); } else { return "DELETED"; } } public SpannableStringBuilder getMessageStringFormatted(int messageFormatType, String restrictionReason, CharSequence messageNameString, boolean applyThumbs) { SpannableStringBuilder stringBuilder; MessageObject captionMessage = getCaptionMessage(); CharSequence msgText = message != null ? message.messageText : null; applyName = true; if (!TextUtils.isEmpty(restrictionReason)) { stringBuilder = formatInternal(messageFormatType, restrictionReason, messageNameString); } else if (message.messageOwner instanceof TLRPC.TL_messageService) { CharSequence mess; if (message.messageTextShort != null && (!(message.messageOwner.action instanceof TLRPC.TL_messageActionTopicCreate) || !isTopic)) { mess = message.messageTextShort; } else { mess = message.messageText; } if (MessageObject.isTopicActionMessage(message)) { stringBuilder = formatInternal(messageFormatType, mess, messageNameString); if (message.topicIconDrawable[0] instanceof ForumBubbleDrawable) { TLRPC.TL_forumTopic topic = MessagesController.getInstance(currentAccount).getTopicsController().findTopic(-message.getDialogId(), MessageObject.getTopicId(currentAccount, message.messageOwner, true)); if (topic != null) { ((ForumBubbleDrawable) message.topicIconDrawable[0]).setColor(topic.icon_color); } } } else { applyName = false; stringBuilder = SpannableStringBuilder.valueOf(mess); } if (applyThumbs) { applyThumbs(stringBuilder); } } else if (captionMessage != null && captionMessage.caption != null) { MessageObject message = captionMessage; CharSequence mess = message.caption.toString(); String emoji; if (!needEmoji) { emoji = ""; } else if (message.isVideo()) { emoji = "\uD83D\uDCF9 "; } else if (message.isVoice()) { emoji = "\uD83C\uDFA4 "; } else if (message.isMusic()) { emoji = "\uD83C\uDFA7 "; } else if (message.isPhoto()) { emoji = "\uD83D\uDDBC "; } else { emoji = "\uD83D\uDCCE "; } if (message.hasHighlightedWords() && !TextUtils.isEmpty(message.messageOwner.message)) { CharSequence text = message.messageTrimmedToHighlight; int w = getMeasuredWidth() - dp(messagePaddingStart + 23 + 24); if (hasNameInMessage) { if (!TextUtils.isEmpty(messageNameString)) { w -= currentMessagePaint.measureText(messageNameString.toString()); } w -= currentMessagePaint.measureText(": "); } if (w > 0) { text = AndroidUtilities.ellipsizeCenterEnd(text, message.highlightedWords.get(0), w, currentMessagePaint, 130).toString(); } stringBuilder = new SpannableStringBuilder(emoji).append(text); } else { if (mess.length() > 150) { mess = mess.subSequence(0, 150); } SpannableStringBuilder msgBuilder = new SpannableStringBuilder(mess); if (message != null) { message.spoilLoginCode(); } MediaDataController.addTextStyleRuns(message.messageOwner.entities, mess, msgBuilder, TextStyleSpan.FLAG_STYLE_SPOILER | TextStyleSpan.FLAG_STYLE_STRIKE); if (message != null && message.messageOwner != null) { MediaDataController.addAnimatedEmojiSpans(message.messageOwner.entities, msgBuilder, currentMessagePaint == null ? null : currentMessagePaint.getFontMetricsInt()); } CharSequence charSequence = new SpannableStringBuilder(emoji).append(AndroidUtilities.replaceNewLines(msgBuilder)); if (applyThumbs) { charSequence = applyThumbs(charSequence); } stringBuilder = formatInternal(messageFormatType, charSequence, messageNameString); } } else if (message.messageOwner.media != null && !message.isMediaEmpty()) { currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex]; CharSequence innerMessage; int colorKey = Theme.key_chats_attachMessage; if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media; if (Build.VERSION.SDK_INT >= 18) { if (mediaPoll.poll.question != null && mediaPoll.poll.question.entities != null) { SpannableStringBuilder questionText = new SpannableStringBuilder(mediaPoll.poll.question.text.replace('\n', ' ')); MediaDataController.addTextStyleRuns(mediaPoll.poll.question.entities, mediaPoll.poll.question.text, questionText); MediaDataController.addAnimatedEmojiSpans(mediaPoll.poll.question.entities, questionText, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt()); innerMessage = new SpannableStringBuilder("\uD83D\uDCCA \u2068").append(questionText).append("\u2069"); } else { innerMessage = String.format("\uD83D\uDCCA \u2068%s\u2069", mediaPoll.poll.question.text); } } else { if (mediaPoll.poll.question != null && mediaPoll.poll.question.entities != null) { SpannableStringBuilder questionText = new SpannableStringBuilder(mediaPoll.poll.question.text.replace('\n', ' ')); MediaDataController.addTextStyleRuns(mediaPoll.poll.question.entities, mediaPoll.poll.question.text, questionText); MediaDataController.addAnimatedEmojiSpans(mediaPoll.poll.question.entities, questionText, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt()); innerMessage = new SpannableStringBuilder("\uD83D\uDCCA ").append(questionText); } else { innerMessage = String.format("\uD83D\uDCCA %s", mediaPoll.poll.question.text); } } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) { if (Build.VERSION.SDK_INT >= 18) { innerMessage = String.format("\uD83C\uDFAE \u2068%s\u2069", message.messageOwner.media.game.title); } else { innerMessage = String.format("\uD83C\uDFAE %s", message.messageOwner.media.game.title); } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice) { innerMessage = message.messageOwner.media.title; } else if (message.type == MessageObject.TYPE_MUSIC) { if (Build.VERSION.SDK_INT >= 18) { innerMessage = String.format("\uD83C\uDFA7 \u2068%s - %s\u2069", message.getMusicAuthor(), message.getMusicTitle()); } else { innerMessage = String.format("\uD83C\uDFA7 %s - %s", message.getMusicAuthor(), message.getMusicTitle()); } } else if (thumbsCount > 1) { if (hasVideoThumb) { innerMessage = LocaleController.formatPluralString("Media", groupMessages == null ? 0 : groupMessages.size()); } else { innerMessage = LocaleController.formatPluralString("Photos", groupMessages == null ? 0 : groupMessages.size()); } colorKey = Theme.key_chats_actionMessage; } else { innerMessage = msgText.toString(); colorKey = Theme.key_chats_actionMessage; } if (innerMessage instanceof String) { innerMessage = ((String) innerMessage).replace('\n', ' '); } CharSequence message = innerMessage; if (applyThumbs) { message = applyThumbs(innerMessage); } stringBuilder = formatInternal(messageFormatType, message, messageNameString); if (!isForumCell()) { try { stringBuilder.setSpan(new ForegroundColorSpanThemable(colorKey, resourcesProvider), hasNameInMessage ? messageNameString.length() + 2 : 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Exception e) { FileLog.e(e); } } } else if (message.messageOwner.message != null) { CharSequence mess = message.messageOwner.message; if (message.hasHighlightedWords()) { if (message.messageTrimmedToHighlight != null) { mess = message.messageTrimmedToHighlight; } int w = getMeasuredWidth() - dp(messagePaddingStart + 23 + 10); if (hasNameInMessage) { if (!TextUtils.isEmpty(messageNameString)) { w -= currentMessagePaint.measureText(messageNameString.toString()); } w -= currentMessagePaint.measureText(": "); } if (w > 0) { mess = AndroidUtilities.ellipsizeCenterEnd(mess, message.highlightedWords.get(0), w, currentMessagePaint, 130).toString(); } } else { if (mess.length() > 150) { mess = mess.subSequence(0, 150); } mess = AndroidUtilities.replaceNewLines(mess); } mess = new SpannableStringBuilder(mess); if (message != null) { message.spoilLoginCode(); } MediaDataController.addTextStyleRuns(message, (Spannable) mess, TextStyleSpan.FLAG_STYLE_SPOILER | TextStyleSpan.FLAG_STYLE_STRIKE); if (message != null && message.messageOwner != null) { MediaDataController.addAnimatedEmojiSpans(message.messageOwner.entities, mess, currentMessagePaint == null ? null : currentMessagePaint.getFontMetricsInt()); } if (applyThumbs) { mess = applyThumbs(mess); } stringBuilder = formatInternal(messageFormatType, mess, messageNameString); } else { stringBuilder = new SpannableStringBuilder(); } return stringBuilder; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (rightFragmentOpenedProgress == 0 && !isTopic && storyParams.checkOnTouchEvent(ev, this)) { return true; } return super.onInterceptTouchEvent(ev); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (!isTopic && ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) { storyParams.checkOnTouchEvent(ev, this); } return super.dispatchTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent event) { if (rightFragmentOpenedProgress == 0 && !isTopic && storyParams.checkOnTouchEvent(event, this)) { return true; } if (delegate == null || delegate.canClickButtonInside()) { if (lastTopicMessageUnread && canvasButton != null && buttonLayout != null && (dialogsType == DialogsActivity.DIALOGS_TYPE_DEFAULT || dialogsType == DialogsActivity.DIALOGS_TYPE_FOLDER1 || dialogsType == DialogsActivity.DIALOGS_TYPE_FOLDER2) && canvasButton.checkTouchEvent(event)) { return true; } } return super.onTouchEvent(event); } public void setClipProgress(float value) { clipProgress = value; invalidate(); } public float getClipProgress() { return clipProgress; } public void setTopClip(int value) { topClip = value; } public void setBottomClip(int value) { bottomClip = value; } public void setArchivedPullAnimation(PullForegroundDrawable drawable) { archivedChatsDrawable = drawable; } public int getCurrentDialogFolderId() { return currentDialogFolderId; } public boolean isDialogFolder() { return currentDialogFolderId > 0; } public MessageObject getMessage() { return message; } public void setDialogCellDelegate(DialogCellDelegate delegate) { this.delegate = delegate; } public interface DialogCellDelegate { void onButtonClicked(DialogCell dialogCell); void onButtonLongPress(DialogCell dialogCell); boolean canClickButtonInside(); void openStory(DialogCell dialogCell, Runnable onDone); void showChatPreview(DialogCell dialogCell); void openHiddenStories(); } private class DialogUpdateHelper { public long lastDrawnDialogId; public long lastDrawnMessageId; public boolean lastDrawnTranslated; public boolean lastDrawnDialogIsFolder; public long lastDrawnReadState; public int lastDrawnDraftHash; public Integer lastDrawnPrintingType; public int lastDrawnSizeHash; public int lastTopicsCount; public boolean lastDrawnPinned; public boolean lastDrawnHasCall; public float typingProgres; public boolean typingOutToTop; public int lastKnownTypingType; boolean waitngNewMessageFroTypingAnimation = false; long startWaitingTime; public boolean update() { TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(currentDialogId); if (dialog == null) { if (dialogsType == DialogsActivity.DIALOGS_TYPE_FORWARD && lastDrawnDialogId != currentDialogId) { lastDrawnDialogId = currentDialogId; return true; } return false; } int messageHash = message == null ? 0 : message.getId() + message.hashCode(); Integer printingType = null; long readHash = dialog.read_inbox_max_id + ((long) dialog.read_outbox_max_id << 8) + ((long) (dialog.unread_count + (dialog.unread_mark ? -1 : 0)) << 16) + (dialog.unread_reactions_count > 0 ? (1 << 18) : 0) + (dialog.unread_mentions_count > 0 ? (1 << 19) : 0); if (!isForumCell() && (isDialogCell || isTopic)) { if (!TextUtils.isEmpty(MessagesController.getInstance(currentAccount).getPrintingString(currentDialogId, getTopicId(), true))) { printingType = MessagesController.getInstance(currentAccount).getPrintingStringType(currentDialogId, getTopicId()); } else { printingType = null; } } int sizeHash = getMeasuredWidth() + (getMeasuredHeight() << 16); int topicCount = 0; if (isForumCell()) { ArrayList<TLRPC.TL_forumTopic> topics = MessagesController.getInstance(currentAccount).getTopicsController().getTopics(-currentDialogId); topicCount = topics == null ? -1 : topics.size(); if (topicCount == -1 && MessagesController.getInstance(currentAccount).getTopicsController().endIsReached(-currentDialogId)) { topicCount = 0; } } boolean draftVoice = false; TLRPC.DraftMessage draftMessage = null; if (isTopic) { draftVoice = MediaDataController.getInstance(currentAccount).getDraftVoice(currentDialogId, getTopicId()) != null; draftMessage = !draftVoice ? MediaDataController.getInstance(currentAccount).getDraft(currentDialogId, getTopicId()) : null; if (draftMessage != null && TextUtils.isEmpty(draftMessage.message)) { draftMessage = null; } } else if (isDialogCell) { draftVoice = MediaDataController.getInstance(currentAccount).getDraftVoice(currentDialogId, 0) != null; draftMessage = !draftVoice ? MediaDataController.getInstance(currentAccount).getDraft(currentDialogId, 0) : null; } int draftHash = draftMessage == null ? 0 : draftMessage.message.hashCode() + (draftMessage.reply_to != null ? (draftMessage.reply_to.reply_to_msg_id << 16) : 0); boolean hasCall = chat != null && chat.call_active && chat.call_not_empty; boolean translated = MessagesController.getInstance(currentAccount).getTranslateController().isTranslatingDialog(currentDialogId); if (lastDrawnSizeHash == sizeHash && lastDrawnMessageId == messageHash && lastDrawnTranslated == translated && lastDrawnDialogId == currentDialogId && lastDrawnDialogIsFolder == dialog.isFolder && lastDrawnReadState == readHash && Objects.equals(lastDrawnPrintingType, printingType) && lastTopicsCount == topicCount && draftHash == lastDrawnDraftHash && lastDrawnPinned == drawPin && lastDrawnHasCall == hasCall && DialogCell.this.draftVoice == draftVoice) { return false; } if (lastDrawnDialogId != currentDialogId) { typingProgres = printingType == null ? 0f : 1f; waitngNewMessageFroTypingAnimation = false; } else { if (!Objects.equals(lastDrawnPrintingType, printingType) || waitngNewMessageFroTypingAnimation) { if (!waitngNewMessageFroTypingAnimation && printingType == null) { waitngNewMessageFroTypingAnimation = true; startWaitingTime = System.currentTimeMillis(); } else if (waitngNewMessageFroTypingAnimation && lastDrawnMessageId != messageHash) { waitngNewMessageFroTypingAnimation = false; } if (lastDrawnMessageId != messageHash) { typingOutToTop = false; } else { typingOutToTop = true; } } } if (printingType != null) { lastKnownTypingType = printingType; } lastDrawnDialogId = currentDialogId; lastDrawnMessageId = messageHash; lastDrawnDialogIsFolder = dialog.isFolder; lastDrawnReadState = readHash; lastDrawnPrintingType = printingType; lastDrawnSizeHash = sizeHash; lastDrawnDraftHash = draftHash; lastTopicsCount = topicCount; lastDrawnPinned = drawPin; lastDrawnHasCall = hasCall; lastDrawnTranslated = translated; return true; } public void updateAnimationValues() { if (!waitngNewMessageFroTypingAnimation) { if (lastDrawnPrintingType != null && typingLayout != null && typingProgres != 1f) { typingProgres += 16f / 200f; invalidate(); } else if (lastDrawnPrintingType == null && typingProgres != 0) { typingProgres -= 16f / 200f; invalidate(); } typingProgres = Utilities.clamp(typingProgres, 1f, 0f); } else { if (System.currentTimeMillis() - startWaitingTime > 100) { waitngNewMessageFroTypingAnimation = false; } invalidate(); } } } @Override public void invalidate() { if (StoryViewer.animationInProgress) { return; } super.invalidate(); } @Override public void invalidate(int l, int t, int r, int b) { if (StoryViewer.animationInProgress) { return; } super.invalidate(l, t, r, b); } public static class SharedResources { LongSparseArray<ForumFormattedNames> formattedTopicNames = new LongSparseArray<>(); } private static class ForumFormattedNames { int lastMessageId; int topMessageTopicStartIndex; int topMessageTopicEndIndex; boolean lastTopicMessageUnread; boolean isLoadingState; CharSequence formattedNames; private void formatTopicsNames(int currentAccount, MessageObject message, TLRPC.Chat chat) { int messageId = message == null || chat == null ? 0 : message.getId(); if (lastMessageId == messageId && !isLoadingState) { return; } topMessageTopicStartIndex = 0; topMessageTopicEndIndex = 0; lastTopicMessageUnread = false; isLoadingState = false; lastMessageId = messageId; Paint currentMessagePaint = Theme.dialogs_messagePaint[0]; if (chat != null) { List<TLRPC.TL_forumTopic> topics = MessagesController.getInstance(currentAccount).getTopicsController().getTopics(chat.id); boolean hasDivider = false; if (topics != null && !topics.isEmpty()) { topics = new ArrayList<>(topics); Collections.sort(topics, Comparator.comparingInt(o -> -o.top_message)); SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); long topMessageTopicId = 0; int boldLen = 0; if (message != null) { topMessageTopicId = MessageObject.getTopicId(currentAccount, message.messageOwner, true); TLRPC.TL_forumTopic topic = MessagesController.getInstance(currentAccount).getTopicsController().findTopic(chat.id, topMessageTopicId); if (topic != null) { CharSequence topicString = ForumUtilities.getTopicSpannedName(topic, currentMessagePaint, false); spannableStringBuilder.append(topicString); if (topic.unread_count > 0) { boldLen = topicString.length(); } topMessageTopicStartIndex = 0; topMessageTopicEndIndex = topicString.length(); if (message.isOutOwner()) { lastTopicMessageUnread = false; } else { lastTopicMessageUnread = topic.unread_count > 0; } } else { lastTopicMessageUnread = false; } if (lastTopicMessageUnread) { spannableStringBuilder.append(" "); spannableStringBuilder.setSpan(new DialogCell.FixedWidthSpan(dp(3)), spannableStringBuilder.length() - 1, spannableStringBuilder.length(), 0); hasDivider = true; } } boolean firstApplay = true; for (int i = 0; i < Math.min(4, topics.size()); i++) { if (topics.get(i).id == topMessageTopicId) { continue; } if (spannableStringBuilder.length() != 0) { if (firstApplay && hasDivider) { spannableStringBuilder.append(" "); } else { spannableStringBuilder.append(", "); } } firstApplay = false; CharSequence topicString = ForumUtilities.getTopicSpannedName(topics.get(i), currentMessagePaint, false); spannableStringBuilder.append(topicString); } if (boldLen > 0) { spannableStringBuilder.setSpan( new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, Theme.key_chats_name, null), 0, Math.min(spannableStringBuilder.length(), boldLen + 2), 0 ); } formattedNames = spannableStringBuilder; return; } if (!MessagesController.getInstance(currentAccount).getTopicsController().endIsReached(chat.id)) { MessagesController.getInstance(currentAccount).getTopicsController().preloadTopics(chat.id); formattedNames = LocaleController.getString("Loading", R.string.Loading); isLoadingState = true; } else { formattedNames = "no created topics"; } } } } private ColorFilter[] adaptiveEmojiColorFilter; private int[] adaptiveEmojiColor; private ColorFilter getAdaptiveEmojiColorFilter(int n, int color) { if (adaptiveEmojiColorFilter == null) { adaptiveEmojiColor = new int[4]; adaptiveEmojiColorFilter = new ColorFilter[4]; } if (color != adaptiveEmojiColor[n] || adaptiveEmojiColorFilter[n] == null) { adaptiveEmojiColorFilter[n] = new PorterDuffColorFilter(adaptiveEmojiColor[n] = color, PorterDuff.Mode.SRC_IN); } return adaptiveEmojiColorFilter[n]; } private Runnable unsubscribePremiumBlocked; public void showPremiumBlocked(boolean show) { if (show != (unsubscribePremiumBlocked != null)) { if (!show && unsubscribePremiumBlocked != null) { unsubscribePremiumBlocked.run(); unsubscribePremiumBlocked = null; } else if (show) { unsubscribePremiumBlocked = NotificationCenter.getInstance(currentAccount).listen(this, NotificationCenter.userIsPremiumBlockedUpadted, args -> { updatePremiumBlocked(true); }); } } } private void updatePremiumBlocked(boolean animated) { final boolean wasPremiumBlocked = premiumBlocked; premiumBlocked = (unsubscribePremiumBlocked != null) && user != null && MessagesController.getInstance(currentAccount).isUserPremiumBlocked(user.id); if (wasPremiumBlocked != premiumBlocked) { if (!animated) { premiumBlockedT.set(premiumBlocked, true); } invalidate(); } } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java
2,173
/* * 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
2,174
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.util.ui; import com.intellij.BundleBase; import com.intellij.concurrency.ThreadContext; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.GraphicsConfig; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.Strings; import com.intellij.openapi.util.text.TextWithMnemonic; import com.intellij.ui.*; import com.intellij.ui.icons.HiDPIImage; import com.intellij.ui.mac.foundation.Foundation; import com.intellij.ui.paint.LinePainter2D; import com.intellij.ui.paint.PaintUtil.RoundingMode; import com.intellij.ui.render.RenderingUtil; import com.intellij.ui.scale.JBUIScale; import com.intellij.util.*; import com.intellij.util.concurrency.SynchronizedClearableLazy; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.JBIterable; import com.intellij.util.containers.JBTreeTraverser; import org.intellij.lang.annotations.JdkConstants; import org.intellij.lang.annotations.Language; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.*; import sun.font.FontUtilities; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.swing.FocusManager; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.plaf.ButtonUI; import javax.swing.plaf.ComboBoxUI; import javax.swing.plaf.FontUIResource; import javax.swing.plaf.basic.BasicComboBoxUI; import javax.swing.plaf.basic.BasicRadioButtonUI; import javax.swing.plaf.basic.ComboPopup; import javax.swing.text.*; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import java.awt.*; import java.awt.event.*; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; import java.awt.image.RGBImageFilter; import java.awt.print.PrinterGraphics; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.BufferedInputStream; import java.io.InputStream; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.net.URL; import java.text.NumberFormat; import java.text.ParseException; import java.util.List; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.function.Supplier; import java.util.regex.Pattern; @SuppressWarnings("StaticMethodOnlyUsedInOneClass") public final class UIUtil { public static final @NlsSafe String BORDER_LINE = "<hr size=1 noshade>"; public static final @NlsSafe String BR = "<br/>"; public static final @NlsSafe String HR = "<hr/>"; public static final @NlsSafe String LINE_SEPARATOR = "\n"; private static final Key<WeakReference<Component>> FOSTER_PARENT = Key.create("Component.fosterParent"); private static final Key<Boolean> HAS_FOCUS = Key.create("Component.hasFocus"); /** * A key for hiding a line under the window title bar on macOS * It works if and only if transparent title bars are enabled and IDE runs on JetBrains Runtime */ @ApiStatus.Internal public static final String NO_BORDER_UNDER_WINDOW_TITLE_KEY = ""; // cannot be static because logging maybe not configured yet private static @NotNull Logger getLogger() { return Logger.getInstance(UIUtil.class); } public static int getTransparentTitleBarHeight(JRootPane rootPane) { Object property = rootPane.getClientProperty("Window.transparentTitleBarHeight"); if (property instanceof Integer) { return (int)property; } if ("small".equals(rootPane.getClientProperty("Window.style"))) { return JBUI.getInt("macOSWindow.Title.heightSmall", 19); } else { return JBUI.getInt("macOSWindow.Title.height", SystemInfo.isMacOSBigSur ? 29 : 23); } } // Here we setup dialog to be suggested in OwnerOptional as owner even if the dialog is not modal public static void markAsPossibleOwner(Dialog dialog) { ClientProperty.put(dialog, "PossibleOwner", Boolean.TRUE); } public static boolean isPossibleOwner(@NotNull Dialog dialog) { return ClientProperty.isTrue(dialog, "PossibleOwner"); } public static int getMultiClickInterval() { Object property = Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"); if (property instanceof Integer) { return (Integer)property; } return 500; } private static final Supplier<Boolean> X_RENDER_ACTIVE = new SynchronizedClearableLazy<>(() -> { if (!StartupUiUtil.isXToolkit()) { return false; } try { Class<?> clazz = ClassLoader.getSystemClassLoader().loadClass("sun.awt.X11GraphicsEnvironment"); Method method = clazz.getMethod("isXRenderAvailable"); return (Boolean)method.invoke(null); } catch (Throwable e) { return false; } }); private static final String[] STANDARD_FONT_SIZES = {"8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "72"}; public static void applyStyle(@NotNull ComponentStyle componentStyle, @NotNull Component comp) { if (!(comp instanceof JComponent c)) { return; } if (isUnderAquaBasedLookAndFeel()) { c.putClientProperty("JComponent.sizeVariant", Strings.toLowerCase(componentStyle.name())); } FontSize fontSize; if (componentStyle == ComponentStyle.MINI) { fontSize = FontSize.MINI; } else if (componentStyle == ComponentStyle.SMALL) { fontSize = FontSize.SMALL; } else { fontSize = FontSize.NORMAL; } c.setFont(getFont(fontSize, c.getFont())); Container p = c.getParent(); if (p != null) { SwingUtilities.updateComponentTreeUI(p); } } public static @Nullable Cursor cursorIfNotDefault(@Nullable Cursor cursorToSet) { return cursorToSet != null && cursorToSet.getType() != Cursor.DEFAULT_CURSOR ? cursorToSet : null; } public static @NotNull RGBImageFilter getGrayFilter() { return GrayFilter.namedFilter("grayFilter", new GrayFilter(33, -35, 100)); } public static @NotNull RGBImageFilter getTextGrayFilter() { return GrayFilter.namedFilter("text.grayFilter", new GrayFilter(20, 0, 100)); } public static @NotNull Couple<Color> getCellColors(@NotNull JTable table, boolean isSel, int row, int column) { return Couple.of(isSel ? table.getSelectionForeground() : table.getForeground(), isSel ? table.getSelectionBackground() : table.getBackground()); } public static void fixOSXEditorBackground(@NotNull JTable table) { if (!SystemInfoRt.isMac) { return; } if (table.isEditing()) { int column = table.getEditingColumn(); int row = table.getEditingRow(); Component renderer = column >= 0 && row >= 0 ? table.getCellRenderer(row, column) .getTableCellRendererComponent(table, table.getValueAt(row, column), true, table.hasFocus(), row, column) : null; Component component = table.getEditorComponent(); if (component != null && renderer != null) { changeBackGround(component, renderer.getBackground()); } } } public enum FontSize {NORMAL, SMALL, MINI} public enum ComponentStyle {LARGE, REGULAR, SMALL, MINI} public enum FontColor {NORMAL, BRIGHTER} public static final char MNEMONIC = BundleBase.MNEMONIC; public static final @NlsSafe String HTML_MIME = "text/html"; public static final @NonNls String TABLE_FOCUS_CELL_BACKGROUND_PROPERTY = "Table.focusCellBackground"; /** * Prevent component DataContext from returning parent editor * Useful for components that are manually painted over the editor to prevent shortcuts from falling-through to editor * <p> * Usage: {@code component.putClientProperty(HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, Boolean.TRUE)} */ public static final @NonNls String HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY = "AuxEditorComponent"; public static final @NonNls String CENTER_TOOLTIP_DEFAULT = "ToCenterTooltip"; public static final @NonNls String CENTER_TOOLTIP_STRICT = "ToCenterTooltip.default"; public static final @NonNls String ENABLE_IME_FORWARDING_IN_POPUP = "EnableIMEForwardingInPopup"; private static final Pattern CLOSE_TAG_PATTERN = Pattern.compile("<\\s*([^<>/ ]+)([^<>]*)/\\s*>", Pattern.CASE_INSENSITIVE); public static final Key<Integer> KEEP_BORDER_SIDES = Key.create("keepBorderSides"); /** * Alt+click does copy text from tooltip or balloon to clipboard. * We collect this text from components recursively and this generic approach might 'grab' unexpected text fragments. * To provide more accurate text scope you should mark dedicated component with putClientProperty(TEXT_COPY_ROOT, Boolean.TRUE) * Note, main(root) components of BalloonImpl and AbstractPopup are already marked with this key */ public static final Key<Boolean> TEXT_COPY_ROOT = Key.create("TEXT_COPY_ROOT"); private static final Color ACTIVE_HEADER_COLOR = JBColor.namedColor("HeaderColor.active", 0xa0bad5); private static final Color INACTIVE_HEADER_COLOR = JBColor.namedColor("HeaderColor.inactive", Gray._128); public static final Color CONTRAST_BORDER_COLOR = JBColor.namedColor("Borders.ContrastBorderColor", new JBColor(0xC9C9C9, 0x323232)); public static final Color SIDE_PANEL_BACKGROUND = JBColor.namedColor("SidePanel.background", new JBColor(0xE6EBF0, 0x3E434C)); public static final Color AQUA_SEPARATOR_BACKGROUND_COLOR = new JBColor(Gray._240, Gray.x51); public static final Color TRANSPARENT_COLOR = Gray.TRANSPARENT; public static final int DEFAULT_HGAP = 10; public static final int DEFAULT_VGAP = 4; public static final int LARGE_VGAP = 12; private static final int REGULAR_PANEL_TOP_BOTTOM_INSET = 8; private static final int REGULAR_PANEL_LEFT_RIGHT_INSET = 12; public static final Insets PANEL_REGULAR_INSETS = getRegularPanelInsets(); public static final Insets PANEL_SMALL_INSETS = JBInsets.create(5, 8); private static final @NonNls String ROOT_PANE = "JRootPane.future"; private static final Ref<Boolean> ourRetina = Ref.create(SystemInfoRt.isMac ? null : false); private UIUtil() { } public static boolean isRetina(@NotNull Graphics2D graphics) { return SystemInfoRt.isMac ? DetectRetinaKit.isMacRetina(graphics) : isRetina(); } public static boolean isRetina() { if (GraphicsEnvironment.isHeadless()) return false; //Temporary workaround for HiDPI on Windows/Linux if ("true".equalsIgnoreCase(System.getProperty("is.hidpi"))) { return true; } if (Registry.is("new.retina.detection", false)) { return DetectRetinaKit.isRetina(); } else { synchronized (ourRetina) { if (ourRetina.isNull()) { ourRetina.set(false); // in case HiDPIScaledImage.drawIntoImage is not called for some reason try { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); final GraphicsDevice device = env.getDefaultScreenDevice(); Integer scale = ReflectionUtil.getField(device.getClass(), device, int.class, "scale"); if (scale != null && scale == 2) { ourRetina.set(true); return true; } } catch (AWTError | Exception ignore) { } ourRetina.set(false); } return ourRetina.get(); } } } /** * @param component a Swing component that may hold a client property value * @param key the client property key * @return {@code true} if the property of the specified component is set to {@code true} * @deprecated use {@link ClientProperty#isTrue(Component, Object)} instead */ @Deprecated public static boolean isClientPropertyTrue(Object component, @NotNull Object key) { return component instanceof Component && ClientProperty.isTrue((Component)component, key); } /** * @param component a Swing component that may hold a client property value * @param key the client property key that specifies a return type * @return the property value from the specified component or {@code null} * @deprecated use {@link ClientProperty#get(Component, Object)} instead */ @Deprecated(forRemoval = true) public static Object getClientProperty(Object component, @NotNull @NonNls Object key) { return component instanceof Component ? ClientProperty.get((Component)component, key) : null; } /** * @param component a Swing component that may hold a client property value * @return the property value from the specified component or {@code null} */ public static <T> T getClientProperty(Component component, @NotNull Class<T> type) { Object obj = ClientProperty.get(component, type); return type.isInstance(obj) ? type.cast(obj) : null; } /** * @param component a Swing component that may hold a client property value * @param key the client property key that specifies a return type * @return the property value from the specified component or {@code null} * @deprecated use {@link ClientProperty#get(Component, Key)} instead */ @Deprecated public static <T> T getClientProperty(Object component, @NotNull Key<T> key) { return component instanceof Component ? ClientProperty.get((Component)component, key) : null; } /** * @deprecated use {@link JComponent#putClientProperty(Object, Object)} * or {@link ClientProperty#put(JComponent, Key, Object)} instead */ @Deprecated public static <T> void putClientProperty(@NotNull JComponent component, @NotNull Key<T> key, T value) { component.putClientProperty(key, value); } @Contract(pure = true) public static @NotNull String getHtmlBody(@NotNull String text) { int htmlIndex = 6 + text.indexOf("<html>"); if (htmlIndex < 6) { return text.replaceAll("\n", "<br>"); } int htmlCloseIndex = text.indexOf("</html>", htmlIndex); if (htmlCloseIndex < 0) { htmlCloseIndex = text.length(); } int bodyIndex = 6 + text.indexOf("<body>", htmlIndex); if (bodyIndex < 6) { return text.substring(htmlIndex, htmlCloseIndex); } int bodyCloseIndex = text.indexOf("</body>", bodyIndex); if (bodyCloseIndex < 0) { bodyCloseIndex = text.length(); } return text.substring(bodyIndex, Math.min(bodyCloseIndex, htmlCloseIndex)); } @SuppressWarnings("HardCodedStringLiteral") public static @NotNull @Nls String getHtmlBody(@NotNull Html html) { String result = getHtmlBody(html.getText()); return html.isKeepFont() ? result : result.replaceAll("<font(.*?)>", "").replaceAll("</font>", ""); } public static void drawLinePickedOut(@NotNull Graphics graphics, int x, int y, int x1, int y1) { if (x == x1) { int minY = Math.min(y, y1); int maxY = Math.max(y, y1); LinePainter2D.paint((Graphics2D)graphics, x, minY + 1, x1, maxY - 1); } else if (y == y1) { int minX = Math.min(x, x1); int maxX = Math.max(x, x1); LinePainter2D.paint((Graphics2D)graphics, minX + 1, y, maxX - 1, y1); } else { LinePainter2D.paint((Graphics2D)graphics, x, y, x1, y1); } } public static boolean isReallyTypedEvent(@NotNull KeyEvent e) { char c = e.getKeyChar(); if (c == KeyEvent.CHAR_UNDEFINED) { // ignore CHAR_UNDEFINED, like Swing text components do return false; } if (c < 0x20 || c == 0x7F) { return false; } // allow input of special characters on Windows in Persian keyboard layout using Ctrl+Shift+1..4 if (SystemInfoRt.isWindows && c >= 0x200C && c <= 0x200F) { return true; } else if (SystemInfoRt.isMac) { return !e.isMetaDown() && !e.isControlDown(); } else { return !e.isAltDown() && !e.isControlDown(); } } public static int getStringY(final @NotNull String string, final @NotNull Rectangle bounds, final @NotNull Graphics2D g) { int centerY = bounds.height / 2; Font font = g.getFont(); FontRenderContext frc = g.getFontRenderContext(); Rectangle stringBounds = font.getStringBounds(string.isEmpty() ? " " : string, frc).getBounds(); return (int)(centerY - stringBounds.height / 2.0 - stringBounds.y); } public static void drawLabelDottedRectangle(final @NotNull JLabel label, final @NotNull Graphics g) { drawLabelDottedRectangle(label, g, null); } public static void drawLabelDottedRectangle(final @NotNull JLabel label, final @NotNull Graphics g, @Nullable Rectangle bounds) { if (bounds == null) { bounds = getLabelTextBounds(label); } // JLabel draws the text relative to the baseline. So, we must ensure // we draw the dotted rectangle relative to that same baseline. FontMetrics fm = label.getFontMetrics(label.getFont()); int baseLine = label.getUI().getBaseline(label, label.getWidth(), label.getHeight()); int textY = baseLine - fm.getLeading() - fm.getAscent(); int textHeight = fm.getHeight(); drawDottedRectangle(g, bounds.x, textY, bounds.x + bounds.width - 1, textY + textHeight - 1); } public static @NotNull Rectangle getLabelTextBounds(final @NotNull JLabel label) { final Dimension size = label.getPreferredSize(); Icon icon = label.getIcon(); final Point point = new Point(0, 0); final Insets insets = label.getInsets(); if (icon != null) { if (label.getHorizontalTextPosition() == SwingConstants.TRAILING) { point.x += label.getIconTextGap(); point.x += icon.getIconWidth(); } else if (label.getHorizontalTextPosition() == SwingConstants.LEADING) { size.width -= icon.getIconWidth(); } } point.x += insets.left; point.y += insets.top; size.width -= point.x; size.width -= insets.right; size.height -= insets.bottom; return new Rectangle(point, size); } /** * @param string {@code String} to examine * @param font {@code Font} that is used to render the string * @param graphics {@link Graphics} that should be used to render the string * @return height of the tallest glyph in a string. If string is empty, returns 0 */ public static int getHighestGlyphHeight(@NotNull String string, @NotNull Font font, @NotNull Graphics graphics) { FontRenderContext frc = ((Graphics2D)graphics).getFontRenderContext(); GlyphVector gv = font.createGlyphVector(frc, string); int maxHeight = 0; for (int i = 0; i < string.length(); i++) { maxHeight = Math.max(maxHeight, (int)gv.getGlyphMetrics(i).getBounds2D().getHeight()); } return maxHeight; } public static void setEnabled(@NotNull Component component, boolean enabled, boolean recursively) { setEnabled(component, enabled, recursively, false); } public static void setEnabled(@NotNull Component component, boolean enabled, boolean recursively, final boolean visibleOnly) { JBIterable<Component> all = recursively ? uiTraverser(component).expandAndFilter( visibleOnly ? Component::isVisible : Conditions.alwaysTrue()).traverse() : JBIterable.of(component); Color fg = enabled ? getLabelForeground() : getLabelDisabledForeground(); for (Component c : all) { c.setEnabled(enabled); if (c instanceof JLabel) { c.setForeground(fg); } } } public static void drawLine(@NotNull Graphics2D g, int x1, int y1, int x2, int y2, @Nullable Color bgColor, @Nullable Color fgColor) { Color oldFg = g.getColor(); Color oldBg = g.getBackground(); if (fgColor != null) { g.setColor(fgColor); } if (bgColor != null) { g.setBackground(bgColor); } LinePainter2D.paint(g, x1, y1, x2, y2); if (fgColor != null) { g.setColor(oldFg); } if (bgColor != null) { g.setBackground(oldBg); } } public static void drawWave(@NotNull Graphics2D g, @NotNull Rectangle rectangle) { WavePainter.forColor(g.getColor()).paint(g, (int)rectangle.getMinX(), (int)rectangle.getMaxX(), (int)rectangle.getMaxY()); } public static String @NotNull [] splitText(@NotNull String text, @NotNull FontMetrics fontMetrics, int widthLimit, char separator) { List<String> lines = new ArrayList<>(); StringBuilder currentLine = new StringBuilder(); StringBuilder currentAtom = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); currentAtom.append(ch); boolean lineBreak = ch == '\n'; if (lineBreak || ch == separator) { currentLine.append(currentAtom); currentAtom.setLength(0); } String s = currentLine.toString() + currentAtom; int width = fontMetrics.stringWidth(s); if (lineBreak || width >= widthLimit - fontMetrics.charWidth('w')) { if (!currentLine.isEmpty()) { lines.add(currentLine.toString()); currentLine = new StringBuilder(); } else { lines.add(currentAtom.toString()); currentAtom.setLength(0); } } } String s = currentLine.toString() + currentAtom; if (!s.isEmpty()) { lines.add(s); } return ArrayUtilRt.toStringArray(lines); } public static void setActionNameAndMnemonic(@NotNull @Nls String text, @NotNull Action action) { assignMnemonic(text, action); text = text.replaceAll("&", ""); action.putValue(Action.NAME, text); } public static void assignMnemonic(@NotNull @Nls String text, @NotNull Action action) { int mnemoPos = text.indexOf('&'); if (mnemoPos >= 0 && mnemoPos < text.length() - 2) { String mnemoChar = text.substring(mnemoPos + 1, mnemoPos + 2).trim(); if (mnemoChar.length() == 1) { action.putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnemoChar.charAt(0))); } } } public static @NotNull Font getLabelFont(@NotNull FontSize size) { return getFont(size, null); } public static @NotNull Font getFont(@NotNull FontSize size, @Nullable Font base) { if (base == null) base = StartupUiUtil.getLabelFont(); return JBFont.create(base).deriveFont(getFontSize(size)); } public static float getFontSize(@NotNull FontSize size) { int defSize = StartupUiUtil.getLabelFont().getSize(); return switch (size) { case SMALL -> Math.max(defSize - JBUIScale.scale(2f), JBUIScale.scale(11f)); case MINI -> Math.max(defSize - JBUIScale.scale(4f), JBUIScale.scale(9f)); default -> defSize; }; } public static @NotNull Color getLabelFontColor(@NotNull FontColor fontColor) { Color defColor = getLabelForeground(); if (fontColor == FontColor.BRIGHTER) { return new JBColor(new Color(Math.min(defColor.getRed() + 50, 255), Math.min(defColor.getGreen() + 50, 255), Math.min( defColor.getBlue() + 50, 255)), defColor.darker()); } return defColor; } public static int getCheckBoxTextHorizontalOffset(@NotNull JCheckBox cb) { // logic copied from javax.swing.plaf.basic.BasicRadioButtonUI.paint ButtonUI ui = cb.getUI(); Icon buttonIcon = cb.getIcon(); if (buttonIcon == null && ui != null) { if (ui instanceof BasicRadioButtonUI) { buttonIcon = ((BasicRadioButtonUI)ui).getDefaultIcon(); } } return getButtonTextHorizontalOffset(cb, cb.getSize(new Dimension()), buttonIcon); } public static int getButtonTextHorizontalOffset(@NotNull AbstractButton button, @NotNull Dimension size, @Nullable Icon buttonIcon) { String text = button.getText(); Rectangle viewRect = new Rectangle(); Rectangle iconRect = new Rectangle(); Rectangle textRect = new Rectangle(); Insets i = button.getInsets(); viewRect.y = i.top; viewRect.width = size.width - (i.right + viewRect.x); viewRect.height = size.height - (i.bottom + viewRect.y); SwingUtilities.layoutCompoundLabel( button, button.getFontMetrics(button.getFont()), text, buttonIcon, button.getVerticalAlignment(), button.getHorizontalAlignment(), button.getVerticalTextPosition(), button.getHorizontalTextPosition(), viewRect, iconRect, textRect, text == null ? 0 : button.getIconTextGap()); return textRect.x; } public static int getScrollBarWidth() { return UIManager.getInt("ScrollBar.width"); } public static Color getLabelBackground() { return UIManager.getColor("Label.background"); } public static @NotNull Color getLabelForeground() { return JBColor.namedColor("Label.foreground", new JBColor(Gray._0, Gray.xBB)); } public static @NotNull Color getLabelSuccessForeground() { return JBColor.namedColor("Label.successForeground", 0x368746, 0x50A661); } public static @NotNull Color getErrorForeground() { return NamedColorUtil.getErrorForeground(); } public static @NotNull Color getLabelDisabledForeground() { return JBColor.namedColor("Label.disabledForeground", JBColor.GRAY); } public static @NotNull Color getLabelInfoForeground() { return JBColor.namedColor("Label.infoForeground", new JBColor(Gray._120, Gray._135)); } public static @NotNull Color getContextHelpForeground() { return JBUI.CurrentTheme.ContextHelp.FOREGROUND; } public static @Nls @NotNull String removeMnemonic(@Nls @NotNull String s) { return TextWithMnemonic.parse(s).getText(); } public static int getDisplayMnemonicIndex(@NotNull String s) { int idx = s.indexOf('&'); if (idx >= 0 && idx != s.length() - 1 && idx == s.lastIndexOf('&')) return idx; idx = s.indexOf(MNEMONIC); if (idx >= 0 && idx != s.length() - 1 && idx == s.lastIndexOf(MNEMONIC)) return idx; return -1; } public static @Nls String replaceMnemonicAmpersand(@Nls String value) { return BundleBase.replaceMnemonicAmpersand(value); } /** * @deprecated use {@link #getTreeForeground()} */ @Deprecated(forRemoval = true) public static @NotNull Color getTreeTextForeground() { return getTreeForeground(); } /** * @deprecated use {@link #getTreeBackground()} */ @Deprecated public static @NotNull Color getTreeTextBackground() { return getTreeBackground(); } public static Color getFieldForegroundColor() { return UIManager.getColor("field.foreground"); } public static Color getActiveTextColor() { return UIManager.getColor("textActiveText"); } public static @NotNull Color getInactiveTextColor() { return NamedColorUtil.getInactiveTextColor(); } public static Color getInactiveTextFieldBackgroundColor() { return UIManager.getColor("TextField.inactiveBackground"); } public static Color getTreeSelectionBorderColor() { return UIManager.getColor("Tree.selectionBorderColor"); } public static int getTreeRightChildIndent() { return UIManager.getInt("Tree.rightChildIndent"); } public static int getTreeLeftChildIndent() { return UIManager.getInt("Tree.leftChildIndent"); } public static @NotNull Color getToolTipBackground() { return JBColor.namedColor("ToolTip.background", new JBColor(Gray.xF2, new Color(0x3c3f41))); } public static @NotNull Color getToolTipActionBackground() { return JBColor.namedColor("ToolTip.Actions.background", new JBColor(Gray.xEB, new Color(0x43474a))); } public static @NotNull Color getToolTipForeground() { return JBColor.namedColor("ToolTip.foreground", new JBColor(Gray.x00, Gray.xBF)); } public static Color getComboBoxDisabledForeground() { return UIManager.getColor("ComboBox.disabledForeground"); } public static Color getComboBoxDisabledBackground() { return UIManager.getColor("ComboBox.disabledBackground"); } public static Color getButtonSelectColor() { return UIManager.getColor("Button.select"); } public static Integer getPropertyMaxGutterIconWidth(@NotNull String propertyPrefix) { return (Integer)UIManager.get(propertyPrefix + ".maxGutterIconWidth"); } public static Color getMenuItemDisabledForeground() { return UIManager.getColor("MenuItem.disabledForeground"); } public static Object getMenuItemDisabledForegroundObject() { return UIManager.get("MenuItem.disabledForeground"); } public static Object getTabbedPanePaintContentBorder(final @NotNull JComponent c) { return c.getClientProperty("TabbedPane.paintContentBorder"); } public static Color getTableGridColor() { return UIManager.getColor("Table.gridColor"); } public static @NotNull Color getPanelBackground() { return JBColor.PanelBackground; } public static Color getEditorPaneBackground() { return UIManager.getColor("EditorPane.background"); } public static Color getTableFocusCellBackground() { return UIManager.getColor(TABLE_FOCUS_CELL_BACKGROUND_PROPERTY); } public static Color getTextFieldForeground() { return UIManager.getColor("TextField.foreground"); } public static Color getTextFieldBackground() { return UIManager.getColor("TextField.background"); } public static Color getTextFieldDisabledBackground() { return UIManager.getColor("TextField.disabledBackground"); } public static Font getButtonFont() { return UIManager.getFont("Button.font"); } public static Font getToolTipFont() { return UIManager.getFont("ToolTip.font"); } public static void setSliderIsFilled(final @NotNull JSlider slider, final boolean value) { slider.putClientProperty("JSlider.isFilled", value); } public static Color getLabelTextForeground() { return UIManager.getColor("Label.foreground"); } public static Color getControlColor() { return UIManager.getColor("control"); } public static Font getOptionPaneMessageFont() { return UIManager.getFont("OptionPane.messageFont"); } /** * @deprecated Use {@link FontUtil#getMenuFont()} */ @Deprecated @SuppressWarnings("unused") public static Font getMenuFont() { return FontUtil.getMenuFont(); } /** * @deprecated use {@link JBUI.CurrentTheme.CustomFrameDecorations#separatorForeground()} */ @Deprecated(forRemoval = true) public static @NotNull Color getSeparatorColor() { return JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground(); } public static Border getTableFocusCellHighlightBorder() { return UIManager.getBorder("Table.focusCellHighlightBorder"); } /** * @deprecated unsupported UI feature */ @Deprecated public static void setLineStyleAngled(@SuppressWarnings("unused") @NotNull JTree component) { } public static Color getTableFocusCellForeground() { return UIManager.getColor("Table.focusCellForeground"); } public static Border getTextFieldBorder() { return UIManager.getBorder("TextField.border"); } public static @NotNull Icon getErrorIcon() { return Objects.requireNonNullElse(UIManager.getIcon("OptionPane.errorIcon"), AllIcons.General.ErrorDialog); } public static @NotNull Icon getInformationIcon() { return Objects.requireNonNullElse(UIManager.getIcon("OptionPane.informationIcon"), AllIcons.General.InformationDialog); } public static @NotNull Icon getQuestionIcon() { return Objects.requireNonNullElse(UIManager.getIcon("OptionPane.questionIcon"), AllIcons.General.QuestionDialog); } public static @NotNull Icon getWarningIcon() { return Objects.requireNonNullElse(UIManager.getIcon("OptionPane.warningIcon"), AllIcons.General.WarningDialog); } public static @NotNull Icon getBalloonInformationIcon() { return AllIcons.General.BalloonInformation; } public static @NotNull Icon getBalloonWarningIcon() { return AllIcons.General.BalloonWarning; } public static @NotNull Icon getBalloonErrorIcon() { return AllIcons.General.BalloonError; } public static @NotNull Icon getTreeNodeIcon(boolean expanded, boolean selected, boolean focused) { boolean white = selected && focused || StartupUiUtil.isUnderDarcula(); Icon expandedDefault = getTreeExpandedIcon(); Icon collapsedDefault = getTreeCollapsedIcon(); Icon expandedSelected = getTreeSelectedExpandedIcon(); Icon collapsedSelected = getTreeSelectedCollapsedIcon(); int width = Math.max( Math.max(expandedDefault.getIconWidth(), collapsedDefault.getIconWidth()), Math.max(expandedSelected.getIconWidth(), collapsedSelected.getIconWidth())); int height = Math.max( Math.max(expandedDefault.getIconHeight(), collapsedDefault.getIconHeight()), Math.max(expandedSelected.getIconHeight(), collapsedSelected.getIconHeight())); return new CenteredIcon(!white ? expanded ? expandedDefault : collapsedDefault : expanded ? expandedSelected : collapsedSelected, width, height, false); } public static @NotNull Icon getTreeCollapsedIcon() { return UIManager.getIcon("Tree.collapsedIcon"); } public static @NotNull Icon getTreeExpandedIcon() { return UIManager.getIcon("Tree.expandedIcon"); } public static @NotNull Icon getTreeSelectedCollapsedIcon() { Icon icon = UIManager.getIcon("Tree.collapsedSelectedIcon"); return icon == null ? getTreeCollapsedIcon() : icon; } public static @NotNull Icon getTreeSelectedExpandedIcon() { Icon icon = UIManager.getIcon("Tree.expandedSelectedIcon"); return icon == null ? getTreeExpandedIcon() : icon; } public static Color getWindowColor() { return UIManager.getColor("window"); } public static Color getTextAreaForeground() { return UIManager.getColor("TextArea.foreground"); } public static Color getOptionPaneBackground() { return UIManager.getColor("OptionPane.background"); } /** * @deprecated Aqua Look-n-Feel is not supported anymore */ @Deprecated(forRemoval = true) public static boolean isUnderAquaLookAndFeel() { return SystemInfoRt.isMac && UIManager.getLookAndFeel().getName().contains("Mac OS X"); } /** * @deprecated Nimbus Look-n-Feel is deprecated and not supported anymore */ @Deprecated(forRemoval = true) public static boolean isUnderNimbusLookAndFeel() { return false; } public static boolean isUnderAquaBasedLookAndFeel() { return SystemInfoRt.isMac && (StartupUiUtil.isUnderDarcula() || isUnderIntelliJLaF()); } /** * Do not use it. Use theme properties instead of it. */ @Deprecated(forRemoval = true) public static boolean isUnderDefaultMacTheme() { return false; } /** * Do not use it. Use theme properties instead of it. */ @Deprecated(forRemoval = true) public static boolean isUnderWin10LookAndFeel() { return false; } /** * @deprecated Do not use it. Use {@link JBColor#isBright()} to detect if current LaF theme is dark or bright. * See also {@link com.intellij.openapi.editor.colors.EditorColorsManager#isDarkEditor()} */ @Deprecated(forRemoval = true) public static boolean isUnderDarcula() { return StartupUiUtil.INSTANCE.isDarkTheme(); } public static boolean isUnderIntelliJLaF() { return StartupUiUtil.isUnderIntelliJLaF(); } @Deprecated(forRemoval = true) public static boolean isUnderGTKLookAndFeel() { return SystemInfoRt.isUnix && !SystemInfoRt.isMac && UIManager.getLookAndFeel().getName().contains("GTK"); } public static boolean isGraphite() { if (!SystemInfoRt.isMac) { return false; } try { // https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSCell_Class/index.html#//apple_ref/doc/c_ref/NSGraphiteControlTint // NSGraphiteControlTint = 6 return Foundation.invoke("NSColor", "currentControlTint").intValue() == 6; } catch (Exception e) { return false; } } public static @NotNull Font getToolbarFont() { return SystemInfoRt.isMac ? getLabelFont(UIUtil.FontSize.SMALL) : StartupUiUtil.getLabelFont(); } public static @NotNull Color shade(@NotNull Color c, final double factor, final double alphaFactor) { assert factor >= 0 : factor; //noinspection UseJBColor return new Color( Math.min((int)Math.round(c.getRed() * factor), 255), Math.min((int)Math.round(c.getGreen() * factor), 255), Math.min((int)Math.round(c.getBlue() * factor), 255), Math.min((int)Math.round(c.getAlpha() * alphaFactor), 255) ); } /** * @param c1 first color to mix * @param c2 second color to mix * @param factor impact of color specified in {@code c2} * @return Mixed color */ public static @NotNull Color mix(@NotNull Color c1, final Color c2, final double factor) { assert 0 <= factor && factor <= 1.0 : factor; final double backFactor = 1.0 - factor; //noinspection UseJBColor return new Color( Math.min((int)Math.round(c1.getRed() * backFactor + c2.getRed() * factor), 255), Math.min((int)Math.round(c1.getGreen() * backFactor + c2.getGreen() * factor), 255), Math.min((int)Math.round(c1.getBlue() * backFactor + c2.getBlue() * factor), 255) ); } public static boolean isFullRowSelectionLAF() { return false; } public static boolean isUnderNativeMacLookAndFeel() { return StartupUiUtil.isUnderDarcula(); } public static int getListCellHPadding() { return isUnderDefaultMacTheme() ? 8 : isUnderWin10LookAndFeel() ? 2 : 7; } public static int getListCellVPadding() { return 1; } public static @NotNull JBInsets getRegularPanelInsets() { return JBInsets.create(REGULAR_PANEL_TOP_BOTTOM_INSET, REGULAR_PANEL_LEFT_RIGHT_INSET); } public static @NotNull Insets getListCellPadding() { return JBInsets.create(getListCellVPadding(), getListCellHPadding()); } public static @NotNull Insets getListViewportPadding() { return getListViewportPadding(false); } public static @NotNull Insets getListViewportPadding(boolean listWithAdvertiser) { return listWithAdvertiser ? new JBInsets(4, 0, 8, 0) : JBInsets.create(4, 0); } public static boolean isToUseDottedCellBorder() { return !isUnderNativeMacLookAndFeel(); } public static boolean isControlKeyDown(@NotNull MouseEvent mouseEvent) { return SystemInfoRt.isMac ? mouseEvent.isMetaDown() : mouseEvent.isControlDown(); } public static @NotNull String getControlKeyName() { return SystemInfoRt.isMac ? "Command" : "Ctrl"; } public static String @NotNull [] getStandardFontSizes() { return STANDARD_FONT_SIZES; } public static void setupEnclosingDialogBounds(final @NotNull JComponent component) { component.revalidate(); component.repaint(); final Window window = SwingUtilities.windowForComponent(component); if (window != null && (window.getSize().height < window.getMinimumSize().height || window.getSize().width < window.getMinimumSize().width)) { window.pack(); } } public static @NotNull String displayPropertiesToCSS(Font font, Color fg) { @NonNls StringBuilder rule = new StringBuilder("body {"); if (font != null) { rule.append(" font-family: "); rule.append(font.getFamily()); rule.append(" ; "); rule.append(" font-size: "); rule.append(font.getSize()); rule.append("pt ;"); if (font.isBold()) { rule.append(" font-weight: 700 ; "); } if (font.isItalic()) { rule.append(" font-style: italic ; "); } } if (fg != null) { rule.append(" color: #"); appendColor(fg, rule); rule.append(" ; "); } rule.append(" }"); return rule.toString(); } public static void appendColor(final @NotNull Color color, @NotNull StringBuilder sb) { if (color.getRed() < 16) sb.append('0'); sb.append(Integer.toHexString(color.getRed())); if (color.getGreen() < 16) sb.append('0'); sb.append(Integer.toHexString(color.getGreen())); if (color.getBlue() < 16) sb.append('0'); sb.append(Integer.toHexString(color.getBlue())); } /** * @param g graphics. * @param x top left X coordinate. * @param y top left Y coordinate. * @param x1 right bottom X coordinate. * @param y1 right bottom Y coordinate. */ public static void drawDottedRectangle(@NotNull Graphics g, int x, int y, int x1, int y1) { int i1; for (i1 = x; i1 <= x1; i1 += 2) { LinePainter2D.paint((Graphics2D)g, i1, y, i1, y); } for (i1 = y + (i1 != x1 + 1 ? 2 : 1); i1 <= y1; i1 += 2) { LinePainter2D.paint((Graphics2D)g, x1, i1, x1, i1); } for (i1 = x1 - (i1 != y1 + 1 ? 2 : 1); i1 >= x; i1 -= 2) { LinePainter2D.paint((Graphics2D)g, i1, y1, i1, y1); } for (i1 = y1 - (i1 != x - 1 ? 2 : 1); i1 >= y; i1 -= 2) { LinePainter2D.paint((Graphics2D)g, x, i1, x, i1); } } /** * Should be invoked only in EDT. * * @param g Graphics surface * @param startX Line start X coordinate * @param endX Line end X coordinate * @param lineY Line Y coordinate * @param bgColor Background color (optional) * @param fgColor Foreground color (optional) * @param opaque If opaque the image will be dr */ public static void drawBoldDottedLine(@NotNull Graphics2D g, final int startX, final int endX, final int lineY, final Color bgColor, final Color fgColor, final boolean opaque) { if (SystemInfoRt.isMac && !isRetina() || SystemInfoRt.isLinux) { drawAppleDottedLine(g, startX, endX, lineY, bgColor, fgColor, opaque); } else { drawBoringDottedLine(g, startX, endX, lineY, bgColor, fgColor, opaque); } } @SuppressWarnings({"UnregisteredNamedColor", "UseJBColor"}) public static void drawSearchMatch(@NotNull Graphics2D g, final float startX, final float endX, final int height) { drawSearchMatch(g, startX, endX, height, getSearchMatchGradientStartColor(), getSearchMatchGradientEndColor()); } public static @NotNull JBColor getSearchMatchGradientStartColor() { return JBColor.namedColor("SearchMatch.startBackground", JBColor.namedColor("SearchMatch.startColor", new Color(0xb3ffeaa2, true))); } public static @NotNull JBColor getSearchMatchGradientEndColor() { return JBColor.namedColor("SearchMatch.endBackground", JBColor.namedColor("SearchMatch.endColor", new Color(0xb3ffd042, true))); } public static void drawSearchMatch(@NotNull Graphics2D g, float startXf, float endXf, int height, Color c1, Color c2) { Graphics2D g2 = (Graphics2D)g.create(); try { g2.setPaint(getGradientPaint(startXf, 2, c1, startXf, height - 5, c2)); if (JreHiDpiUtil.isJreHiDPI(g2)) { GraphicsUtil.setupRoundedBorderAntialiasing(g2); g2.fill(new RoundRectangle2D.Float(startXf, 2, endXf - startXf, height - 4, 5, 5)); } else { int startX = (int)startXf; int endX = (int)endXf; g2.fillRect(startX, 3, endX - startX, height - 5); boolean drawRound = endXf - startXf > 4; if (drawRound) { LinePainter2D.paint(g2, startX - 1, 4, startX - 1, height - 4); LinePainter2D.paint(g2, endX, 4, endX, height - 4); g2.setColor(new Color(100, 100, 100, 50)); LinePainter2D.paint(g2, startX - 1, 4, startX - 1, height - 4); LinePainter2D.paint(g2, endX, 4, endX, height - 4); LinePainter2D.paint(g2, startX, 3, endX - 1, 3); LinePainter2D.paint(g2, startX, height - 3, endX - 1, height - 3); } } } finally { g2.dispose(); } } private static void drawBoringDottedLine(final @NotNull Graphics2D g, final int startX, final int endX, final int lineY, final Color bgColor, final Color fgColor, final boolean opaque) { final Color oldColor = g.getColor(); // Fill 2 lines with background color if (opaque && bgColor != null) { g.setColor(bgColor); LinePainter2D.paint(g, startX, lineY, endX, lineY); LinePainter2D.paint(g, startX, lineY + 1, endX, lineY + 1); } // Draw dotted line: // // CCC CCC CCC ... // CCC CCC CCC ... // // (where "C" - colored pixel, " " - white pixel) final int step = 4; final int startPosCorrection = startX % step < 3 ? 0 : 1; g.setColor(fgColor != null ? fgColor : oldColor); // Now draw bold line segments for (int dotXi = (startX / step + startPosCorrection) * step; dotXi < endX; dotXi += step) { LinePainter2D.paint(g, dotXi, lineY, dotXi + 1, lineY); LinePainter2D.paint(g, dotXi, lineY + 1, dotXi + 1, lineY + 1); } // restore color g.setColor(oldColor); } public static void drawGradientHToolbarBackground(@NotNull Graphics g, final int width, final int height) { final Graphics2D g2d = (Graphics2D)g; g2d.setPaint(getGradientPaint(0, 0, Gray._215, 0, height, Gray._200)); g2d.fillRect(0, 0, width, height); } public static void drawHeader(@NotNull Graphics g, int x, int width, int height, boolean active, boolean drawTopLine) { drawHeader(g, x, width, height, active, false, drawTopLine, true); } public static void drawHeader(@NotNull Graphics g, int x, int width, int height, boolean active, boolean toolWindow, boolean drawTopLine, boolean drawBottomLine) { GraphicsConfig config = GraphicsUtil.disableAAPainting(g); try { g.setColor(JBUI.CurrentTheme.ToolWindow.headerBackground(active)); g.fillRect(x, 0, width, height); g.setColor(JBUI.CurrentTheme.ToolWindow.headerBorderBackground()); if (drawTopLine) LinePainter2D.paint((Graphics2D)g, x, 0, width, 0); if (drawBottomLine) LinePainter2D.paint((Graphics2D)g, x, height - 1, width, height - 1); } finally { config.restore(); } } public static void drawDoubleSpaceDottedLine(final @NotNull Graphics2D g, final int start, final int end, final int xOrY, final Color fgColor, boolean horizontal) { g.setColor(fgColor); for (int dot = start; dot < end; dot += 3) { if (horizontal) { LinePainter2D.paint(g, dot, xOrY, dot, xOrY); } else { LinePainter2D.paint(g, xOrY, dot, xOrY, dot); } } } private static void drawAppleDottedLine(final @NotNull Graphics2D g, final int startX, final int endX, final int lineY, final Color bgColor, final Color fgColor, final boolean opaque) { final Color oldColor = g.getColor(); // Fill 3 lines with background color if (opaque && bgColor != null) { g.setColor(bgColor); LinePainter2D.paint(g, startX, lineY, endX, lineY); LinePainter2D.paint(g, startX, lineY + 1, endX, lineY + 1); LinePainter2D.paint(g, startX, lineY + 2, endX, lineY + 2); } AppleBoldDottedPainter painter = AppleBoldDottedPainter.forColor(Objects.requireNonNullElse(fgColor, oldColor)); painter.paint(g, startX, endX, lineY); } @Deprecated(forRemoval = true) public static void applyRenderingHints(@NotNull Graphics g) { GraphicsUtil.applyRenderingHints((Graphics2D)g); } /** * @deprecated Use {@link ImageUtil#createImage(int, int, int)} */ @Deprecated public static @NotNull BufferedImage createImage(int width, int height, int type) { return ImageUtil.createImage(width, height, type); } /** * Creates a HiDPI-aware BufferedImage in the graphics config scale. * * @param gc the graphics config * @param width the width in user coordinate space * @param height the height in user coordinate space * @param type the type of the image * @param rm the rounding mode to apply to width/height (for a HiDPI-aware image, the rounding is applied in the device space) * @return a HiDPI-aware BufferedImage in the graphics scale * @throws IllegalArgumentException if {@code width} or {@code height} is not greater than 0 */ public static @NotNull BufferedImage createImage(GraphicsConfiguration gc, double width, double height, int type, @NotNull RoundingMode rm) { if (JreHiDpiUtil.isJreHiDPI(gc)) { return new HiDPIImage(gc, width, height, type, rm); } //noinspection UndesirableClassUsage return new BufferedImage(rm.round(width), rm.round(height), type); } /** * Creates a HiDPI-aware BufferedImage in the component scale. * * @param component the component associated with the target graphics device * @param width the width in user coordinate space * @param height the height in user coordinate space * @param type the type of the image * @return a HiDPI-aware BufferedImage in the component scale * @throws IllegalArgumentException if {@code width} or {@code height} is not greater than 0 */ public static @NotNull BufferedImage createImage(@Nullable Component component, int width, int height, int type) { return ImageUtil.createImage(component == null ? null : component.getGraphicsConfiguration(), width, height, type); } /** * Configures composite to use for drawing text with the given graphics container. * <p/> * The whole idea is that <a href="http://en.wikipedia.org/wiki/X_Rendering_Extension">XRender-based</a> pipeline doesn't support * {@link AlphaComposite#SRC} and we should use {@link AlphaComposite#SRC_OVER} instead. * * @param g target graphics container */ public static void setupComposite(@NotNull Graphics2D g) { g.setComposite(X_RENDER_ACTIVE.get() ? AlphaComposite.SrcOver : AlphaComposite.Src); } /** * Dispatch all pending invocation events (if any) in the {@link com.intellij.ide.IdeEventQueue}, ignores and removes all other events from the queue. * In tests, consider using {@link com.intellij.testFramework.PlatformTestUtil#dispatchAllInvocationEventsInIdeEventQueue()} instead * Must be called from EDT. * * @see #pump() */ @TestOnly public static void dispatchAllInvocationEvents() { try (AccessToken ignored = ThreadContext.resetThreadContext()) { EDT.dispatchAllInvocationEvents(); } } public static void addAwtListener(@NotNull AWTEventListener listener, long mask, @NotNull Disposable parent) { StartupUiUtil.addAwtListener(mask, parent, listener); } public static void addParentChangeListener(@NotNull Component component, @NotNull PropertyChangeListener listener) { component.addPropertyChangeListener("ancestor", listener); } public static void drawVDottedLine(@NotNull Graphics2D g, int lineX, int startY, int endY, final @Nullable Color bgColor, final Color fgColor) { if (bgColor != null) { g.setColor(bgColor); LinePainter2D.paint(g, lineX, startY, lineX, endY); } g.setColor(fgColor); for (int i = startY / 2 * 2; i < endY; i += 2) { g.drawRect(lineX, i, 0, 0); } } public static void drawHDottedLine(@NotNull Graphics2D g, int startX, int endX, int lineY, final @Nullable Color bgColor, final Color fgColor) { if (bgColor != null) { g.setColor(bgColor); LinePainter2D.paint(g, startX, lineY, endX, lineY); } g.setColor(fgColor); for (int i = startX / 2 * 2; i < endX; i += 2) { g.drawRect(i, lineY, 0, 0); } } public static void drawDottedLine(@NotNull Graphics2D g, int x1, int y1, int x2, int y2, final @Nullable Color bgColor, final Color fgColor) { if (x1 == x2) { drawVDottedLine(g, x1, y1, y2, bgColor, fgColor); } else if (y1 == y2) { drawHDottedLine(g, x1, x2, y1, bgColor, fgColor); } else { throw new IllegalArgumentException("Only vertical or horizontal lines are supported"); } } public static void drawStringWithHighlighting(@NotNull Graphics g, @NotNull String s, int x, int y, Color foreground, Color highlighting) { g.setColor(highlighting); boolean isRetina = JreHiDpiUtil.isJreHiDPI((Graphics2D)g); float scale = 1 / JBUIScale.sysScale((Graphics2D)g); for (float i = x - 1; i <= x + 1; i += isRetina ? scale : 1) { for (float j = y - 1; j <= y + 1; j += isRetina ? scale : 1) { ((Graphics2D)g).drawString(s, i, j); } } g.setColor(foreground); g.drawString(s, x, y); } /** * Draws a centered string in the passed rectangle. * * @param g the {@link Graphics} instance to draw to * @param rect the {@link Rectangle} to use as bounding box * @param str the string to draw * @param horzCentered if true, the string will be centered horizontally * @param vertCentered if true, the string will be centered vertically */ public static void drawCenteredString(@NotNull Graphics2D g, @NotNull Rectangle rect, @NotNull String str, boolean horzCentered, boolean vertCentered) { FontMetrics fm = g.getFontMetrics(g.getFont()); int textWidth = fm.stringWidth(str) - 1; int x = horzCentered ? Math.max(rect.x, rect.x + (rect.width - textWidth) / 2) : rect.x; int y = vertCentered ? Math.max(rect.y, rect.y + rect.height / 2 + fm.getAscent() * 2 / 5) : rect.y; Shape oldClip = g.getClip(); g.clip(rect); g.drawString(str, x, y); g.setClip(oldClip); } /** * Draws a centered string in the passed rectangle. * * @param g the {@link Graphics} instance to draw to * @param rect the {@link Rectangle} to use as bounding box * @param str the string to draw */ public static void drawCenteredString(@NotNull Graphics2D g, @NotNull Rectangle rect, @NotNull String str) { drawCenteredString(g, rect, str, true, true); } /** * @param component to check whether it has focus within its component hierarchy * @return {@code true} if component or one of its parents has focus in a more general sense than UI focuses, * sometimes useful to limit various activities by checking the focus of the real UI, * but it could be unneeded in headless mode or in other scenarios. * @see Component#isFocusOwner() */ public static boolean isFocusAncestor(@NotNull Component component) { Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner == null) return false; if (SwingUtilities.isDescendingFrom(owner, component)) return true; while (component != null) { if (kindaHasFocus(component)) return true; component = component.getParent(); } return false; } /** * Get the parent of a component in a more general sense than UI parent, i.e., * if it doesn't have a real UI parent, use a foster one instead. * * @see UIUtil#setFosterParent(JComponent, Component) */ @ApiStatus.Experimental public static @Nullable Component getParent(@NotNull Component component) { WeakReference<Component> ref = ClientProperty.get(component, FOSTER_PARENT); if (ref != null) { Component fosterParent = ref.get(); if (fosterParent != null) { return fosterParent; } } return component.getParent(); } /** * Set a foster parent for a component, i.e., explicitly specify what should be treated * as the component's parent if it doesn't have a real UI one. * * @throws IllegalArgumentException if the establishment of requested link * will form a cycle in a generalized hierarchy graph. * @see UIUtil#getParent(Component) */ @ApiStatus.Internal @ApiStatus.Experimental public static void setFosterParent(@NotNull JComponent component, @Nullable Component parent) { WeakReference<Component> ref = validateFosterParent(component, parent); ClientProperty.put(component, FOSTER_PARENT, ref); } /** * An overload of {@link UIUtil#setFosterParent(JComponent, Component)} for windows. */ @ApiStatus.Internal @ApiStatus.Experimental public static void setFosterParent(@NotNull Window window, @Nullable Component parent) { WeakReference<Component> ref = validateFosterParent(window, parent); ClientProperty.put(window, FOSTER_PARENT, ref); } private static @Nullable WeakReference<Component> validateFosterParent(@NotNull Component component, @Nullable Component parent) { if (parent != null && isGeneralizedAncestor(component, parent)) { throw new IllegalArgumentException("Setting this component as a foster parent will form a cycle in a hierarchy graph"); } return parent != null ? new WeakReference<>(parent) : null; } private static boolean isGeneralizedAncestor(@NotNull Component ancestor, @NotNull Component descendant) { do { if (descendant == ancestor) { return true; } descendant = getParent(descendant); } while (descendant != null); return false; } private static boolean kindaHasFocus(@NotNull Component component) { if (GraphicsEnvironment.isHeadless()) { return true; } JComponent jComponent = component instanceof JComponent ? (JComponent)component : null; return jComponent != null && Boolean.TRUE.equals(jComponent.getClientProperty(HAS_FOCUS)); } /** * Checks if a component is focused in a more general sense than UI focuses, * sometimes useful to limit various activities by checking the focus of real UI, * but it could be unneeded in headless mode or in other scenarios. * * @see UIUtil#isShowing(Component) */ @ApiStatus.Experimental public static boolean hasFocus(@NotNull Component component) { return kindaHasFocus(component) || component.hasFocus(); } /** * Marks a component as focused */ @ApiStatus.Internal @ApiStatus.Experimental public static void markAsFocused(@NotNull JComponent component, boolean value) { if (GraphicsEnvironment.isHeadless()) { return; } component.putClientProperty(HAS_FOCUS, value ? Boolean.TRUE : null); } public static boolean isCloseClick(@NotNull MouseEvent e) { return isCloseClick(e, MouseEvent.MOUSE_PRESSED); } public static boolean isCloseClick(@NotNull MouseEvent e, int effectiveType) { if (e.isPopupTrigger() || e.getID() != effectiveType) return false; return e.getButton() == MouseEvent.BUTTON2 || e.getButton() == MouseEvent.BUTTON1 && e.isShiftDown(); } public static boolean isActionClick(@NotNull MouseEvent e) { return isActionClick(e, MouseEvent.MOUSE_PRESSED); } public static boolean isActionClick(@NotNull MouseEvent e, int effectiveType) { return isActionClick(e, effectiveType, false); } public static boolean isActionClick(@NotNull MouseEvent e, int effectiveType, boolean allowShift) { if (!allowShift && isCloseClick(e) || e.isPopupTrigger() || e.getID() != effectiveType) return false; return e.getButton() == MouseEvent.BUTTON1; } /** * Provides all input event modifiers including deprecated, since they are still used in IntelliJ platform */ @MagicConstant(flags = { Event.SHIFT_MASK, Event.CTRL_MASK, Event.META_MASK, Event.ALT_MASK, InputEvent.SHIFT_DOWN_MASK, InputEvent.CTRL_DOWN_MASK, InputEvent.META_DOWN_MASK, InputEvent.ALT_DOWN_MASK, InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON2_DOWN_MASK, InputEvent.BUTTON3_DOWN_MASK, InputEvent.ALT_GRAPH_DOWN_MASK, }) public static int getAllModifiers(@NotNull InputEvent event) { return event.getModifiers() | event.getModifiersEx(); } public static @NotNull Color getBgFillColor(@NotNull Component c) { Component parent = findNearestOpaque(c); return parent == null ? c.getBackground() : parent.getBackground(); } public static @Nullable Component findNearestOpaque(Component c) { return ComponentUtil.findParentByCondition(c, Component::isOpaque); } //x and y should be from {0, 0} to {parent.getWidth(), parent.getHeight()} public static @Nullable Component getDeepestComponentAt(@NotNull Component parent, int x, int y) { Component component = SwingUtilities.getDeepestComponentAt(parent, x, y); if (component != null && component.getParent() instanceof JRootPane rootPane) { // GlassPane case component = getDeepestComponentAtForComponent(parent, x, y, rootPane.getLayeredPane()); if (component == null) { component = getDeepestComponentAtForComponent(parent, x, y, rootPane.getContentPane()); } } if (component != null && component.getParent() instanceof JLayeredPane) { // Handle LoadingDecorator Component[] components = ((JLayeredPane)component.getParent()).getComponentsInLayer(JLayeredPane.DEFAULT_LAYER); if (components.length == 1 && ArrayUtilRt.indexOf(components, component, 0, components.length) == -1) { component = getDeepestComponentAtForComponent(parent, x, y, components[0]); } } return component; } private static Component getDeepestComponentAtForComponent(@NotNull Component parent, int x, int y, @NotNull Component component) { Point point = SwingUtilities.convertPoint(parent, new Point(x, y), component); return SwingUtilities.getDeepestComponentAt(component, point.x, point.y); } public static void layoutRecursively(@NotNull Component component) { if (!(component instanceof JComponent)) { return; } forEachComponentInHierarchy(component, Component::doLayout); } @Language("HTML") public static @NlsSafe @NotNull String getCssFontDeclaration(@NotNull Font font) { return getCssFontDeclaration(font, getLabelForeground(), JBUI.CurrentTheme.Link.Foreground.ENABLED, null); } @Language("HTML") public static @NlsSafe @NotNull String getCssFontDeclaration(@NotNull Font font, @Nullable Color fgColor, @Nullable Color linkColor, @Nullable String liImg) { @Language("HTML") String familyAndSize = "font-family:'" + font.getFamily() + "'; font-size:" + font.getSize() + "pt;"; return "<style>\n" + "body, div, td, p {" + familyAndSize + (fgColor != null ? " color:#" + ColorUtil.toHex(fgColor) + ';' : "") + "}\n" + "a {" + familyAndSize + (linkColor != null ? " color:#" + ColorUtil.toHex(linkColor) + ';' : "") + "}\n" + "code {font-size:" + font.getSize() + "pt;}\n" + "ul {list-style:disc; margin-left:15px;}\n" + "</style>"; } public static @NotNull Color getFocusedFillColor() { return toAlpha(getListSelectionBackground(true), 100); } public static @NotNull Color getFocusedBoundsColor() { return NamedColorUtil.getBoundsColor(); } public static @NotNull Color getBoundsColor() { return NamedColorUtil.getBoundsColor(); } public static @NotNull Color toAlpha(final Color color, final int alpha) { Color actual = color != null ? color : Color.black; return new Color(actual.getRed(), actual.getGreen(), actual.getBlue(), alpha); } /** * @param component to check whether it can be focused or not * @return {@code true} if component is not {@code null} and can be focused * @see Component#isRequestFocusAccepted(boolean, boolean, FocusEvent.Cause) */ public static boolean isFocusable(@Nullable Component component) { return component != null && component.isFocusable() && component.isEnabled() && component.isShowing(); } /** * @deprecated use {@link com.intellij.openapi.wm.IdeFocusManager} */ @Deprecated public static void requestFocus(@NotNull JComponent c) { if (c.isShowing()) { c.requestFocus(); } else { SwingUtilities.invokeLater(c::requestFocus); } } // whitelist for component types that provide obvious 'focused' view public static boolean canDisplayFocusedState(@NotNull Component component) { return component instanceof JTextComponent || component instanceof AbstractButton || component instanceof JComboBox; } //todo maybe should do for all kind of listeners via the AWTEventMulticaster class public static void dispose(final Component c) { if (c == null) return; final MouseListener[] mouseListeners = c.getMouseListeners(); for (MouseListener each : mouseListeners) { c.removeMouseListener(each); } final MouseMotionListener[] motionListeners = c.getMouseMotionListeners(); for (MouseMotionListener each : motionListeners) { c.removeMouseMotionListener(each); } final MouseWheelListener[] mouseWheelListeners = c.getMouseWheelListeners(); for (MouseWheelListener each : mouseWheelListeners) { c.removeMouseWheelListener(each); } if (c instanceof AbstractButton) { final ActionListener[] listeners = ((AbstractButton)c).getActionListeners(); for (ActionListener listener : listeners) { ((AbstractButton)c).removeActionListener(listener); } } } public static void disposeProgress(final @NotNull JProgressBar progress) { if (!isUnderNativeMacLookAndFeel()) return; SwingUtilities.invokeLater(() -> progress.setUI(null)); } public static @Nullable Component findUltimateParent(@Nullable Component c) { return c == null ? null : ComponentUtil.findUltimateParent(c); } public static @NotNull Color getHeaderActiveColor() { return ACTIVE_HEADER_COLOR; } public static @NotNull Color getFocusedBorderColor() { return JBUI.CurrentTheme.Focus.focusColor(); } public static @NotNull Color getHeaderInactiveColor() { return INACTIVE_HEADER_COLOR; } public static @NotNull Font getTitledBorderFont() { return StartupUiUtil.getLabelFont(); } /** * @deprecated use {@link HTMLEditorKitBuilder} */ @Deprecated public static @NotNull HTMLEditorKit getHTMLEditorKit() { return HTMLEditorKitBuilder.simple(); } /** * @deprecated use {@link HTMLEditorKitBuilder} */ @Deprecated public static @NotNull HTMLEditorKit getHTMLEditorKit(boolean noGapsBetweenParagraphs) { HTMLEditorKitBuilder builder = new HTMLEditorKitBuilder(); if (!noGapsBetweenParagraphs) { builder.withGapsBetweenParagraphs(); } return builder.build(); } /** * @deprecated use {@link HTMLEditorKitBuilder#withWordWrapViewFactory()} */ @Deprecated public static final class JBWordWrapHtmlEditorKit extends JBHtmlEditorKit { @Override public ViewFactory getViewFactory() { return ExtendableHTMLViewFactory.DEFAULT_WORD_WRAP; } } public static @NotNull Font getFontWithFallbackIfNeeded(@NotNull Font font, @NotNull String text) { if (!SystemInfoRt.isMac /* 'getFontWithFallback' does nothing on macOS */ && font.canDisplayUpTo(text) != -1) { return getFontWithFallback(font); } else { return font; } } public static @NotNull Font getFontWithFallbackIfNeeded(@NotNull Font font, @NotNull char[] text) { if (!SystemInfoRt.isMac /* 'getFontWithFallback' does nothing on macOS */ && font.canDisplayUpTo(text, 0, text.length) != -1) { return getFontWithFallback(font); } else { return font; } } public static @NotNull FontUIResource getFontWithFallback(@NotNull Font font) { // On macOS font fallback is implemented in JDK by default // (except for explicitly registered fonts, e.g. the fonts we bundle with IDE, for them we don't have a solution now) if (!SystemInfoRt.isMac) { try { if (!FontUtilities.fontSupportsDefaultEncoding(font)) { font = FontUtilities.getCompositeFontUIResource(font); } } catch (Throwable e) { // this might happen e.g., if we're running under newer runtime, forbidding access to sun.font package getLogger().warn(e); // this might not give the same result, but we have no choice here return StartupUiUtilKt.getFontWithFallback(font.getFamily(), font.getStyle(), font.getSize()); } } return font instanceof FontUIResource ? (FontUIResource)font : new FontUIResource(font); } public static @NotNull FontUIResource getFontWithFallback(@Nullable String familyName, @JdkConstants.FontStyle int style, int size) { return StartupUiUtilKt.getFontWithFallback(familyName, style, size); } //Escape error-prone HTML data (if any) when we use it in renderers, see IDEA-170768 public static <T> T htmlInjectionGuard(T toRender) { if (toRender instanceof String && Strings.toLowerCase((String)toRender).startsWith("<html>")) { //noinspection unchecked return (T)("<html>" + Strings.escapeXmlEntities((String)toRender)); } return toRender; } /** * @deprecated This method is a hack. Please avoid it and create borderless {@code JScrollPane} manually using * {@link com.intellij.ui.ScrollPaneFactory#createScrollPane(Component, boolean)}. */ @Deprecated public static void removeScrollBorder(final Component c) { JBIterable<JScrollPane> scrollPanes = uiTraverser(c) .expand(o -> o == c || o instanceof JPanel || o instanceof JLayeredPane) .filter(JScrollPane.class); for (JScrollPane scrollPane : scrollPanes) { Integer keepBorderSides = ClientProperty.get(scrollPane, KEEP_BORDER_SIDES); if (keepBorderSides != null) { if (scrollPane.getBorder() instanceof LineBorder) { Color color = ((LineBorder)scrollPane.getBorder()).getLineColor(); scrollPane.setBorder(new SideBorder(color, keepBorderSides.intValue())); } else { scrollPane.setBorder(new SideBorder(NamedColorUtil.getBoundsColor(), keepBorderSides.intValue())); } } else { scrollPane.setBorder(new SideBorder(NamedColorUtil.getBoundsColor(), SideBorder.NONE)); } } } public static @NotNull @NlsSafe String toHtml(@NotNull @Nls String html) { return toHtml(html, 0); } public static @NotNull @NlsSafe String toHtml(@NotNull @Nls String html, final int hPadding) { final @NlsSafe String withClosedTag = CLOSE_TAG_PATTERN.matcher(html).replaceAll("<$1$2></$1>"); Font font = StartupUiUtil.getLabelFont(); @NonNls String family = font.getFamily(); int size = font.getSize(); return "<html><style>body { font-family: " + family + "; font-size: " + size + ";} ul li {list-style-type:circle;}</style>" + addPadding(withClosedTag, hPadding) + "</html>"; } public static @NotNull String addPadding(@NotNull String html, int hPadding) { return String.format("<p style=\"margin: 0 %dpx 0 %dpx;\">%s</p>", hPadding, hPadding, html); } /** * Please use Application.invokeLater() with a modality state (or ModalityUiUtil, or TransactionGuard methods), unless you work with Swings internals * and 'runnable' deals with Swings components only and doesn't access any PSI, VirtualFiles, project/module model or other project settings. For those, use ModalityUiUtil, application.invoke* or TransactionGuard methods.<p/> * <p> * On AWT thread, invoked runnable immediately, otherwise do {@link SwingUtilities#invokeLater(Runnable)} on it. */ public static void invokeLaterIfNeeded(@NotNull Runnable runnable) { EdtInvocationManager.invokeLaterIfNeeded(runnable); } /** * Please use Application.invokeAndWait() with a modality state (or ModalityUiUtil, or TransactionGuard methods), unless you work with Swings internals * and 'runnable' deals with Swings components only and doesn't access any PSI, VirtualFiles, project/module model or other project settings.<p/> * <p> * Invoke and wait in the event dispatch thread * or in the current thread if the current thread * is event queue thread. * DO NOT INVOKE THIS METHOD FROM UNDER READ ACTION. * * @param runnable a runnable to invoke */ @ApiStatus.Obsolete public static void invokeAndWaitIfNeeded(@NotNull Runnable runnable) { EdtInvocationManager.invokeAndWaitIfNeeded(runnable); } /** * Please use Application.invokeAndWait() with a modality state (or ModalityUiUtil, or TransactionGuard methods), unless you work with Swings internals * and 'runnable' deals with Swings components only and doesn't access any PSI, VirtualFiles, project/module model or other project settings.<p/> * <p> * Invoke and wait in the event dispatch thread * or in the current thread if the current thread * is event queue thread. * DO NOT INVOKE THIS METHOD FROM UNDER READ ACTION. * * @param computable a runnable to invoke */ @ApiStatus.Obsolete public static <T> T invokeAndWaitIfNeeded(@NotNull Computable<T> computable) { final Ref<T> result = Ref.create(); EdtInvocationManager.invokeAndWaitIfNeeded(() -> result.set(computable.compute())); return result.get(); } public static void maybeInstall(@NotNull InputMap map, String action, KeyStroke stroke) { if (map.get(stroke) == null) { map.put(stroke, action); } } /** * Avoid blinking while changing background. * * @param component component. * @param background new background. */ public static void changeBackGround(final @NotNull Component component, final Color background) { final Color oldBackGround = component.getBackground(); if (background == null || !background.equals(oldBackGround)) { component.setBackground(background); } } public static @Nullable ComboPopup getComboBoxPopup(@NotNull JComboBox<?> comboBox) { final ComboBoxUI ui = comboBox.getUI(); if (ui instanceof BasicComboBoxUI) { return ReflectionUtil.getField(BasicComboBoxUI.class, ui, ComboPopup.class, "popup"); } return null; } public static void fixFormattedField(@NotNull JFormattedTextField field) { if (SystemInfoRt.isMac) { final int commandKeyMask; try { commandKeyMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); } catch (HeadlessException e) { return; } final InputMap inputMap = field.getInputMap(); final KeyStroke copyKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, commandKeyMask); inputMap.put(copyKeyStroke, "copy-to-clipboard"); final KeyStroke pasteKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_V, commandKeyMask); inputMap.put(pasteKeyStroke, "paste-from-clipboard"); final KeyStroke cutKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_X, commandKeyMask); inputMap.put(cutKeyStroke, "cut-to-clipboard"); } } public static boolean isPrinting(Graphics g) { return g instanceof PrintGraphics || g instanceof PrinterGraphics; } public static boolean isSelectionButtonDown(@NotNull MouseEvent e) { return e.isShiftDown() || e.isControlDown() || e.isMetaDown(); } public static boolean isToggleListSelectionEvent(@NotNull MouseEvent e) { return SwingUtilities.isLeftMouseButton(e) && (SystemInfoRt.isMac ? e.isMetaDown() : e.isControlDown()) && !e.isPopupTrigger(); } /** * @see JBUI.CurrentTheme.List#rowHeight() */ public static final int LIST_FIXED_CELL_HEIGHT = 20; /** * The main difference from javax.swing.SwingUtilities#isDescendingFrom(Component, Component) is that this method * uses getInvoker() instead of getParent() when it meets JPopupMenu * * @param child child component * @param parent parent component * @return true if parent if a top parent of child, false otherwise * @see SwingUtilities#isDescendingFrom(Component, Component) */ public static boolean isDescendingFrom(@Nullable Component child, @NotNull Component parent) { while (child != null && child != parent) { child = child instanceof JPopupMenu ? ((JPopupMenu)child).getInvoker() : child.getParent(); } return child == parent; } /** * Searches above in the component hierarchy starting from the specified component. * Note that the initial component is also checked. * * @param type expected class * @param component initial component * @return a component of the specified type, or {@code null} if the search is failed * @see SwingUtilities#getAncestorOfClass */ @Contract(pure = true) public static @Nullable <T> T getParentOfType(@NotNull Class<? extends T> type, Component component) { return ComponentUtil.getParentOfType(type, component); } public static @NotNull JBIterable<Component> uiParents(@Nullable Component c, boolean strict) { return strict ? JBIterable.generate(c, c1 -> c1.getParent()).skip(1) : JBIterable.generate(c, c1 -> c1.getParent()); } public static @NotNull JBIterable<Component> uiChildren(@Nullable Component component) { if (!(component instanceof Container container)) return JBIterable.empty(); return JBIterable.of(container.getComponents()); } public static @NotNull JBTreeTraverser<Component> uiTraverser(@Nullable Component component) { return UI_TRAVERSER.withRoot(component).expandAndFilter(o -> !(o instanceof CellRendererPane)); } public static final Key<Iterable<? extends Component>> NOT_IN_HIERARCHY_COMPONENTS = ComponentUtil.NOT_IN_HIERARCHY_COMPONENTS; private static final JBTreeTraverser<Component> UI_TRAVERSER = JBTreeTraverser.from((Function<Component, JBIterable<Component>>)c -> { if (c instanceof Window window && isDisposed(window)) { return JBIterable.empty(); } JBIterable<Component> result; if (c instanceof JMenu) { result = JBIterable.of(((JMenu)c).getMenuComponents()); } else { result = uiChildren(c); } if (c instanceof JComponent jc) { Iterable<? extends Component> orphans = ClientProperty.get(jc, NOT_IN_HIERARCHY_COMPONENTS); if (orphans != null) { result = result.append(orphans); } JPopupMenu jpm = jc.getComponentPopupMenu(); if (jpm != null && jpm.isVisible() && jpm.getInvoker() == jc) { result = result.append(Collections.singletonList(jpm)); } } return result; }); private static boolean isDisposed(Window window) { Window w = window; while (w != null) { if (w instanceof DisposableWindow dw && dw.isWindowDisposed()) { return true; } w = w.getOwner(); } return false; } @ApiStatus.Internal public static void addNotInHierarchyComponents(@NotNull JComponent container, @NotNull Iterable<Component> components) { Iterable<? extends Component> oldValue = ClientProperty.get(container, NOT_IN_HIERARCHY_COMPONENTS); if (oldValue == null) { ClientProperty.put(container, NOT_IN_HIERARCHY_COMPONENTS, components); return; } ClientProperty.put(container, NOT_IN_HIERARCHY_COMPONENTS, IterablesConcat.concat(oldValue, components)); } public static void scrollListToVisibleIfNeeded(final @NotNull JList<?> list) { SwingUtilities.invokeLater(() -> { final int selectedIndex = list.getSelectedIndex(); if (selectedIndex >= 0) { final Rectangle visibleRect = list.getVisibleRect(); final Rectangle cellBounds = list.getCellBounds(selectedIndex, selectedIndex); if (!visibleRect.contains(cellBounds)) { list.scrollRectToVisible(cellBounds); } } }); } public static @Nullable <T extends JComponent> T findComponentOfType(JComponent parent, Class<T> cls) { if (parent == null || cls.isInstance(parent)) { return cls.cast(parent); } for (Component component : parent.getComponents()) { if (component instanceof JComponent) { T comp = findComponentOfType((JComponent)component, cls); if (comp != null) return comp; } } return null; } public static @NotNull <T extends JComponent> List<T> findComponentsOfType(@Nullable JComponent parent, @NotNull Class<? extends T> cls) { return ComponentUtil.findComponentsOfType(parent, cls); } public static final class TextPainter { private final List<String> myLines = new ArrayList<>(); private boolean myDrawShadow; private Color myShadowColor; private float myLineSpacing; private Font myFont; private Color myColor; public TextPainter() { myDrawShadow = StartupUiUtil.isUnderDarcula(); myShadowColor = StartupUiUtil.isUnderDarcula() ? Gray._0.withAlpha(100) : Gray._220; myLineSpacing = 1.0f; } public @NotNull TextPainter withShadow(boolean drawShadow, Color shadowColor) { myDrawShadow = drawShadow; myShadowColor = shadowColor; return this; } public @NotNull TextPainter withLineSpacing(float lineSpacing) { myLineSpacing = lineSpacing; return this; } public @NotNull TextPainter withColor(Color color) { myColor = color; return this; } public @NotNull TextPainter withFont(Font font) { myFont = font; return this; } public @NotNull TextPainter appendLine(String text) { if (text == null || text.isEmpty()) return this; myLines.add(text); return this; } /** * _position(block width, block height) => (x, y) of the block */ public void draw(final @NotNull Graphics g, @NotNull PairFunction<? super Integer, ? super Integer, ? extends Couple<Integer>> _position) { Font oldFont = null; if (myFont != null) { oldFont = g.getFont(); g.setFont(myFont); } Color oldColor = null; if (myColor != null) { oldColor = g.getColor(); g.setColor(myColor); } try { final int[] maxWidth = {0}; final int[] height = {0}; ContainerUtil.process(myLines, text -> { FontMetrics fm = g.getFontMetrics(); maxWidth[0] = Math.max(fm.stringWidth(text.replace("<shortcut>", "").replace("</shortcut>", "")), maxWidth[0]); height[0] += (fm.getHeight() + fm.getLeading()) * myLineSpacing; return true; }); final Couple<Integer> position = _position.fun(maxWidth[0] + 20, height[0]); assert position != null; final int[] yOffset = {position.getSecond()}; ContainerUtil.process(myLines, text -> { String shortcut = ""; if (text.contains("<shortcut>")) { shortcut = text.substring(text.indexOf("<shortcut>") + "<shortcut>".length(), text.indexOf("</shortcut>")); text = text.substring(0, text.indexOf("<shortcut>")); } int x = position.getFirst() + 10; FontMetrics fm = g.getFontMetrics(); if (myDrawShadow) { int xOff = StartupUiUtil.isUnderDarcula() ? 1 : 0; Color oldColor1 = g.getColor(); g.setColor(myShadowColor); int yOff = 1; g.drawString(text, x + xOff, yOffset[0] + yOff); g.setColor(oldColor1); } g.drawString(text, x, yOffset[0]); if (!Strings.isEmpty(shortcut)) { Color oldColor1 = g.getColor(); g.setColor(JBColor.namedColor("Editor.shortcutForeground", new JBColor(new Color(82, 99, 155), new Color(88, 157, 246)))); g.drawString(shortcut, x + fm.stringWidth(text + (StartupUiUtil.isUnderDarcula() ? " " : "")), yOffset[0]); g.setColor(oldColor1); } yOffset[0] += (fm.getHeight() + fm.getLeading()) * myLineSpacing; return true; }); } finally { if (oldFont != null) g.setFont(oldFont); if (oldColor != null) g.setColor(oldColor); } } } public static @Nullable JRootPane getRootPane(Component c) { JRootPane root = ComponentUtil.getParentOfType((Class<? extends JRootPane>)JRootPane.class, c); if (root != null) return root; Component eachParent = c; while (eachParent != null) { if (eachParent instanceof JComponent) { @SuppressWarnings("unchecked") WeakReference<JRootPane> pane = (WeakReference<JRootPane>)((JComponent)eachParent).getClientProperty(ROOT_PANE); if (pane != null) return pane.get(); } eachParent = eachParent.getParent(); } return null; } public static void setFutureRootPane(@NotNull JComponent c, @NotNull JRootPane pane) { c.putClientProperty(ROOT_PANE, new WeakReference<>(pane)); } public static boolean isDialogRootPane(JRootPane rootPane) { if (rootPane != null) { final Object isDialog = rootPane.getClientProperty("DIALOG_ROOT_PANE"); return isDialog instanceof Boolean && ((Boolean)isDialog).booleanValue(); } return false; } public static void runWhenVisibilityChanged(@NotNull Component component, Runnable runnable) { component.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent e) { runnable.run(); } @Override public void componentHidden(ComponentEvent e) { runnable.run(); } }); } public static @Nullable JComponent mergeComponentsWithAnchor(PanelWithAnchor @NotNull ... panels) { return mergeComponentsWithAnchor(Arrays.asList(panels)); } public static @Nullable JComponent mergeComponentsWithAnchor(@NotNull Collection<? extends PanelWithAnchor> panels) { return mergeComponentsWithAnchor(panels, false); } public static @Nullable JComponent mergeComponentsWithAnchor(@NotNull Collection<? extends PanelWithAnchor> panels, boolean visibleOnly) { JComponent maxWidthAnchor = null; int maxWidth = 0; for (PanelWithAnchor panel : panels) { if (visibleOnly && (panel instanceof JComponent) && !((JComponent)panel).isVisible()) { continue; } JComponent anchor = panel != null ? panel.getOwnAnchor() : null; if (anchor != null) { panel.setAnchor(null); // to get own preferred size int anchorWidth = anchor.getPreferredSize().width; if (maxWidth < anchorWidth) { maxWidth = anchorWidth; maxWidthAnchor = anchor; } } } for (PanelWithAnchor panel : panels) { if (panel != null) { panel.setAnchor(maxWidthAnchor); if (panel instanceof JComponent) { ((JComponent)panel).revalidate(); ((JComponent)panel).repaint(); } } } return maxWidthAnchor; } public static void setNotOpaqueRecursively(@NotNull Component component) { setOpaqueRecursively(component, false); } public static void setOpaqueRecursively(@NotNull Component component, boolean opaque) { if (!(component instanceof JComponent)) { return; } forEachComponentInHierarchy(component, c -> { if (c instanceof JComponent) { ((JComponent)c).setOpaque(opaque); } }); } public static void setEnabledRecursively(@NotNull Component component, boolean enabled) { forEachComponentInHierarchy(component, c -> { c.setEnabled(enabled); }); } public static void setBackgroundRecursively(@NotNull Component component, @NotNull Color bg) { forEachComponentInHierarchy(component, c -> c.setBackground(bg)); } public static void setForegroundRecursively(@NotNull Component component, @NotNull Color bg) { forEachComponentInHierarchy(component, c -> c.setForeground(bg)); } public static void setTooltipRecursively(@NotNull Component component, @Nls String text) { forEachComponentInHierarchy(component, c -> ((JComponent)c).setToolTipText(text)); } public static void forEachComponentInHierarchy(@NotNull Component component, @NotNull Consumer<? super Component> action) { action.consume(component); if (component instanceof Container) { for (Component c : ((Container)component).getComponents()) { forEachComponentInHierarchy(c, action); } } } /** * Adds an empty border with the specified insets to the specified component. * If the component already has a border it will be preserved. * * @param component the component to which border added * @param top the inset from the top * @param left the inset from the left * @param bottom the inset from the bottom * @param right the inset from the right */ public static void addInsets(@NotNull JComponent component, int top, int left, int bottom, int right) { addBorder(component, BorderFactory.createEmptyBorder(top, left, bottom, right)); } /** * Adds an empty border with the specified insets to the specified component. * If the component already has a border it will be preserved. * * @param component the component to which border added * @param insets the top, left, bottom, and right insets */ public static void addInsets(@NotNull JComponent component, @NotNull Insets insets) { addInsets(component, insets.top, insets.left, insets.bottom, insets.right); } public static int getLcdContrastValue() { return StartupUiUtil.getLcdContrastValue(); } /** * Adds the specified border to the specified component. * If the component already has a border it will be preserved. * If component or border is not specified nothing happens. * * @param component the component to which border added * @param border the border to add to the component */ public static void addBorder(JComponent component, Border border) { if (component != null && border != null) { Border old = component.getBorder(); if (old != null) { border = BorderFactory.createCompoundBorder(border, old); } component.setBorder(border); } } private static final Color DECORATED_ROW_BG_COLOR = new JBColor(new Color(242, 245, 249), new Color(65, 69, 71)); public static @NotNull Color getDecoratedRowColor() { return JBColor.namedColor("Table.stripeColor", DECORATED_ROW_BG_COLOR); } public static @NotNull Paint getGradientPaint(float x1, float y1, @NotNull Color c1, float x2, float y2, @NotNull Color c2) { return Registry.is("ui.no.bangs.and.whistles", false) ? ColorUtil.mix(c1, c2, .5) : new GradientPaint(x1, y1, c1, x2, y2, c2); } public static @Nullable Point getLocationOnScreen(@NotNull JComponent component) { int dx = 0; int dy = 0; for (Container c = component; c != null; c = c.getParent()) { if (c.isShowing()) { Point locationOnScreen = c.getLocationOnScreen(); locationOnScreen.translate(dx, dy); return locationOnScreen; } else { Point location = c.getLocation(); dx += location.x; dy += location.y; } } return null; } public static void setAutoRequestFocus(@NotNull Window window, boolean value) { if (!SystemInfoRt.isMac) { window.setAutoRequestFocus(value); } } public static void runWhenWindowOpened(@NotNull Window window, @NotNull Runnable runnable) { window.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { e.getWindow().removeWindowListener(this); runnable.run(); } }); } public static void runWhenWindowClosed(@NotNull Window window, @NotNull Runnable runnable) { window.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { e.getWindow().removeWindowListener(this); runnable.run(); } }); } //May have no usages but it's useful in runtime (Debugger "watches", some logging etc.) public static @NotNull String getDebugText(@NotNull Component c) { StringBuilder builder = new StringBuilder(); getAllTextsRecursively(c, builder); return builder.toString(); } private static void getAllTextsRecursively(@NotNull Component component, @NotNull StringBuilder builder) { String candidate = ""; if (component instanceof JLabel) candidate = ((JLabel)component).getText(); if (component instanceof JTextComponent) candidate = ((JTextComponent)component).getText(); if (component instanceof AbstractButton) candidate = ((AbstractButton)component).getText(); if (Strings.isNotEmpty(candidate)) { candidate = candidate.replaceAll("<a href=\"#inspection/[^)]+\\)", ""); if (!builder.isEmpty()) { builder.append(' '); } builder.append(StringUtil.removeHtmlTags(candidate).trim()); } if (component instanceof Container) { Component[] components = ((Container)component).getComponents(); for (Component child : components) { getAllTextsRecursively(child, builder); } } } public static boolean isAncestor(@NotNull Component ancestor, @Nullable Component descendant) { while (descendant != null) { if (descendant == ancestor) { return true; } descendant = descendant.getParent(); } return false; } /** * Use {@link SwingUndoUtil#addUndoRedoActions(JTextComponent)} * * @param textComponent */ @Deprecated public static void addUndoRedoActions(@NotNull JTextComponent textComponent) { SwingUndoUtil.addUndoRedoActions(textComponent); } public static void playSoundFromResource(@NotNull String resourceName) { Class<?> callerClass = ReflectionUtil.getGrandCallerClass(); if (callerClass == null) { return; } playSoundFromStream(() -> callerClass.getResourceAsStream(resourceName)); } public static void playSoundFromStream(final @NotNull Factory<? extends InputStream> streamProducer) { // The wrapper thread is unnecessary, unless it blocks on the // Clip finishing; see comments. new Thread(() -> { try { Clip clip = AudioSystem.getClip(); InputStream stream = streamProducer.create(); if (!stream.markSupported()) stream = new BufferedInputStream(stream); AudioInputStream inputStream = AudioSystem.getAudioInputStream(stream); clip.open(inputStream); clip.start(); } catch (Exception e) { getLogger().info(e); } }, "play sound").start(); } public static @NlsSafe @NotNull String leftArrow() { return FontUtil.leftArrow(StartupUiUtil.getLabelFont()); } public static @NlsSafe @NotNull String rightArrow() { return FontUtil.rightArrow(StartupUiUtil.getLabelFont()); } public static @NlsSafe @NotNull String upArrow(@NotNull String defaultValue) { return FontUtil.upArrow(StartupUiUtil.getLabelFont(), defaultValue); } /** * It is your responsibility to set correct horizontal align (left in case of UI Designer) */ public static void configureNumericFormattedTextField(@NotNull JFormattedTextField textField) { NumberFormat format = NumberFormat.getIntegerInstance(); format.setParseIntegerOnly(true); format.setGroupingUsed(false); NumberFormatter numberFormatter = new NumberFormatter(format); numberFormatter.setMinimum(0); textField.setFormatterFactory(new DefaultFormatterFactory(numberFormatter)); textField.setHorizontalAlignment(SwingConstants.TRAILING); textField.setColumns(4); } public static @Nullable Window getWindow(@Nullable Component component) { return ComponentUtil.getWindow(component); } /** * Places the specified window at the top of the stacking order and shows it in front of any other windows. * If the window is iconified it will be shown anyway. * * @param window the window to activate */ public static void toFront(@Nullable Window window) { if (window instanceof Frame) { ((Frame)window).setState(Frame.NORMAL); } if (window != null) { window.toFront(); } } /** * Indicates whether the specified component is scrollable or it contains a scrollable content. */ public static boolean hasScrollPane(@NotNull Component component) { return hasComponentOfType(component, JScrollPane.class); } /** * Indicates whether the specified component is instance of one of the specified types * or it contains an instance of one of the specified types. */ public static boolean hasComponentOfType(@NotNull Component component, Class<?> @NotNull ... types) { for (Class<?> type : types) { if (type.isAssignableFrom(component.getClass())) { return true; } } if (component instanceof Container container) { for (int i = 0; i < container.getComponentCount(); i++) { if (hasComponentOfType(container.getComponent(i), types)) { return true; } } } return false; } public static void setColumns(JTextComponent textComponent, int columns) { if (textComponent instanceof JTextField) { ((JTextField)textComponent).setColumns(columns); } if (textComponent instanceof JTextArea) { ((JTextArea)textComponent).setColumns(columns); } } public static int getLineHeight(@NotNull JTextComponent textComponent) { return getLineHeight((JComponent)textComponent); } public static int getLineHeight(@NotNull JComponent component) { return component.getFontMetrics(component.getFont()).getHeight(); } /** * Returns the first focusable component in the specified container. * This method returns {@code null} if container is {@code null}, * or if focus traversal policy cannot be determined, * or if found focusable component is not a {@link JComponent}. * * @param container a container whose first focusable component is to be returned * @return the first focusable component or {@code null} if it cannot be found */ public static JComponent getPreferredFocusedComponent(Container container) { Container parent = container; if (parent == null) return null; FocusTraversalPolicy policy = parent.getFocusTraversalPolicy(); while (policy == null) { parent = parent.getParent(); if (parent == null) return null; policy = parent.getFocusTraversalPolicy(); } Component component = policy.getFirstComponent(container); return component instanceof JComponent ? (JComponent)component : null; } /** * Calculates a component style from the corresponding client property. * The key "JComponent.sizeVariant" is used by Apple's L&F to scale components. * * @param component a component to process * @return a component style of the specified component */ public static @NotNull ComponentStyle getComponentStyle(Component component) { if (component instanceof JComponent) { Object property = ((JComponent)component).getClientProperty("JComponent.sizeVariant"); if ("large".equals(property)) return ComponentStyle.LARGE; if ("small".equals(property)) return ComponentStyle.SMALL; if ("mini".equals(property)) return ComponentStyle.MINI; } return ComponentStyle.REGULAR; } public static final String CHECKBOX_ROLLOVER_PROPERTY = "JCheckBox.rollOver.rectangle"; public static final String CHECKBOX_PRESSED_PROPERTY = "JCheckBox.pressed.rectangle"; public static void repaintViewport(@NotNull JComponent c) { if (!c.isDisplayable() || !c.isVisible()) return; Container p = c.getParent(); if (p instanceof JViewport) { p.repaint(); } } public static void setCursor(@NotNull Component component, Cursor cursor) { // cursor is updated by native code even if component has the same cursor, causing performance problems (IDEA-167733) if (!component.isCursorSet() || component.getCursor() != cursor) { component.setCursor(cursor); } } public static boolean haveCommonOwner(Component c1, Component c2) { if (c1 == null || c2 == null) return false; Window c1Ancestor = findWindowAncestor(c1); Window c2Ancestor = findWindowAncestor(c2); Set<Window> ownerSet = new HashSet<>(); Window owner = c1Ancestor; while (owner != null && !(owner instanceof JDialog || owner instanceof JFrame)) { ownerSet.add(owner); owner = owner.getOwner(); } owner = c2Ancestor; while (owner != null && !(owner instanceof JDialog || owner instanceof JFrame)) { if (ownerSet.contains(owner)) return true; owner = owner.getOwner(); } return false; } private static Window findWindowAncestor(@NotNull Component c) { return c instanceof Window ? (Window)c : SwingUtilities.getWindowAncestor(c); } public static boolean isSimpleWindow(Window window) { return window != null && !(window instanceof Frame || window instanceof Dialog); } public static boolean isHelpButton(Component button) { return button instanceof JButton && "help".equals(((JComponent)button).getClientProperty("JButton.buttonType")); } public static boolean isRetina(@NotNull GraphicsDevice device) { return DetectRetinaKit.isOracleMacRetinaDevice(device); } /** * Employs a common pattern to use {@code Graphics}. This is a non-distractive approach * all modifications on {@code Graphics} are metter only inside the {@code Consumer} block * * @param originGraphics graphics to work with * @param drawingConsumer you can use the Graphics2D object here safely */ public static void useSafely(@NotNull Graphics originGraphics, @NotNull Consumer<? super Graphics2D> drawingConsumer) { Graphics2D graphics = (Graphics2D)originGraphics.create(); try { drawingConsumer.consume(graphics); } finally { graphics.dispose(); } } // List public static @NotNull Font getListFont() { Font font = UIManager.getFont("List.font"); return font != null ? font : StartupUiUtil.getLabelFont(); } // background /** * @see RenderingUtil#getBackground(JList) */ public static @NotNull Color getListBackground() { return JBUI.CurrentTheme.List.BACKGROUND; } /** * @see RenderingUtil#getSelectionBackground(JList) */ public static @NotNull Color getListSelectionBackground(boolean focused) { return JBUI.CurrentTheme.List.Selection.background(focused); } public static @NotNull Dimension updateListRowHeight(@NotNull Dimension size) { size.height = Math.max(size.height, UIManager.getInt("List.rowHeight")); return size; } /** * @see RenderingUtil#getBackground(JList, boolean) */ public static @NotNull Color getListBackground(boolean selected, boolean focused) { return !selected ? getListBackground() : getListSelectionBackground(focused); } /** * @deprecated use {@link #getListBackground(boolean, boolean)} */ @Deprecated public static @NotNull Color getListBackground(boolean selected) { return getListBackground(selected, true); } /** * @deprecated use {@link #getListSelectionBackground(boolean)} */ @Deprecated public static @NotNull Color getListSelectionBackground() { return getListSelectionBackground(true); } /** * @deprecated use {@link #getListSelectionBackground(boolean)} */ @Deprecated(forRemoval = true) public static @NotNull Color getListUnfocusedSelectionBackground() { return getListSelectionBackground(false); } // foreground /** * @see RenderingUtil#getForeground(JList) */ public static @NotNull Color getListForeground() { return JBUI.CurrentTheme.List.FOREGROUND; } /** * @see RenderingUtil#getSelectionForeground(JList) */ public static @NotNull Color getListSelectionForeground(boolean focused) { return NamedColorUtil.getListSelectionForeground(focused); } /** * @see RenderingUtil#getForeground(JList, boolean) */ public static @NotNull Color getListForeground(boolean selected, boolean focused) { return !selected ? getListForeground() : NamedColorUtil.getListSelectionForeground(focused); } /** * @deprecated use {@link #getListForeground(boolean, boolean)} */ @Deprecated(forRemoval = true) public static @NotNull Color getListForeground(boolean selected) { return getListForeground(selected, true); } /** * @deprecated use {@link #getListSelectionForeground(boolean)} */ @Deprecated public static @NotNull Color getListSelectionForeground() { return NamedColorUtil.getListSelectionForeground(true); } // Tree public static @NotNull Font getTreeFont() { Font font = UIManager.getFont("Tree.font"); return font != null ? font : StartupUiUtil.getLabelFont(); } // background /** * @see RenderingUtil#getBackground(JTree) */ public static @NotNull Color getTreeBackground() { return JBUI.CurrentTheme.Tree.BACKGROUND; } /** * @see RenderingUtil#getSelectionBackground(JTree) */ public static @NotNull Color getTreeSelectionBackground(boolean focused) { return JBUI.CurrentTheme.Tree.Selection.background(focused); } /** * @see RenderingUtil#getBackground(JTree, boolean) */ public static @NotNull Color getTreeBackground(boolean selected, boolean focused) { return !selected ? getTreeBackground() : getTreeSelectionBackground(focused); } /** * @deprecated use {@link #getTreeSelectionBackground(boolean)} */ @Deprecated public static @NotNull Color getTreeSelectionBackground() { return getTreeSelectionBackground(true); } /** * @deprecated use {@link #getTreeSelectionBackground(boolean)} */ @Deprecated public static @NotNull Color getTreeUnfocusedSelectionBackground() { return getTreeSelectionBackground(false); } // foreground /** * @see RenderingUtil#getForeground(JTree) */ public static @NotNull Color getTreeForeground() { return JBUI.CurrentTheme.Tree.FOREGROUND; } /** * @see RenderingUtil#getSelectionForeground(JTree) */ public static @NotNull Color getTreeSelectionForeground(boolean focused) { return JBUI.CurrentTheme.Tree.Selection.foreground(focused); } /** * @see RenderingUtil#getForeground(JTree, boolean) */ public static @NotNull Color getTreeForeground(boolean selected, boolean focused) { return !selected ? getTreeForeground() : getTreeSelectionForeground(focused); } /** * @deprecated use {@link #getTreeSelectionForeground(boolean)} */ @Deprecated public static @NotNull Color getTreeSelectionForeground() { return getTreeSelectionForeground(true); } /** * @see RenderingUtil#getBackground(JTable) */ public static @NotNull Color getTableBackground() { return JBUI.CurrentTheme.Table.BACKGROUND; } /** * @see RenderingUtil#getSelectionBackground(JTable) */ public static @NotNull Color getTableSelectionBackground(boolean focused) { return JBUI.CurrentTheme.Table.Selection.background(focused); } /** * @see RenderingUtil#getBackground(JTable, boolean) */ public static @NotNull Color getTableBackground(boolean selected, boolean focused) { return !selected ? getTableBackground() : getTableSelectionBackground(focused); } /** * @deprecated use {@link #getTableBackground(boolean, boolean)} */ @Deprecated public static @NotNull Color getTableBackground(boolean selected) { return getTableBackground(selected, true); } /** * @deprecated use {@link #getTableSelectionBackground(boolean)} */ @Deprecated public static @NotNull Color getTableSelectionBackground() { return getTableSelectionBackground(true); } // foreground /** * @see RenderingUtil#getForeground(JTable) */ public static @NotNull Color getTableForeground() { return JBUI.CurrentTheme.Table.FOREGROUND; } /** * @see RenderingUtil#getSelectionForeground(JTable) */ public static @NotNull Color getTableSelectionForeground(boolean focused) { return JBUI.CurrentTheme.Table.Selection.foreground(focused); } /** * @see RenderingUtil#getForeground(JTable, boolean) */ public static @NotNull Color getTableForeground(boolean selected, boolean focused) { return !selected ? getTableForeground() : getTableSelectionForeground(focused); } /** * @deprecated use {@link #getTableForeground(boolean, boolean)} */ @Deprecated(forRemoval = true) public static @NotNull Color getTableForeground(boolean selected) { return getTableForeground(selected, true); } /** * @deprecated use {@link #getTableSelectionForeground(boolean)} */ @Deprecated public static @NotNull Color getTableSelectionForeground() { return getTableSelectionForeground(true); } public static void doNotScrollToCaret(@NotNull JTextComponent textComponent) { textComponent.setCaret(new DefaultCaret() { @Override protected void adjustVisibility(Rectangle nloc) { } }); } public static void convertToLabel(@NotNull JEditorPane editorPane) { editorPane.setEditable(false); editorPane.setFocusable(false); editorPane.setOpaque(false); editorPane.setBorder(null); editorPane.setContentType("text/html"); editorPane.setEditorKit(HTMLEditorKitBuilder.simple()); } /** * By default soft wrapping in text components (for ASCII text) is only performed at spaces. This enables wrapping also at other places, * e.g. at dots. * <p> * NOTE: any operation which replaces document in the text component (e.g. {@link JTextComponent#setDocument(Document)}, * {@link JEditorPane#setPage(URL)}, {@link JEditorPane#setEditorKit(EditorKit)}) will cancel the effect of this call. */ public static void enableEagerSoftWrapping(@NotNull JTextComponent textComponent) { // see javax.swing.text.GlyphView.getBreaker() textComponent.getDocument().putProperty("multiByte", Boolean.TRUE); } public static @NotNull Color getTooltipSeparatorColor() { return JBColor.namedColor("Tooltip.separatorColor", 0xd1d1d1, 0x545658); } /** * This method (as opposed to {@link JEditorPane#scrollToReference}) supports also targets using {@code id} HTML attribute. */ public static void scrollToReference(@NotNull JEditorPane editor, @NotNull @NonNls String reference) { Document document = editor.getDocument(); if (document instanceof HTMLDocument) { Element elementById = ((HTMLDocument)document).getElement(reference); if (elementById != null) { try { int pos = elementById.getStartOffset(); Rectangle r = editor.modelToView(pos); if (r != null) { r.height = editor.getVisibleRect().height; editor.scrollRectToVisible(r); editor.setCaretPosition(pos); } } catch (BadLocationException e) { getLogger().error(e); } return; } } editor.scrollToReference(reference); } /** * Checks if a component is showing in a more general sense than UI visibility, * sometimes it's useful to limit various activities by checking the visibility of the real UI, * but it could be unneeded in headless mode or in other scenarios. * * @see UIUtil#hasFocus(Component) */ @ApiStatus.Experimental public static boolean isShowing(@NotNull Component component) { return isShowing(component, true); } /** * An overload of {@link UIUtil#isShowing(Component)} allowing to ignore headless mode. * * @param checkHeadless when {@code true}, the {@code component} will always be considered visible in headless mode. */ @ApiStatus.Experimental public static boolean isShowing(@NotNull Component component, boolean checkHeadless) { return ComponentUtil.isShowing(component, checkHeadless); } /** * Marks a component as showing */ @ApiStatus.Internal @ApiStatus.Experimental public static void markAsShowing(@NotNull JComponent component, boolean value) { ComponentUtil.markAsShowing(component, value); } public static void runWhenFocused(@NotNull Component component, @NotNull Runnable runnable) { assert component.isShowing(); if (component.isFocusOwner()) { runnable.run(); } else { Disposable disposable = Disposer.newDisposable(); FocusListener focusListener = new FocusAdapter() { @Override public void focusGained(FocusEvent e) { Disposer.dispose(disposable); runnable.run(); } }; HierarchyListener hierarchyListener = e -> { if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && !component.isShowing()) { Disposer.dispose(disposable); } }; component.addFocusListener(focusListener); component.addHierarchyListener(hierarchyListener); Disposer.register(disposable, () -> { component.removeFocusListener(focusListener); component.removeHierarchyListener(hierarchyListener); }); } } public static void runWhenHidden(@NotNull Component component, @NotNull Runnable runnable) { component.addHierarchyListener(runWhenHidden(runnable)); } private static @NotNull HierarchyListener runWhenHidden(@NotNull Runnable runnable) { return new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { if (!BitUtil.isSet(e.getChangeFlags(), HierarchyEvent.DISPLAYABILITY_CHANGED)) { return; } Component component = e.getComponent(); if (component.isDisplayable()) { return; } component.removeHierarchyListener(this); runnable.run(); } }; } public static void runWhenChanged(@NotNull Component component, @NotNull String property, @NotNull Runnable runnable) { component.addPropertyChangeListener(property, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { component.removePropertyChangeListener(property, this); runnable.run(); } }); } public static Future<?> runOnceWhenResized(@NotNull Component component, @NotNull Runnable runnable) { var future = new CompletableFuture<>(); component.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { component.removeComponentListener(this); if (!future.isCancelled()) { try { runnable.run(); future.complete(null); } catch (Throwable ex) { future.completeExceptionally(ex); } } } }); return future; } public static Font getLabelFont() { return StartupUiUtil.getLabelFont(); } public static void drawImage(@NotNull Graphics g, @NotNull Image image, int x, int y, @Nullable ImageObserver observer) { StartupUiUtil.drawImage(g, image, x, y, observer); } public static @NotNull Point getCenterPoint(@NotNull Dimension container, @NotNull Dimension child) { return StartupUiUtil.getCenterPoint(container, child); } public static @NotNull Point getCenterPoint(@NotNull Rectangle container, @NotNull Dimension child) { return StartupUiUtil.getCenterPoint(container, child); } public static void drawImage(@NotNull Graphics g, @NotNull Image image, @Nullable Rectangle dstBounds, @Nullable Rectangle srcBounds, @Nullable ImageObserver observer) { StartupUiUtilKt.drawImage(g, image, dstBounds, srcBounds, null, observer); } @TestOnly public static void pump() { StartupUiUtil.INSTANCE.pump(); } public static boolean isJreHiDPI() { return StartupUiUtil.isJreHiDPI(); } public static Color makeTransparent(@NotNull Color color, @NotNull Color backgroundColor, double transparency) { int r = makeTransparent(transparency, color.getRed(), backgroundColor.getRed()); int g = makeTransparent(transparency, color.getGreen(), backgroundColor.getGreen()); int b = makeTransparent(transparency, color.getBlue(), backgroundColor.getBlue()); //noinspection UseJBColor return new Color(r, g, b); } private static int makeTransparent(double transparency, int channel, int backgroundChannel) { final int result = (int)(backgroundChannel * (1 - transparency) + channel * transparency); if (result < 0) { return 0; } return Math.min(result, 255); } public static void stopFocusedEditing(@NotNull Window window) { Component focusOwner = FocusManager.getCurrentManager().getFocusOwner(); if (focusOwner == null || !SwingUtilities.isDescendingFrom(focusOwner, window)) { return; } if (focusOwner instanceof JFormattedTextField) { try { ((JFormattedTextField)focusOwner).commitEdit(); } catch (ParseException ignored) { } } Object obj = focusOwner.getParent(); if (obj instanceof JTable) { TableUtil.stopEditing((JTable)obj); } Object obj1 = focusOwner.getParent(); if (obj1 instanceof JTree) { ((JTree)obj1).stopEditing(); } } public static String colorToHex(final Color color) { return to2DigitsHex(color.getRed()) + to2DigitsHex(color.getGreen()) + to2DigitsHex(color.getBlue()); } private static String to2DigitsHex(int i) { String s = Integer.toHexString(i); if (s.length() < 2) s = "0" + s; return s; } public static boolean isXServerOnWindows() { // This is heuristics to detect using Cygwin/X or other build of X.Org server on Windows in a WSL 2 environment return SystemInfoRt.isUnix && !SystemInfoRt.isMac && !SystemInfo.isWayland && System.getenv("WSLENV") != null; } public static void applyDeprecatedBackground(@Nullable JComponent component) { Color color = getDeprecatedBackground(); if (component != null && color != null) { component.setBackground(color); component.setOpaque(true); } } @ApiStatus.Internal public static @Nullable Color getDeprecatedBackground() { return Registry.getColor("ui.deprecated.components.color", null); } public static boolean isMetalRendering() { return SystemInfo.isMac && Boolean.getBoolean("sun.java2d.metal"); } public static boolean isFullScreenSupportedByDefaultGD() { GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); return gd.isFullScreenSupported(); } }
JetBrains/intellij-community
platform/util/ui/src/com/intellij/util/ui/UIUtil.java
2,175
package org.telegram.tgnet.tl; import org.telegram.messenger.DialogObject; import org.telegram.tgnet.AbstractSerializedData; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.tl.TL_stats.TL_statsPercentValue; import org.telegram.ui.Stories.recorder.StoryPrivacyBottomSheet; import java.util.ArrayList; public class TL_stories { public static class TL_stories_storyViews extends TLObject { public static final int constructor = 0xde9eed1d; public ArrayList<StoryViews> views = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public static TL_stories_storyViews TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_stories_storyViews.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_stories_storyViews", constructor)); } else { return null; } } TL_stories_storyViews result = new TL_stories_storyViews(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryViews object = StoryViews.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } views.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(0x1cb5c415); int count = views.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { views.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } } } public static class StoryView extends TLObject { public int flags; public boolean blocked; public boolean blocked_my_stories_from; public long user_id; public int date; public TLRPC.Reaction reaction; public TLRPC.Message message; public TLRPC.Peer peer_id; public StoryItem story; public static StoryView TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { StoryView result = null; switch (constructor) { case TL_storyView.constructor: result = new TL_storyView(); break; case TL_storyViewPublicForward.constructor: result = new TL_storyViewPublicForward(); break; case TL_storyViewPublicRepost.constructor: result = new TL_storyViewPublicRepost(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in StoryView", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_storyView extends StoryView { public static final int constructor = 0xb0bdeac5; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); blocked = (flags & 1) != 0; blocked_my_stories_from = (flags & 2) != 0; user_id = stream.readInt64(exception); date = stream.readInt32(exception); if ((flags & 4) != 0) { reaction = TLRPC.Reaction.TLdeserialize(stream, stream.readInt32(exception), exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = blocked ? (flags | 1) : (flags &~ 1); flags = blocked_my_stories_from ? (flags | 2) : (flags &~ 2); stream.writeInt32(flags); stream.writeInt64(user_id); stream.writeInt32(date); if ((flags & 4) != 0) { reaction.serializeToStream(stream); } } } public static class TL_storyViewPublicForward extends StoryView { public static final int constructor = 0x9083670b; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); blocked = (flags & 1) != 0; blocked_my_stories_from = (flags & 2) != 0; message = TLRPC.Message.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = blocked ? (flags | 1) : (flags &~ 1); flags = blocked_my_stories_from ? (flags | 2) : (flags &~ 2); stream.writeInt32(flags); message.serializeToStream(stream); } } public static class TL_storyViewPublicRepost extends StoryView { public static final int constructor = 0xbd74cf49; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); blocked = (flags & 1) != 0; blocked_my_stories_from = (flags & 2) != 0; peer_id = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); story = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = blocked ? (flags | 1) : (flags &~ 1); flags = blocked_my_stories_from ? (flags | 2) : (flags &~ 2); stream.writeInt32(flags); peer_id.serializeToStream(stream); story.serializeToStream(stream); } } public static abstract class PeerStories extends TLObject { public int flags; public TLRPC.Peer peer; public int max_read_id; public ArrayList<StoryItem> stories = new ArrayList<>(); public static PeerStories TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { PeerStories result = null; switch (constructor) { case 0x9a35e999: result = new TL_peerStories(); break; case 0x8611a200: result = new TL_peerStories_layer162(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in PeerStories", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_peerStories extends PeerStories { public static final int constructor = 0x9a35e999; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); peer = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); if ((flags & 1) != 0) { max_read_id = stream.readInt32(exception); } int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryItem object = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } stories.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); peer.serializeToStream(stream); if ((flags & 1) != 0) { stream.writeInt32(max_read_id); } stream.writeInt32(0x1cb5c415); int count = stories.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stories.get(a).serializeToStream(stream); } } } public static class TL_peerStories_layer162 extends TL_peerStories { public static final int constructor = 0x8611a200; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); long user_id = stream.readInt64(exception); peer = new TLRPC.TL_peerUser(); peer.user_id = user_id; if ((flags & 1) != 0) { max_read_id = stream.readInt32(exception); } int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryItem object = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } stories.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt64(peer.user_id); if ((flags & 1) != 0) { stream.writeInt32(max_read_id); } stream.writeInt32(0x1cb5c415); int count = stories.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stories.get(a).serializeToStream(stream); } } } public static class TL_stories_peerStories extends TLObject { public static final int constructor = 0xcae68768; public PeerStories stories; public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public static TL_stories_peerStories TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_stories_peerStories.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_stories_peerStories", constructor)); } else { return null; } } TL_stories_peerStories result = new TL_stories_peerStories(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { stories = PeerStories.TLdeserialize(stream, stream.readInt32(exception), exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.Chat object = TLRPC.Chat.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } chats.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stories.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { chats.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } } } public static abstract class stories_AllStories extends TLObject { public static stories_AllStories TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { stories_AllStories result = null; switch (constructor) { case 0x1158fe3e: result = new TL_stories_allStoriesNotModified(); break; case 0x6efc5e81: result = new TL_stories_allStories(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in stories_AllStories", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_stories_allStoriesNotModified extends stories_AllStories { public static final int constructor = 0x1158fe3e; public int flags; public String state; public TL_storiesStealthMode stealth_mode; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); state = stream.readString(exception); stealth_mode = TL_storiesStealthMode.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeString(state); stealth_mode.serializeToStream(stream); } } public static class TL_stories_allStories extends stories_AllStories { public static final int constructor = 0x6efc5e81; public int flags; public boolean has_more; public int count; public String state; public ArrayList<PeerStories> peer_stories = new ArrayList<>(); public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public TL_storiesStealthMode stealth_mode; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); has_more = (flags & 1) != 0; count = stream.readInt32(exception); state = stream.readString(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { PeerStories object = PeerStories.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } peer_stories.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.Chat object = TLRPC.Chat.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } chats.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } stealth_mode = TL_storiesStealthMode.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = has_more ? (flags | 1) : (flags &~ 1); stream.writeInt32(flags); stream.writeInt32(count); stream.writeString(state); stream.writeInt32(0x1cb5c415); int count = peer_stories.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { peer_stories.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { chats.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } stealth_mode.serializeToStream(stream); } } public static class TL_stories_canSendStory extends TLObject { public static final int constructor = 0xc7dfdfdd; public TLRPC.InputPeer peer; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Bool.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); } } public static class TL_stories_sendStory extends TLObject { public static final int constructor = 0xe4e6694b; public int flags; public boolean pinned; public boolean noforwards; public boolean fwd_modified; public TLRPC.InputPeer peer; public TLRPC.InputMedia media; public ArrayList<MediaArea> media_areas = new ArrayList<>(); public String caption; public ArrayList<TLRPC.MessageEntity> entities = new ArrayList<>(); public ArrayList<TLRPC.InputPrivacyRule> privacy_rules = new ArrayList<>(); public long random_id; public int period; public TLRPC.InputPeer fwd_from_id; public int fwd_from_story; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Updates.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = pinned ? (flags | 4) : (flags &~ 4); flags = noforwards ? (flags | 16) : (flags &~ 16); flags = fwd_modified ? (flags | 128) : (flags &~ 128); stream.writeInt32(flags); peer.serializeToStream(stream); media.serializeToStream(stream); if ((flags & 32) != 0) { stream.writeInt32(0x1cb5c415); int count = media_areas.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { media_areas.get(a).serializeToStream(stream); } } if ((flags & 1) != 0) { stream.writeString(caption); } if ((flags & 2) != 0) { stream.writeInt32(0x1cb5c415); int count = entities.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { entities.get(a).serializeToStream(stream); } } stream.writeInt32(0x1cb5c415); int count = privacy_rules.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { privacy_rules.get(a).serializeToStream(stream); } stream.writeInt64(random_id); if ((flags & 8) != 0) { stream.writeInt32(period); } if ((flags & 64) != 0) { fwd_from_id.serializeToStream(stream); } if ((flags & 64) != 0) { stream.writeInt32(fwd_from_story); } } } public static class TL_stories_deleteStories extends TLObject { public static final int constructor = 0xae59db5f; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { TLRPC.Vector vector = new TLRPC.Vector(); int size = stream.readInt32(exception); for (int a = 0; a < size; a++) { vector.objects.add(stream.readInt32(exception)); } return vector; } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } } } public static class TL_stories_togglePinned extends TLObject { public static final int constructor = 0x9a75a1ef; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public boolean pinned; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { TLRPC.Vector vector = new TLRPC.Vector(); int size = stream.readInt32(exception); for (int a = 0; a < size; a++) { vector.objects.add(stream.readInt32(exception)); } return vector; } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } stream.writeBool(pinned); } } public static class TL_stories_editStory extends TLObject { public static final int constructor = 0xb583ba46; public int flags; public TLRPC.InputPeer peer; public int id; public TLRPC.InputMedia media; public ArrayList<MediaArea> media_areas = new ArrayList<>(); public String caption; public ArrayList<TLRPC.MessageEntity> entities = new ArrayList<>(); public ArrayList<TLRPC.InputPrivacyRule> privacy_rules = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Updates.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); peer.serializeToStream(stream); stream.writeInt32(id); if ((flags & 1) != 0) { media.serializeToStream(stream); } if ((flags & 8) != 0) { stream.writeInt32(0x1cb5c415); int count = media_areas.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { media_areas.get(a).serializeToStream(stream); } } if ((flags & 2) != 0) { stream.writeString(caption); } if ((flags & 2) != 0) { stream.writeInt32(0x1cb5c415); int count = entities.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { entities.get(a).serializeToStream(stream); } } if ((flags & 4) != 0) { stream.writeInt32(0x1cb5c415); int count = privacy_rules.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { privacy_rules.get(a).serializeToStream(stream); } } } } public static class TL_stories_getAllStories extends TLObject { public static final int constructor = 0xeeb0d625; public int flags; public boolean include_hidden; public boolean next; public String state; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return stories_AllStories.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = next ? (flags | 2) : (flags &~ 2); flags = include_hidden ? (flags | 4) : (flags &~ 4); stream.writeInt32(flags); if ((flags & 1) != 0) { stream.writeString(state); } } } public static class TL_stories_togglePeerStoriesHidden extends TLObject { public static final int constructor = 0xbd0415c4; public TLRPC.InputPeer peer; public boolean hidden; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Bool.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeBool(hidden); } } public static class TL_stories_stories extends TLObject { public static final int constructor = 0x63c3dd0a; public int flags; public int count; public ArrayList<StoryItem> stories = new ArrayList<>(); public ArrayList<Integer> pinned_to_top = new ArrayList<>(); public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public static TL_stories_stories TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_stories_stories.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_stories_stories", constructor)); } else { return null; } } TL_stories_stories result = new TL_stories_stories(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); count = stream.readInt32(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryItem object = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } stories.add(object); } if ((flags & 1) != 0) { magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { pinned_to_top.add(stream.readInt32(exception)); } } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.Chat object = TLRPC.Chat.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } chats.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(count); stream.writeInt32(0x1cb5c415); int count = stories.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stories.get(a).serializeToStream(stream); } if ((flags & 1) != 0) { stream.writeInt32(0x1cb5c415); count = pinned_to_top.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(pinned_to_top.get(a)); } } stream.writeInt32(0x1cb5c415); count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { chats.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } } } public static class TL_stories_getPeerStories extends TLObject { public static final int constructor = 0x2c4ada50; public TLRPC.InputPeer peer; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_stories_peerStories.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); } } public static class TL_updateStory extends TLRPC.Update { public static final int constructor = 0x75b3b798; public TLRPC.Peer peer; public StoryItem story; public void readParams(AbstractSerializedData stream, boolean exception) { peer = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); story = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); story.serializeToStream(stream); } } public static class TL_stories_getPinnedStories extends TLObject { public static final int constructor = 0x5821a5dc; public TLRPC.InputPeer peer; public int offset_id; public int limit; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_stories_stories.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(offset_id); stream.writeInt32(limit); } } public static class TL_stories_getStoriesArchive extends TLObject { public static final int constructor = 0xb4352016; public TLRPC.InputPeer peer; public int offset_id; public int limit; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_stories_stories.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(offset_id); stream.writeInt32(limit); } } public static class TL_updateReadStories extends TLRPC.Update { public static final int constructor = 0xf74e932b; public TLRPC.Peer peer; public int max_id; public void readParams(AbstractSerializedData stream, boolean exception) { peer = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); max_id = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(max_id); } } public static class StoryViewsList extends TLObject { public int flags; public int count; public int views_count; public int forwards_count; public int reactions_count; public ArrayList<StoryView> views = new ArrayList<>(); public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public String next_offset = ""; public static StoryViewsList TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { StoryViewsList result = null; switch (constructor) { case TL_storyViewsList.constructor: result = new TL_storyViewsList(); break; case TL_storyViewsList_layer167.constructor: result = new TL_storyViewsList_layer167(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in StoryViewsList", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_storyViewsList extends StoryViewsList { public static final int constructor = 0x59d78fc5; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); count = stream.readInt32(exception); views_count = stream.readInt32(exception); forwards_count = stream.readInt32(exception); reactions_count = stream.readInt32(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryView object = StoryView.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } views.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.Chat object = TLRPC.Chat.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } chats.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } if ((flags & 1) != 0) { next_offset = stream.readString(exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(count); stream.writeInt32(views_count); stream.writeInt32(forwards_count); stream.writeInt32(reactions_count); stream.writeInt32(0x1cb5c415); int count = views.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { views.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { chats.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } if ((flags & 1) != 0) { stream.writeString(next_offset); } } } public static class TL_storyViewsList_layer167 extends StoryViewsList { public static final int constructor = 0x46e9b9ec; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); count = stream.readInt32(exception); reactions_count = stream.readInt32(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryView object = StoryView.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } views.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } if ((flags & 1) != 0) { next_offset = stream.readString(exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(count); stream.writeInt32(reactions_count); stream.writeInt32(0x1cb5c415); int count = views.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { views.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } if ((flags & 1) != 0) { stream.writeString(next_offset); } } } public static class TL_stories_readStories extends TLObject { public static final int constructor = 0xa556dac8; public TLRPC.InputPeer peer; public int max_id; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { TLRPC.Vector vector = new TLRPC.Vector(); int size = stream.readInt32(exception); for (int a = 0; a < size; a++) { vector.objects.add(stream.readInt32(exception)); } return vector; } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(max_id); } } public static class TL_stories_incrementStoryViews extends TLObject { public static final int constructor = 0xb2028afb; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Bool.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } } } public static class TL_stories_getStoryViewsList extends TLObject { public static final int constructor = 0x7ed23c57; public int flags; public boolean just_contacts; public boolean reactions_first; public boolean forwards_first; public TLRPC.InputPeer peer; public String q; public int id; public String offset; public int limit; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return StoryViewsList.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = just_contacts ? (flags | 1) : (flags &~ 1); flags = reactions_first ? (flags | 4) : (flags &~ 4); flags = forwards_first ? (flags | 8) : (flags &~ 8); stream.writeInt32(flags); peer.serializeToStream(stream); if ((flags & 2) != 0) { stream.writeString(q); } stream.writeInt32(id); stream.writeString(offset); stream.writeInt32(limit); } } public static class TL_stories_getStoriesByID extends TLObject { public static final int constructor = 0x5774ca74; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_stories_stories.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } } } public static class TL_stories_getStoriesViews extends TLObject { public static final int constructor = 0x28e16cc8; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_stories_storyViews.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } } } public static class TL_exportedStoryLink extends TLObject { public static final int constructor = 0x3fc9053b; public String link; public static TL_exportedStoryLink TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_exportedStoryLink.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_exportedStoryLink", constructor)); } else { return null; } } TL_exportedStoryLink result = new TL_exportedStoryLink(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { link = stream.readString(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeString(link); } } public static class TL_stories_exportStoryLink extends TLObject { public static final int constructor = 0x7b8def20; public TLRPC.InputPeer peer; public int id; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_exportedStoryLink.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(id); } } public static class TL_stories_report extends TLObject { public static final int constructor = 0x1923fa8c; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public TLRPC.ReportReason reason; public String message; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Bool.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } reason.serializeToStream(stream); stream.writeString(message); } } public static class TL_stories_getAllReadPeerStories extends TLObject { public static final int constructor = 0x9b5ae7f9; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Updates.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); } } public static class TL_stories_getPeerMaxIDs extends TLObject { public static final int constructor = 0x535983c3; public ArrayList<TLRPC.InputPeer> id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { TLRPC.Vector vector = new TLRPC.Vector(); int size = stream.readInt32(exception); for (int a = 0; a < size; a++) { vector.objects.add(stream.readInt32(exception)); } return vector; } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { id.get(a).serializeToStream(stream); } } } public static class TL_updateStoriesStealthMode extends TLRPC.Update { public static final int constructor = 0x2c084dc1; public TL_storiesStealthMode stealth_mode; public void readParams(AbstractSerializedData stream, boolean exception) { stealth_mode = TL_storiesStealthMode.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stealth_mode.serializeToStream(stream); } } public static class TL_storiesStealthMode extends TLObject { public static final int constructor = 0x712e27fd; public int flags; public int active_until_date; public int cooldown_until_date; public static TL_storiesStealthMode TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_storiesStealthMode.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_storiesStealthMode", constructor)); } else { return null; } } TL_storiesStealthMode result = new TL_storiesStealthMode(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); if ((flags & 1) != 0) { active_until_date = stream.readInt32(exception); } if ((flags & 2) != 0) { cooldown_until_date = stream.readInt32(exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); if ((flags & 1) != 0) { stream.writeInt32(active_until_date); } if ((flags & 2) != 0) { stream.writeInt32(cooldown_until_date); } } } public static class TL_stories_activateStealthMode extends TLObject { public static final int constructor = 0x57bbd166; public int flags; public boolean past; public boolean future; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Updates.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = past ? (flags | 1) : (flags &~ 1); flags = future ? (flags | 2) : (flags &~ 2); stream.writeInt32(flags); } } public static class TL_stories_sendReaction extends TLObject { public static final int constructor = 0x7fd736b2; public int flags; public boolean add_to_recent; public TLRPC.InputPeer peer; public int story_id; public TLRPC.Reaction reaction; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Updates.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = add_to_recent ? (flags | 1) : (flags &~ 1); stream.writeInt32(flags); peer.serializeToStream(stream); stream.writeInt32(story_id); reaction.serializeToStream(stream); } } public static class TL_stories_getChatsToSend extends TLObject { public static final int constructor = 0xa56a8b60; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.TL_messages_chats.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); } } public static class TL_myBoost extends TLObject { public static int constructor = 0xc448415c; public int flags; public int slot; public TLRPC.Peer peer; public int date; public int expires; public int cooldown_until_date; public static TL_myBoost TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_myBoost.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_myBoost", constructor)); } else { return null; } } TL_myBoost result = new TL_myBoost(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); slot = stream.readInt32(exception); if ((flags & 1) != 0) { peer = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); } date = stream.readInt32(exception); expires = stream.readInt32(exception); if ((flags & 2) != 0) { cooldown_until_date = stream.readInt32(exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(slot); if ((flags & 1) != 0) { peer.serializeToStream(stream); } stream.writeInt32(date); stream.writeInt32(expires); if ((flags & 2) != 0) { stream.writeInt32(cooldown_until_date); } } } public static class TL_premium_myBoosts extends TLObject { public static int constructor = 0x9ae228e2; public ArrayList<TL_myBoost> my_boosts = new ArrayList<>(); public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public static TL_premium_myBoosts TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_premium_myBoosts.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_premium_myBoosts", constructor)); } else { return null; } } TL_premium_myBoosts result = new TL_premium_myBoosts(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TL_myBoost object = TL_myBoost.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } my_boosts.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.Chat object = TLRPC.Chat.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } chats.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(0x1cb5c415); int count = my_boosts.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { my_boosts.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { chats.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } } } public static class TL_premium_getMyBoosts extends TLObject { public static int constructor = 0xbe77b4a; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_premium_myBoosts.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); } } public static class TL_premium_boostsStatus extends TLObject { public static int constructor = 0x4959427a; public int flags; public boolean my_boost; public int level; public int current_level_boosts; public int boosts; public int gift_boosts; public int next_level_boosts; public TL_statsPercentValue premium_audience; public String boost_url; public ArrayList<TL_prepaidGiveaway> prepaid_giveaways = new ArrayList<>(); public ArrayList<Integer> my_boost_slots = new ArrayList<>(); public static TL_premium_boostsStatus TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_premium_boostsStatus.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_premium_boostsStatus", constructor)); } else { return null; } } TL_premium_boostsStatus result = new TL_premium_boostsStatus(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); my_boost = (flags & 4) != 0; level = stream.readInt32(exception); current_level_boosts = stream.readInt32(exception); boosts = stream.readInt32(exception); if ((flags & 16) != 0) { gift_boosts = stream.readInt32(exception); } if ((flags & 1) != 0) { next_level_boosts = stream.readInt32(exception); } if ((flags & 2) != 0) { premium_audience = TL_stats.TL_statsPercentValue.TLdeserialize(stream, stream.readInt32(exception), exception); } boost_url = stream.readString(exception); if ((flags & 8) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TL_prepaidGiveaway object = TL_prepaidGiveaway.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } prepaid_giveaways.add(object); } } if ((flags & 4) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { my_boost_slots.add(stream.readInt32(exception)); } } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = my_boost ? (flags | 4) : (flags &~ 4); stream.writeInt32(flags); stream.writeInt32(level); stream.writeInt32(current_level_boosts); stream.writeInt32(boosts); if ((flags & 16) != 0) { stream.writeInt32(gift_boosts); } if ((flags & 1) != 0) { stream.writeInt32(next_level_boosts); } if ((flags & 2) != 0) { premium_audience.serializeToStream(stream); } stream.writeString(boost_url); if ((flags & 8) != 0) { stream.writeInt32(0x1cb5c415); int count = prepaid_giveaways.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { prepaid_giveaways.get(a).serializeToStream(stream); } } if ((flags & 4) != 0) { stream.writeInt32(0x1cb5c415); int count = my_boost_slots.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(my_boost_slots.get(a)); } } } } public static class TL_premium_getBoostsStatus extends TLObject { public static int constructor = 0x42f1f61; public TLRPC.InputPeer peer; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_premium_boostsStatus.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); } } public static class TL_premium_applyBoost extends TLObject { public static int constructor = 0x6b7da746; public int flags; public ArrayList<Integer> slots = new ArrayList<>(); public TLRPC.InputPeer peer; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_premium_myBoosts.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); if ((flags & 1) != 0) { stream.writeInt32(0x1cb5c415); int count = slots.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(slots.get(a)); } } peer.serializeToStream(stream); } } public static class TL_boost extends TLObject { public static int constructor = 0x2a1c8c71; public static final long NO_USER_ID = -1L; //custom public int flags; public boolean gift; public boolean giveaway; public boolean unclaimed; public String id; public long user_id = NO_USER_ID; public int giveaway_msg_id; public int date; public int expires; public String used_gift_slug; public int multiplier; public static TL_boost TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_boost.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_boost", constructor)); } else { return null; } } TL_boost result = new TL_boost(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); gift = (flags & 2) != 0; giveaway = (flags & 4) != 0; unclaimed = (flags & 8) != 0; id = stream.readString(exception); if ((flags & 1) != 0) { user_id = stream.readInt64(exception); } if ((flags & 4) != 0) { giveaway_msg_id = stream.readInt32(exception); } date = stream.readInt32(exception); expires = stream.readInt32(exception); if ((flags & 16) != 0) { used_gift_slug = stream.readString(exception); } if ((flags & 32) != 0) { multiplier = stream.readInt32(exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = gift ? (flags | 2) : (flags &~ 2); flags = giveaway ? (flags | 4) : (flags &~ 4); flags = unclaimed ? (flags | 8) : (flags &~ 8); stream.writeInt32(flags); stream.writeString(id); if ((flags & 1) != 0) { stream.writeInt64(user_id); } if ((flags & 4) != 0) { stream.writeInt32(giveaway_msg_id); } stream.writeInt32(date); stream.writeInt32(expires); if ((flags & 16) != 0) { stream.writeString(used_gift_slug); } if ((flags & 32) != 0) { stream.writeInt32(multiplier); } } } public static class TL_premium_boostsList extends TLObject { public static int constructor = 0x86f8613c; public int flags; public int count; public ArrayList<TL_boost> boosts = new ArrayList<>(); public String next_offset; public ArrayList<TLRPC.User> users = new ArrayList<>(); public static TL_premium_boostsList TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_premium_boostsList.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_premium_boostsList", constructor)); } else { return null; } } TL_premium_boostsList result = new TL_premium_boostsList(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); count = stream.readInt32(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TL_boost object = TL_boost.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } boosts.add(object); } if ((flags & 1) != 0) { next_offset = stream.readString(exception); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(count); stream.writeInt32(0x1cb5c415); int count = boosts.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { boosts.get(a).serializeToStream(stream); } if ((flags & 1) != 0) { stream.writeString(next_offset); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } } } public static class TL_premium_getBoostsList extends TLObject { public static int constructor = 0x60f67660; public int flags; public boolean gifts; public TLRPC.InputPeer peer; public String offset; public int limit; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_premium_boostsList.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = gifts ? (flags | 1) : (flags &~ 1); stream.writeInt32(flags); peer.serializeToStream(stream); stream.writeString(offset); stream.writeInt32(limit); } } public static abstract class StoryItem extends TLObject { public int flags; public boolean pinned; public boolean isPublic; public boolean close_friends; public boolean contacts; public boolean selected_contacts; public boolean noforwards; public boolean min; public boolean out; public int id; public int date; public TLRPC.Peer from_id; public StoryFwdHeader fwd_from; public int expire_date; public String caption; public boolean edited; public ArrayList<TLRPC.MessageEntity> entities = new ArrayList<>(); public TLRPC.MessageMedia media; public ArrayList<MediaArea> media_areas = new ArrayList(); public ArrayList<TLRPC.PrivacyRule> privacy = new ArrayList<>(); public StoryViews views; public TLRPC.Reaction sent_reaction; public long lastUpdateTime; //custom public String attachPath; //custom public String firstFramePath; //custom public long dialogId;// custom public boolean justUploaded;// custom public int messageId;//custom public int messageType;//custom public int fileReference; public String detectedLng; //custom public String translatedLng; //custom public boolean translated; //custom public TLRPC.TL_textWithEntities translatedText; //custom public StoryPrivacyBottomSheet.StoryPrivacy parsedPrivacy; //custom public static StoryItem TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { StoryItem result = null; switch (constructor) { case TL_storyItem.constructor: result = new TL_storyItem(); break; case TL_storyItem_layer174.constructor: result = new TL_storyItem_layer174(); break; case TL_storyItem_layer166.constructor: result = new TL_storyItem_layer166(); break; case TL_storyItem_layer160.constructor: result = new TL_storyItem_layer160(); break; case TL_storyItemDeleted.constructor: result = new TL_storyItemDeleted(); break; case TL_storyItemSkipped.constructor: result = new TL_storyItemSkipped(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in StoryItem", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static abstract class StoryViews extends TLObject { public int flags; public int views_count; public int reactions_count; public ArrayList<Long> recent_viewers = new ArrayList<>(); public boolean has_viewers; public int forwards_count; public ArrayList<TLRPC.ReactionCount> reactions = new ArrayList<>(); public static StoryViews TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { StoryViews result = null; switch (constructor) { case 0xd36760cf: result = new TL_storyViews_layer160(); break; case 0xc64c0b97: result = new TL_storyViews_layer161(); break; case 0x8d595cd6: result = new TL_storyViews(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in StoryViews", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_storyViews_layer160 extends StoryViews { public static final int constructor = 0xd36760cf; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); views_count = stream.readInt32(exception); if ((flags & 1) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { recent_viewers.add(stream.readInt64(exception)); } } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(views_count); if ((flags & 1) != 0) { stream.writeInt32(0x1cb5c415); int count = recent_viewers.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt64(recent_viewers.get(a)); } } } } public static class TL_storyViews_layer161 extends StoryViews { public static final int constructor = 0xc64c0b97; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); views_count = stream.readInt32(exception); reactions_count = stream.readInt32(exception); if ((flags & 1) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { recent_viewers.add(stream.readInt64(exception)); } } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(views_count); stream.writeInt32(reactions_count); if ((flags & 1) != 0) { stream.writeInt32(0x1cb5c415); int count = recent_viewers.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt64(recent_viewers.get(a)); } } } } public static class TL_storyViews extends StoryViews { public static final int constructor = 0x8d595cd6; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); has_viewers = (flags & 2) != 0; views_count = stream.readInt32(exception); if ((flags & 4) != 0) { forwards_count = stream.readInt32(exception); } if ((flags & 8) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.ReactionCount object = TLRPC.ReactionCount.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } reactions.add(object); } } if ((flags & 16) != 0) { reactions_count = stream.readInt32(exception); } if ((flags & 1) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { recent_viewers.add(stream.readInt64(exception)); } } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = has_viewers ? (flags | 2) : (flags & ~2); stream.writeInt32(flags); stream.writeInt32(views_count); if ((flags & 4) != 0) { stream.writeInt32(forwards_count); } if ((flags & 8) != 0) { stream.writeInt32(0x1cb5c415); int count = reactions.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { reactions.get(a).serializeToStream(stream); } } if ((flags & 16) != 0) { stream.writeInt32(reactions_count); } if ((flags & 1) != 0) { stream.writeInt32(0x1cb5c415); int count = recent_viewers.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt64(recent_viewers.get(a)); } } } } public static class TL_publicForwardStory extends TL_stats.PublicForward { public static final int constructor = 0xedf3add0; public TLRPC.Peer peer; public StoryItem story; public void readParams(AbstractSerializedData stream, boolean exception) { peer = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); story = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); story.serializeToStream(stream); } } public static class StoryFwdHeader extends TLObject { public int flags; public boolean modified; public TLRPC.Peer from; public String from_name; public int story_id; public static StoryFwdHeader TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { StoryFwdHeader result = null; switch (constructor) { case TL_storyFwdHeader.constructor: result = new TL_storyFwdHeader(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in StoryFwdHeader", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_storyFwdHeader extends StoryFwdHeader { public static final int constructor = 0xb826e150; @Override public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); modified = (flags & 8) != 0; if ((flags & 1) != 0) { from = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 2) != 0) { from_name = stream.readString(exception); } if ((flags & 4) != 0) { story_id = stream.readInt32(exception); } } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = modified ? (flags | 8) : (flags &~ 8); stream.writeInt32(flags); if ((flags & 1) != 0) { from.serializeToStream(stream); } if ((flags & 2) != 0) { stream.writeString(from_name); } if ((flags & 4) != 0) { stream.writeInt32(story_id); } } } public static class TL_storyItem extends StoryItem { public static final int constructor = 0x79b26a24; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); pinned = (flags & 32) != 0; isPublic = (flags & 128) != 0; close_friends = (flags & 256) != 0; min = (flags & 512) != 0; noforwards = (flags & 1024) != 0; edited = (flags & 2048) != 0; contacts = (flags & 4096) != 0; selected_contacts = (flags & 8192) != 0; out = (flags & 65536) != 0; id = stream.readInt32(exception); date = stream.readInt32(exception); if ((flags & 262144) != 0) { from_id = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 131072) != 0) { fwd_from = TL_storyFwdHeader.TLdeserialize(stream, stream.readInt32(exception), exception); } expire_date = stream.readInt32(exception); if ((flags & 1) != 0) { caption = stream.readString(exception); } if ((flags & 2) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.MessageEntity object = TLRPC.MessageEntity.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } entities.add(object); } } media = TLRPC.MessageMedia.TLdeserialize(stream, stream.readInt32(exception), exception); if ((flags & 16384) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { MediaArea object = MediaArea.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } media_areas.add(object); } } if ((flags & 4) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.PrivacyRule object = TLRPC.PrivacyRule.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } privacy.add(object); } } if ((flags & 8) != 0) { views = StoryViews.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 32768) != 0) { sent_reaction = TLRPC.Reaction.TLdeserialize(stream, stream.readInt32(exception), exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = pinned ? (flags | 32) : (flags &~ 32); flags = isPublic ? (flags | 128) : (flags &~ 128); flags = close_friends ? (flags | 256) : (flags &~ 256); flags = min ? (flags | 512) : (flags &~ 512); flags = noforwards ? (flags | 1024) : (flags &~ 1024); flags = edited ? (flags | 2048) : (flags &~ 2048); flags = contacts ? (flags | 4096) : (flags &~ 4096); flags = selected_contacts ? (flags | 8192) : (flags &~ 8192); flags = out ? (flags | 65536) : (flags &~ 65536); stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(date); if ((flags & 262144) != 0) { from_id.serializeToStream(stream); } if ((flags & 131072) != 0) { fwd_from.serializeToStream(stream); } stream.writeInt32(expire_date); if ((flags & 1) != 0) { stream.writeString(caption); } if ((flags & 2) != 0) { stream.writeInt32(0x1cb5c415); int count = entities.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { entities.get(a).serializeToStream(stream); } } media.serializeToStream(stream); if ((flags & 16384) != 0) { stream.writeInt32(0x1cb5c415); int count = media_areas.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { media_areas.get(a).serializeToStream(stream); } } if ((flags & 4) != 0) { stream.writeInt32(0x1cb5c415); int count = privacy.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { privacy.get(a).serializeToStream(stream); } } if ((flags & 8) != 0) { views.serializeToStream(stream); } if ((flags & 32768) != 0) { sent_reaction.serializeToStream(stream); } } } public static class TL_storyItem_layer174 extends TL_storyItem { public static final int constructor = 0xaf6365a1; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); pinned = (flags & 32) != 0; isPublic = (flags & 128) != 0; close_friends = (flags & 256) != 0; min = (flags & 512) != 0; noforwards = (flags & 1024) != 0; edited = (flags & 2048) != 0; contacts = (flags & 4096) != 0; selected_contacts = (flags & 8192) != 0; out = (flags & 65536) != 0; id = stream.readInt32(exception); date = stream.readInt32(exception); if ((flags & 131072) != 0) { fwd_from = TL_storyFwdHeader.TLdeserialize(stream, stream.readInt32(exception), exception); } expire_date = stream.readInt32(exception); if ((flags & 1) != 0) { caption = stream.readString(exception); } if ((flags & 2) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.MessageEntity object = TLRPC.MessageEntity.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } entities.add(object); } } media = TLRPC.MessageMedia.TLdeserialize(stream, stream.readInt32(exception), exception); if ((flags & 16384) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { MediaArea object = MediaArea.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } media_areas.add(object); } } if ((flags & 4) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.PrivacyRule object = TLRPC.PrivacyRule.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } privacy.add(object); } } if ((flags & 8) != 0) { views = StoryViews.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 32768) != 0) { sent_reaction = TLRPC.Reaction.TLdeserialize(stream, stream.readInt32(exception), exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = pinned ? (flags | 32) : (flags &~ 32); flags = isPublic ? (flags | 128) : (flags &~ 128); flags = close_friends ? (flags | 256) : (flags &~ 256); flags = min ? (flags | 512) : (flags &~ 512); flags = noforwards ? (flags | 1024) : (flags &~ 1024); flags = edited ? (flags | 2048) : (flags &~ 2048); flags = contacts ? (flags | 4096) : (flags &~ 4096); flags = selected_contacts ? (flags | 8192) : (flags &~ 8192); flags = out ? (flags | 65536) : (flags &~ 65536); stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(date); if ((flags & 131072) != 0) { fwd_from.serializeToStream(stream); } stream.writeInt32(expire_date); if ((flags & 1) != 0) { stream.writeString(caption); } if ((flags & 2) != 0) { stream.writeInt32(0x1cb5c415); int count = entities.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { entities.get(a).serializeToStream(stream); } } media.serializeToStream(stream); if ((flags & 16384) != 0) { stream.writeInt32(0x1cb5c415); int count = media_areas.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { media_areas.get(a).serializeToStream(stream); } } if ((flags & 4) != 0) { stream.writeInt32(0x1cb5c415); int count = privacy.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { privacy.get(a).serializeToStream(stream); } } if ((flags & 8) != 0) { views.serializeToStream(stream); } if ((flags & 32768) != 0) { sent_reaction.serializeToStream(stream); } } } public static class TL_storyItem_layer166 extends TL_storyItem { public static final int constructor = 0x44c457ce; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); pinned = (flags & 32) != 0; isPublic = (flags & 128) != 0; close_friends = (flags & 256) != 0; min = (flags & 512) != 0; noforwards = (flags & 1024) != 0; edited = (flags & 2048) != 0; contacts = (flags & 4096) != 0; selected_contacts = (flags & 8192) != 0; out = (flags & 65536) != 0; id = stream.readInt32(exception); date = stream.readInt32(exception); expire_date = stream.readInt32(exception); if ((flags & 1) != 0) { caption = stream.readString(exception); } if ((flags & 2) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.MessageEntity object = TLRPC.MessageEntity.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } entities.add(object); } } media = TLRPC.MessageMedia.TLdeserialize(stream, stream.readInt32(exception), exception); if ((flags & 16384) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { MediaArea object = MediaArea.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } media_areas.add(object); } } if ((flags & 4) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.PrivacyRule object = TLRPC.PrivacyRule.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } privacy.add(object); } } if ((flags & 8) != 0) { views = StoryViews.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 32768) != 0) { sent_reaction = TLRPC.Reaction.TLdeserialize(stream, stream.readInt32(exception), exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = pinned ? (flags | 32) : (flags &~ 32); flags = isPublic ? (flags | 128) : (flags &~ 128); flags = close_friends ? (flags | 256) : (flags &~ 256); flags = min ? (flags | 512) : (flags &~ 512); flags = noforwards ? (flags | 1024) : (flags &~ 1024); flags = edited ? (flags | 2048) : (flags &~ 2048); flags = contacts ? (flags | 4096) : (flags &~ 4096); flags = selected_contacts ? (flags | 8192) : (flags &~ 8192); flags = out ? (flags | 65536) : (flags &~ 65536); stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(date); stream.writeInt32(expire_date); if ((flags & 1) != 0) { stream.writeString(caption); } if ((flags & 2) != 0) { stream.writeInt32(0x1cb5c415); int count = entities.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { entities.get(a).serializeToStream(stream); } } media.serializeToStream(stream); if ((flags & 16384) != 0) { stream.writeInt32(0x1cb5c415); int count = media_areas.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { media_areas.get(a).serializeToStream(stream); } } if ((flags & 4) != 0) { stream.writeInt32(0x1cb5c415); int count = privacy.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { privacy.get(a).serializeToStream(stream); } } if ((flags & 8) != 0) { views.serializeToStream(stream); } if ((flags & 32768) != 0) { sent_reaction.serializeToStream(stream); } } } public static class TL_storyItem_layer160 extends TL_storyItem { public static final int constructor = 0x562aa637; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); pinned = (flags & 32) != 0; isPublic = (flags & 128) != 0; close_friends = (flags & 256) != 0; min = (flags & 512) != 0; noforwards = (flags & 1024) != 0; edited = (flags & 2048) != 0; contacts = (flags & 4096) != 0; selected_contacts = (flags & 8192) != 0; id = stream.readInt32(exception); date = stream.readInt32(exception); expire_date = stream.readInt32(exception); if ((flags & 1) != 0) { caption = stream.readString(exception); } if ((flags & 2) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.MessageEntity object = TLRPC.MessageEntity.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } entities.add(object); } } media = TLRPC.MessageMedia.TLdeserialize(stream, stream.readInt32(exception), exception); if ((flags & 4) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.PrivacyRule object = TLRPC.PrivacyRule.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } privacy.add(object); } } if ((flags & 8) != 0) { views = StoryViews.TLdeserialize(stream, stream.readInt32(exception), exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = pinned ? (flags | 32) : (flags &~ 32); flags = isPublic ? (flags | 128) : (flags &~ 128); flags = close_friends ? (flags | 256) : (flags &~ 256); flags = min ? (flags | 512) : (flags &~ 512); flags = noforwards ? (flags | 1024) : (flags &~ 1024); flags = edited ? (flags | 2048) : (flags &~ 2048); flags = contacts ? (flags | 4096) : (flags &~ 4096); flags = selected_contacts ? (flags | 8192) : (flags &~ 8192); stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(date); stream.writeInt32(expire_date); if ((flags & 1) != 0) { stream.writeString(caption); } if ((flags & 2) != 0) { stream.writeInt32(0x1cb5c415); int count = entities.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { entities.get(a).serializeToStream(stream); } } media.serializeToStream(stream); if ((flags & 4) != 0) { stream.writeInt32(0x1cb5c415); int count = privacy.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { privacy.get(a).serializeToStream(stream); } } if ((flags & 8) != 0) { views.serializeToStream(stream); } } } public static class TL_storyItemDeleted extends StoryItem { public static final int constructor = 0x51e6ee4f; public void readParams(AbstractSerializedData stream, boolean exception) { id = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(id); } } public static class TL_storyItemSkipped extends StoryItem { public static final int constructor = 0xffadc913; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); close_friends = (flags & 256) != 0; id = stream.readInt32(exception); date = stream.readInt32(exception); expire_date = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = close_friends ? (flags | 256) : (flags &~ 256); stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(date); stream.writeInt32(expire_date); } } public static class TL_mediaAreaCoordinates extends TLObject { public static final int constructor = 0x3d1ea4e; public double x; public double y; public double w; public double h; public double rotation; public static TL_mediaAreaCoordinates TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_mediaAreaCoordinates.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_mediaAreaCoordinates", constructor)); } else { return null; } } TL_mediaAreaCoordinates result = new TL_mediaAreaCoordinates(); result.readParams(stream, exception); return result; } @Override public void readParams(AbstractSerializedData stream, boolean exception) { x = stream.readDouble(exception); y = stream.readDouble(exception); w = stream.readDouble(exception); h = stream.readDouble(exception); rotation = stream.readDouble(exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeDouble(x); stream.writeDouble(y); stream.writeDouble(w); stream.writeDouble(h); stream.writeDouble(rotation); } } public static class MediaArea extends TLObject { public TL_mediaAreaCoordinates coordinates; public TLRPC.Reaction reaction; public int flags; public boolean dark; public boolean flipped; public static MediaArea TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { MediaArea result = null; switch (constructor) { case TL_mediaAreaVenue.constructor: result = new TL_mediaAreaVenue(); break; case TL_mediaAreaGeoPoint.constructor: result = new TL_mediaAreaGeoPoint(); break; case TL_inputMediaAreaVenue.constructor: result = new TL_inputMediaAreaVenue(); break; case TL_inputMediaAreaChannelPost.constructor: result = new TL_inputMediaAreaChannelPost(); break; case TL_mediaAreaSuggestedReaction.constructor: result = new TL_mediaAreaSuggestedReaction(); break; case TL_mediaAreaChannelPost.constructor: result = new TL_mediaAreaChannelPost(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in MediaArea", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_mediaAreaSuggestedReaction extends MediaArea { public static final int constructor = 0x14455871; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); dark = (flags & 1) != 0; flipped = (flags & 2) != 0; coordinates = TL_mediaAreaCoordinates.TLdeserialize(stream, stream.readInt32(exception), exception); reaction = TLRPC.Reaction.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = dark ? (flags | 1) : (flags &~ 1); flags = flipped ? (flags | 2) : (flags &~ 2); stream.writeInt32(flags); coordinates.serializeToStream(stream); reaction.serializeToStream(stream); } } public static class TL_mediaAreaChannelPost extends MediaArea { public static final int constructor = 0x770416af; public long channel_id; public int msg_id; public void readParams(AbstractSerializedData stream, boolean exception) { coordinates = TL_mediaAreaCoordinates.TLdeserialize(stream, stream.readInt32(exception), exception); channel_id = stream.readInt64(exception); msg_id = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); coordinates.serializeToStream(stream); stream.writeInt64(channel_id); stream.writeInt32(msg_id); } } public static class TL_mediaAreaVenue extends MediaArea { public static final int constructor = 0xbe82db9c; public TLRPC.GeoPoint geo; public String title; public String address; public String provider; public String venue_id; public String venue_type; @Override public void readParams(AbstractSerializedData stream, boolean exception) { coordinates = TL_mediaAreaCoordinates.TLdeserialize(stream, stream.readInt32(exception), exception); geo = TLRPC.GeoPoint.TLdeserialize(stream, stream.readInt32(exception), exception); title = stream.readString(exception); address = stream.readString(exception); provider = stream.readString(exception); venue_id = stream.readString(exception); venue_type = stream.readString(exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); coordinates.serializeToStream(stream); geo.serializeToStream(stream); stream.writeString(title); stream.writeString(address); stream.writeString(provider); stream.writeString(venue_id); stream.writeString(venue_type); } } public static class TL_inputMediaAreaVenue extends MediaArea { public static final int constructor = 0xb282217f; public long query_id; public String result_id; @Override public void readParams(AbstractSerializedData stream, boolean exception) { coordinates = TL_mediaAreaCoordinates.TLdeserialize(stream, stream.readInt32(exception), exception); query_id = stream.readInt64(exception); result_id = stream.readString(exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); coordinates.serializeToStream(stream); stream.writeInt64(query_id); stream.writeString(result_id); } } public static class TL_inputMediaAreaChannelPost extends MediaArea { public static final int constructor = 0x2271f2bf; public TLRPC.InputChannel channel; public int msg_id; @Override public void readParams(AbstractSerializedData stream, boolean exception) { coordinates = TL_mediaAreaCoordinates.TLdeserialize(stream, stream.readInt32(exception), exception); channel = TLRPC.InputChannel.TLdeserialize(stream, stream.readInt32(exception), exception); msg_id = stream.readInt32(exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); coordinates.serializeToStream(stream); channel.serializeToStream(stream); stream.writeInt32(msg_id); } } public static class TL_mediaAreaGeoPoint extends MediaArea { public static final int constructor = 0xdf8b3b22; public TLRPC.GeoPoint geo; @Override public void readParams(AbstractSerializedData stream, boolean exception) { coordinates = TL_mediaAreaCoordinates.TLdeserialize(stream, stream.readInt32(exception), exception); geo = TLRPC.GeoPoint.TLdeserialize(stream, stream.readInt32(exception), exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); coordinates.serializeToStream(stream); geo.serializeToStream(stream); } } public static class TL_prepaidGiveaway extends TLObject { public static int constructor = 0xb2539d54; public long id; public int months; public int quantity; public int date; public static TL_prepaidGiveaway TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_prepaidGiveaway.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_prepaidGiveaway", constructor)); } else { return null; } } TL_prepaidGiveaway result = new TL_prepaidGiveaway(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { id = stream.readInt64(exception); months = stream.readInt32(exception); quantity = stream.readInt32(exception); date = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt32(months); stream.writeInt32(quantity); stream.writeInt32(date); } } public static class TL_stats_storyStats extends TLObject { public final static int constructor = 0x50cd067c; public TL_stats.StatsGraph views_graph; public TL_stats.StatsGraph reactions_by_emotion_graph; public static TL_stats_storyStats TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_stats_storyStats.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_stats_storyStats", constructor)); } else { return null; } } TL_stats_storyStats result = new TL_stats_storyStats(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { views_graph = TL_stats.StatsGraph.TLdeserialize(stream, stream.readInt32(exception), exception); reactions_by_emotion_graph = TL_stats.StatsGraph.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); views_graph.serializeToStream(stream); reactions_by_emotion_graph.serializeToStream(stream); } } public static class TL_stats_getStoryStats extends TLObject { public final static int constructor = 0x374fef40; public int flags; public boolean dark; public TLRPC.InputPeer peer; public int id; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_stats_storyStats.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = dark ? (flags | 1) : (flags & ~1); stream.writeInt32(flags); peer.serializeToStream(stream); stream.writeInt32(id); } } public static class StoryReaction extends TLObject { public TLRPC.Peer peer_id; public StoryItem story; public TLRPC.Message message; public static StoryReaction TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { StoryReaction result = null; switch (constructor) { case TL_storyReaction.constructor: result = new TL_storyReaction(); break; case TL_storyReactionPublicForward.constructor: result = new TL_storyReactionPublicForward(); break; case TL_storyReactionPublicRepost.constructor: result = new TL_storyReactionPublicRepost(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in StoryReaction", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_storyReactionPublicForward extends StoryReaction { public final static int constructor = 0xbbab2643; @Override public void readParams(AbstractSerializedData stream, boolean exception) { message = TLRPC.Message.TLdeserialize(stream, stream.readInt32(exception), exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); message.serializeToStream(stream); } } public static class TL_storyReactionPublicRepost extends StoryReaction { public final static int constructor = 0xcfcd0f13; @Override public void readParams(AbstractSerializedData stream, boolean exception) { peer_id = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); story = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); if (story != null) { story.dialogId = DialogObject.getPeerDialogId(peer_id); } } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer_id.serializeToStream(stream); story.serializeToStream(stream); } } public static class TL_storyReaction extends StoryReaction { public final static int constructor = 0x6090d6d5; public int date; public TLRPC.Reaction reaction; @Override public void readParams(AbstractSerializedData stream, boolean exception) { peer_id = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); date = stream.readInt32(exception); reaction = TLRPC.Reaction.TLdeserialize(stream, stream.readInt32(exception), exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer_id.serializeToStream(stream); stream.writeInt32(date); reaction.serializeToStream(stream); } } public static class TL_storyReactionsList extends TLObject { public final static int constructor = 0xaa5f789c; public int flags; public int count; public ArrayList<StoryReaction> reactions = new ArrayList<>(); public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public String next_offset; public static TL_storyReactionsList TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_storyReactionsList.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_storyReactionsList", constructor)); } else { return null; } } TL_storyReactionsList result = new TL_storyReactionsList(); result.readParams(stream, exception); return result; } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(count); stream.writeInt32(0x1cb5c415); int count = reactions.size(); stream.writeInt32(count); for (int i = 0; i < count; ++i) { reactions.get(i).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = chats.size(); stream.writeInt32(count); for (int i = 0; i < count; ++i) { chats.get(i).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int i = 0; i < count; ++i) { users.get(i).serializeToStream(stream); } if ((flags & 1) != 0) { stream.writeString(next_offset); } } @Override public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); count = stream.readInt32(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryReaction object = StoryReaction.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } reactions.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.Chat object = TLRPC.Chat.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } chats.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } if ((flags & 1) != 0) { next_offset = stream.readString(exception); } } } public static class TL_getStoryReactionsList extends TLObject { public final static int constructor = 0xb9b2881f; public int flags; public boolean forwards_first; public TLRPC.InputPeer peer; public int id; public TLRPC.Reaction reaction; public String offset; public int limit; @Override public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_storyReactionsList.TLdeserialize(stream, constructor, exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = forwards_first ? (flags | 4) : (flags &~ 4); stream.writeInt32(flags); peer.serializeToStream(stream); stream.writeInt32(id); if ((flags & 1) != 0) { reaction.serializeToStream(stream); } if ((flags & 2) != 0) { stream.writeString(offset); } stream.writeInt32(limit); } } public static class TL_togglePinnedToTop extends TLObject { public static final int constructor = 0xb297e9b; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Bool.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } } } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/tgnet/tl/TL_stories.java
2,176
package org.telegram.ui; import static org.telegram.messenger.AndroidUtilities.dp; import static org.telegram.messenger.LocaleController.getString; 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.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.drawable.ColorDrawable; 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.TextUtils; 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.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.core.graphics.ColorUtils; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.android.billingclient.api.BillingClient; import com.android.billingclient.api.BillingFlowParams; import com.android.billingclient.api.ProductDetails; import com.android.billingclient.api.Purchase; import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.BillingController; import org.telegram.messenger.BuildVars; import org.telegram.messenger.FileLoader; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaDataController; 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.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; import org.telegram.ui.Business.AwayMessagesActivity; import org.telegram.ui.Business.BusinessChatbotController; import org.telegram.ui.Business.BusinessIntroActivity; import org.telegram.ui.Business.BusinessLinksActivity; import org.telegram.ui.Business.BusinessLinksController; import org.telegram.ui.Business.ChatbotsActivity; import org.telegram.ui.Business.GreetMessagesActivity; import org.telegram.ui.Business.LocationActivity; import org.telegram.ui.Business.OpeningHoursActivity; import org.telegram.ui.Business.QuickRepliesActivity; import org.telegram.ui.Business.QuickRepliesController; import org.telegram.ui.Business.TimezonesController; import org.telegram.ui.Cells.HeaderCell; import org.telegram.ui.Cells.ShadowSectionCell; import org.telegram.ui.Cells.TextCell; import org.telegram.ui.Cells.TextInfoPrivacyCell; import org.telegram.ui.Components.AlertsCreator; import org.telegram.ui.Components.AnimatedEmojiDrawable; import org.telegram.ui.Components.BulletinFactory; import org.telegram.ui.Components.CombinedDrawable; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.FillLastLinearLayoutManager; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.MediaActivity; import org.telegram.ui.Components.Premium.AboutPremiumView; import org.telegram.ui.Components.Premium.GLIcon.GLIconRenderer; import org.telegram.ui.Components.Premium.GLIcon.GLIconTextureView; import org.telegram.ui.Components.Premium.GLIcon.Icon3D; import org.telegram.ui.Components.Premium.PremiumButtonView; import org.telegram.ui.Components.Premium.PremiumFeatureBottomSheet; import org.telegram.ui.Components.Premium.PremiumGradient; import org.telegram.ui.Components.Premium.PremiumNotAvailableBottomSheet; import org.telegram.ui.Components.Premium.PremiumTierCell; import org.telegram.ui.Components.Premium.StarParticlesView; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.SimpleThemeDescription; import org.telegram.ui.Components.TextStyleSpan; import org.telegram.ui.Components.URLSpanBotCommand; import org.telegram.ui.Components.URLSpanBrowser; 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.Stories.recorder.HintView2; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Objects; public class PremiumPreviewFragment extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { public final static String TRANSACTION_PATTERN = "^(.*?)(?:\\.\\.\\d*|)$"; private final static boolean IS_PREMIUM_TIERS_UNAVAILABLE = false; RecyclerListView listView; ArrayList<PremiumFeatureData> premiumFeatures = new ArrayList<>(); ArrayList<PremiumFeatureData> morePremiumFeatures = new ArrayList<>(); ArrayList<SubscriptionTier> subscriptionTiers = new ArrayList<>(); int selectedTierIndex = 0; SubscriptionTier currentSubscriptionTier; int rowCount; int paddingRow; int featuresStartRow; int featuresEndRow; int moreHeaderRow; int moreFeaturesStartRow; int moreFeaturesEndRow; int sectionRow; int helpUsRow; int statusRow; int privacyRow; int lastPaddingRow; int showAdsHeaderRow; int showAdsRow; int showAdsInfoRow; Drawable shadowDrawable; private FrameLayout buttonContainer; private View buttonDivider; PremiumFeatureCell dummyCell; PremiumTierCell dummyTierCell; int totalGradientHeight; int totalTiersGradientHeight; FillLastLinearLayoutManager layoutManager; //icons Shader shader; Matrix matrix = new Matrix(); Paint gradientPaint = new Paint(Paint.ANTI_ALIAS_FLAG); BackgroundView backgroundView; StarParticlesView particlesView; boolean isLandscapeMode; public final static int FEATURES_PREMIUM = 0; public final static int FEATURES_BUSINESS = 1; public final static int PREMIUM_FEATURE_LIMITS = 0; public final static int PREMIUM_FEATURE_UPLOAD_LIMIT = 1; public final static int PREMIUM_FEATURE_DOWNLOAD_SPEED = 2; public final static int PREMIUM_FEATURE_ADS = 3; public final static int PREMIUM_FEATURE_REACTIONS = 4; public final static int PREMIUM_FEATURE_STICKERS = 5; public final static int PREMIUM_FEATURE_PROFILE_BADGE = 6; public final static int PREMIUM_FEATURE_ANIMATED_AVATARS = 7; public final static int PREMIUM_FEATURE_VOICE_TO_TEXT = 8; public final static int PREMIUM_FEATURE_ADVANCED_CHAT_MANAGEMENT = 9; public final static int PREMIUM_FEATURE_APPLICATION_ICONS = 10; public final static int PREMIUM_FEATURE_ANIMATED_EMOJI = 11; public final static int PREMIUM_FEATURE_EMOJI_STATUS = 12; public final static int PREMIUM_FEATURE_TRANSLATIONS = 13; public final static int PREMIUM_FEATURE_STORIES = 14; public final static int PREMIUM_FEATURE_STORIES_STEALTH_MODE = 15; public final static int PREMIUM_FEATURE_STORIES_VIEWS_HISTORY = 16; public final static int PREMIUM_FEATURE_STORIES_EXPIRATION_DURATION = 17; public final static int PREMIUM_FEATURE_STORIES_SAVE_TO_GALLERY = 18; public final static int PREMIUM_FEATURE_STORIES_LINKS_AND_FORMATTING = 19; public final static int PREMIUM_FEATURE_STORIES_PRIORITY_ORDER = 20; public final static int PREMIUM_FEATURE_STORIES_CAPTION = 21; public final static int PREMIUM_FEATURE_WALLPAPER = 22; public final static int PREMIUM_FEATURE_NAME_COLOR = 23; public final static int PREMIUM_FEATURE_SAVED_TAGS = 24; public final static int PREMIUM_FEATURE_STORIES_QUALITY = 25; public final static int PREMIUM_FEATURE_LAST_SEEN = 26; public final static int PREMIUM_FEATURE_MESSAGE_PRIVACY = 27; public final static int PREMIUM_FEATURE_BUSINESS = 28; public final static int PREMIUM_FEATURE_BUSINESS_LOCATION = 29; public final static int PREMIUM_FEATURE_BUSINESS_OPENING_HOURS = 30; public final static int PREMIUM_FEATURE_BUSINESS_QUICK_REPLIES = 31; public final static int PREMIUM_FEATURE_BUSINESS_GREETING_MESSAGES = 32; public final static int PREMIUM_FEATURE_BUSINESS_AWAY_MESSAGES = 33; public final static int PREMIUM_FEATURE_BUSINESS_CHATBOTS = 34; public final static int PREMIUM_FEATURE_FOLDER_TAGS = 35; public final static int PREMIUM_FEATURE_BUSINESS_INTRO = 36; public final static int PREMIUM_FEATURE_BUSINESS_CHAT_LINKS = 37; private int statusBarHeight; private int firstViewHeight; private boolean isDialogVisible; boolean inc; float progress; private int currentYOffset; private FrameLayout contentView; private PremiumButtonView premiumButtonView; float totalProgress; private final int type; private boolean whiteBackground; private String source; private boolean selectAnnualByDefault; final Bitmap gradientTextureBitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); final Canvas gradientCanvas = new Canvas(gradientTextureBitmap); PremiumGradient.PremiumGradientTools gradientTools = new PremiumGradient.PremiumGradientTools(Theme.key_premiumGradientBackground1, Theme.key_premiumGradientBackground2, Theme.key_premiumGradientBackground3, Theme.key_premiumGradientBackground4); PremiumGradient.PremiumGradientTools tiersGradientTools; private boolean forcePremium; float progressToFull; public static int serverStringToFeatureType(String s) { switch (s) { case "double_limits": return PREMIUM_FEATURE_LIMITS; case "more_upload": return PREMIUM_FEATURE_UPLOAD_LIMIT; case "faster_download": return PREMIUM_FEATURE_DOWNLOAD_SPEED; case "voice_to_text": return PREMIUM_FEATURE_VOICE_TO_TEXT; case "no_ads": return PREMIUM_FEATURE_ADS; case "infinite_reactions": return PREMIUM_FEATURE_REACTIONS; case "premium_stickers": return PREMIUM_FEATURE_STICKERS; case "advanced_chat_management": return PREMIUM_FEATURE_ADVANCED_CHAT_MANAGEMENT; case "profile_badge": return PREMIUM_FEATURE_PROFILE_BADGE; case "animated_userpics": return PREMIUM_FEATURE_ANIMATED_AVATARS; case "app_icons": return PREMIUM_FEATURE_APPLICATION_ICONS; case "animated_emoji": return PREMIUM_FEATURE_ANIMATED_EMOJI; case "emoji_status": return PREMIUM_FEATURE_EMOJI_STATUS; case "translations": return PREMIUM_FEATURE_TRANSLATIONS; case "stories": return PREMIUM_FEATURE_STORIES; case "stories__stealth_mode": return PREMIUM_FEATURE_STORIES_STEALTH_MODE; case "stories__quality": return PREMIUM_FEATURE_STORIES_QUALITY; case "stories__permanent_views_history": return PREMIUM_FEATURE_STORIES_VIEWS_HISTORY; case "stories__expiration_durations": return PREMIUM_FEATURE_STORIES_EXPIRATION_DURATION; case "stories__save_stories_to_gallery": return PREMIUM_FEATURE_STORIES_SAVE_TO_GALLERY; case "stories__links_and_formatting": return PREMIUM_FEATURE_STORIES_LINKS_AND_FORMATTING; case "stories__priority_order": return PREMIUM_FEATURE_STORIES_PRIORITY_ORDER; case "stories__caption": return PREMIUM_FEATURE_STORIES_CAPTION; case "wallpapers": return PREMIUM_FEATURE_WALLPAPER; case "peer_colors": return PREMIUM_FEATURE_NAME_COLOR; case "saved_tags": return PREMIUM_FEATURE_SAVED_TAGS; case "last_seen": return PREMIUM_FEATURE_LAST_SEEN; case "message_privacy": return PREMIUM_FEATURE_MESSAGE_PRIVACY; case "folder_tags": return PREMIUM_FEATURE_FOLDER_TAGS; case "business": return PREMIUM_FEATURE_BUSINESS; case "greeting_message": return PREMIUM_FEATURE_BUSINESS_GREETING_MESSAGES; case "away_message": return PREMIUM_FEATURE_BUSINESS_AWAY_MESSAGES; case "quick_replies": return PREMIUM_FEATURE_BUSINESS_QUICK_REPLIES; case "business_bots": return PREMIUM_FEATURE_BUSINESS_CHATBOTS; case "business_intro": return PREMIUM_FEATURE_BUSINESS_INTRO; case "business_links": return PREMIUM_FEATURE_BUSINESS_CHAT_LINKS; case "business_hours": return PREMIUM_FEATURE_BUSINESS_OPENING_HOURS; case "business_location": return PREMIUM_FEATURE_BUSINESS_LOCATION; } return -1; } public static String featureTypeToServerString(int type) { switch (type) { case PREMIUM_FEATURE_LIMITS: return "double_limits"; case PREMIUM_FEATURE_UPLOAD_LIMIT: return "more_upload"; case PREMIUM_FEATURE_DOWNLOAD_SPEED: return "faster_download"; case PREMIUM_FEATURE_VOICE_TO_TEXT: return "voice_to_text"; case PREMIUM_FEATURE_ADS: return "no_ads"; case PREMIUM_FEATURE_REACTIONS: return "infinite_reactions"; case PREMIUM_FEATURE_ANIMATED_EMOJI: return "animated_emoji"; case PREMIUM_FEATURE_STICKERS: return "premium_stickers"; case PREMIUM_FEATURE_ADVANCED_CHAT_MANAGEMENT: return "advanced_chat_management"; case PREMIUM_FEATURE_PROFILE_BADGE: return "profile_badge"; case PREMIUM_FEATURE_ANIMATED_AVATARS: return "animated_userpics"; case PREMIUM_FEATURE_APPLICATION_ICONS: return "app_icons"; case PREMIUM_FEATURE_EMOJI_STATUS: return "emoji_status"; case PREMIUM_FEATURE_TRANSLATIONS: return "translations"; case PREMIUM_FEATURE_STORIES: return "stories"; case PREMIUM_FEATURE_STORIES_STEALTH_MODE: return "stories__stealth_mode"; case PREMIUM_FEATURE_STORIES_QUALITY: return "stories__quality"; case PREMIUM_FEATURE_STORIES_VIEWS_HISTORY: return "stories__permanent_views_history"; case PREMIUM_FEATURE_STORIES_EXPIRATION_DURATION: return "stories__expiration_durations"; case PREMIUM_FEATURE_STORIES_SAVE_TO_GALLERY: return "stories__save_stories_to_gallery"; case PREMIUM_FEATURE_STORIES_LINKS_AND_FORMATTING: return "stories__links_and_formatting"; case PREMIUM_FEATURE_STORIES_PRIORITY_ORDER: return "stories__priority_order"; case PREMIUM_FEATURE_STORIES_CAPTION: return "stories__caption"; case PREMIUM_FEATURE_WALLPAPER: return "wallpapers"; case PREMIUM_FEATURE_NAME_COLOR: return "peer_colors"; case PREMIUM_FEATURE_SAVED_TAGS: return "saved_tags"; case PREMIUM_FEATURE_LAST_SEEN: return "last_seen"; case PREMIUM_FEATURE_MESSAGE_PRIVACY: return "message_privacy"; case PREMIUM_FEATURE_FOLDER_TAGS: return "folder_tags"; case PREMIUM_FEATURE_BUSINESS: return "business"; case PREMIUM_FEATURE_BUSINESS_GREETING_MESSAGES: return "greeting_message"; case PREMIUM_FEATURE_BUSINESS_AWAY_MESSAGES: return "away_message"; case PREMIUM_FEATURE_BUSINESS_QUICK_REPLIES: return "quick_replies"; case PREMIUM_FEATURE_BUSINESS_CHATBOTS: return "business_bots"; case PREMIUM_FEATURE_BUSINESS_INTRO: return "business_intro"; case PREMIUM_FEATURE_BUSINESS_CHAT_LINKS: return "business_links"; case PREMIUM_FEATURE_BUSINESS_OPENING_HOURS: return "business_hours"; case PREMIUM_FEATURE_BUSINESS_LOCATION: return "business_location"; } return null; } public PremiumPreviewFragment setForcePremium() { this.forcePremium = true; return this; } public PremiumPreviewFragment(String source) { this(FEATURES_PREMIUM, source); } public PremiumPreviewFragment(int type, String source) { super(); this.type = type; whiteBackground = !Theme.isCurrentThemeDark() && type == FEATURES_BUSINESS; this.source = source; } { tiersGradientTools = new PremiumGradient.PremiumGradientTools(Theme.key_premiumGradient1, Theme.key_premiumGradient2, -1, -1); tiersGradientTools.exactly = true; tiersGradientTools.x1 = 0; tiersGradientTools.y1 = 0f; tiersGradientTools.x2 = 0; tiersGradientTools.y2 = 1f; tiersGradientTools.cx = 0; tiersGradientTools.cy = 0; } public PremiumPreviewFragment setSelectAnnualByDefault() { this.selectAnnualByDefault = true; return this; } @SuppressLint("NotifyDataSetChanged") @Override public View createView(Context context) { hasOwnBackground = true; shader = new LinearGradient( 0, 0, 0, 100, new int[]{ Theme.getColor(Theme.key_premiumGradient4), Theme.getColor(Theme.key_premiumGradient3), Theme.getColor(Theme.key_premiumGradient2), Theme.getColor(Theme.key_premiumGradient1), Theme.getColor(Theme.key_premiumGradient0) }, new float[]{0f, 0.32f, 0.5f, 0.7f, 1f}, Shader.TileMode.CLAMP ); shader.setLocalMatrix(matrix); gradientPaint.setShader(shader); dummyCell = new PremiumFeatureCell(context); dummyTierCell = new PremiumTierCell(context); premiumFeatures.clear(); morePremiumFeatures.clear(); if (type == FEATURES_PREMIUM) { fillPremiumFeaturesList(premiumFeatures, currentAccount, false); } else { fillBusinessFeaturesList(premiumFeatures, currentAccount, false); fillBusinessFeaturesList(morePremiumFeatures, currentAccount, true); // preload QuickRepliesController.getInstance(currentAccount).load(); if (getUserConfig().isPremium()) { TLRPC.InputStickerSet inputStickerSet = new TLRPC.TL_inputStickerSetShortName(); inputStickerSet.short_name = "RestrictedEmoji"; MediaDataController.getInstance(currentAccount).getStickerSet(inputStickerSet, false); BusinessChatbotController.getInstance(currentAccount).load(null); if (getMessagesController().suggestedFilters.isEmpty()) { getMessagesController().loadSuggestedFilters(); } BusinessLinksController.getInstance(currentAccount).load(false); } } Rect padding = new Rect(); shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); shadowDrawable.getPadding(padding); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { statusBarHeight = AndroidUtilities.isTablet() ? 0 : AndroidUtilities.statusBarHeight; } contentView = new FrameLayout(context) { int lastSize; boolean iconInterceptedTouch; boolean listInterceptedTouch; @Override public boolean dispatchTouchEvent(MotionEvent ev) { float iconX = backgroundView.getX() + backgroundView.imageFrameLayout.getX(); float iconY = backgroundView.getY() + backgroundView.imageFrameLayout.getY(); AndroidUtilities.rectTmp.set(iconX, iconY, iconX + (backgroundView.imageView == null ? 0 : backgroundView.imageView.getMeasuredWidth()), iconY + (backgroundView.imageView == null ? 0 : backgroundView.imageView.getMeasuredHeight())); if ((AndroidUtilities.rectTmp.contains(ev.getX(), ev.getY()) || iconInterceptedTouch) && !listView.scrollingByUser) { ev.offsetLocation(-iconX, -iconY); if (ev.getAction() == MotionEvent.ACTION_DOWN || ev.getAction() == MotionEvent.ACTION_MOVE) { iconInterceptedTouch = true; } else if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) { iconInterceptedTouch = false; } backgroundView.imageView.dispatchTouchEvent(ev); return true; } float listX = backgroundView.getX() + backgroundView.tierListView.getX(), listY = backgroundView.getY() + backgroundView.tierListView.getY(); AndroidUtilities.rectTmp.set(listX, listY, listX + backgroundView.tierListView.getWidth(), listY + backgroundView.tierListView.getHeight()); if (progressToFull < 1.0f && (AndroidUtilities.rectTmp.contains(ev.getX(), ev.getY()) || listInterceptedTouch) && !listView.scrollingByUser) { ev.offsetLocation(-listX, -listY); if (ev.getAction() == MotionEvent.ACTION_DOWN) { listInterceptedTouch = true; } else if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) { listInterceptedTouch = false; } backgroundView.tierListView.dispatchTouchEvent(ev); if (listInterceptedTouch) { return true; } } return super.dispatchTouchEvent(ev); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (MeasureSpec.getSize(widthMeasureSpec) > MeasureSpec.getSize(heightMeasureSpec)) { isLandscapeMode = true; } else { isLandscapeMode = false; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { statusBarHeight = AndroidUtilities.isTablet() ? 0 : AndroidUtilities.statusBarHeight; } backgroundView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); particlesView.getLayoutParams().height = backgroundView.getMeasuredHeight(); int buttonHeight = (buttonContainer == null || buttonContainer.getVisibility() == View.GONE ? 0 : dp(68)); layoutManager.setAdditionalHeight(buttonHeight + statusBarHeight - dp(16)); layoutManager.setMinimumLastViewHeight(buttonHeight); super.onMeasure(widthMeasureSpec, heightMeasureSpec); int size = getMeasuredHeight() + getMeasuredWidth() << 16; if (lastSize != size) { updateBackgroundImage(); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); backgroundView.imageView.mRenderer.gradientScaleX = backgroundView.imageView.getMeasuredWidth() / (float) getMeasuredWidth(); backgroundView.imageView.mRenderer.gradientScaleY = backgroundView.imageView.getMeasuredHeight() / (float) getMeasuredHeight(); backgroundView.imageView.mRenderer.gradientStartX = (backgroundView.getX() + backgroundView.imageView.getX()) / getMeasuredWidth(); backgroundView.imageView.mRenderer.gradientStartY = (backgroundView.getY() + backgroundView.imageView.getY()) / getMeasuredHeight(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); measureGradient(w, h); } private final Paint backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); @Override protected void dispatchDraw(Canvas canvas) { if (!isDialogVisible) { if (inc) { progress += 16f / 1000f; if (progress > 3) { inc = false; } } else { progress -= 16f / 1000f; if (progress < 1) { inc = true; } } } View firstView = null; if (listView.getLayoutManager() != null) { firstView = listView.getLayoutManager().findViewByPosition(0); } currentYOffset = firstView == null ? 0 : firstView.getBottom(); int h = actionBar.getBottom() + dp(16); totalProgress = (1f - (currentYOffset - h) / (float) (firstViewHeight - h)); totalProgress = Utilities.clamp(totalProgress, 1f, 0f); int maxTop = actionBar.getBottom() + dp(16); if (currentYOffset < maxTop) { currentYOffset = maxTop; } float oldProgress = progressToFull; progressToFull = 0; if (currentYOffset < maxTop + dp(30)) { progressToFull = (maxTop + dp(30) - currentYOffset) / (float) dp(30); } if (isLandscapeMode) { progressToFull = 1f; totalProgress = 1f; } if (oldProgress != progressToFull) { listView.invalidate(); } float fromTranslation = currentYOffset - (actionBar.getMeasuredHeight() + backgroundView.getMeasuredHeight() - statusBarHeight) + dp(backgroundView.tierListView.getVisibility() == VISIBLE ? 24 : 16); float toTranslation = ((actionBar.getMeasuredHeight() - statusBarHeight - backgroundView.titleView.getMeasuredHeight()) / 2f) + statusBarHeight - backgroundView.getTop() - backgroundView.titleView.getTop(); float translationsY = Math.max(toTranslation, fromTranslation); float iconTranslationsY = -translationsY / 4f + dp(16); backgroundView.setTranslationY(translationsY); backgroundView.imageView.setTranslationY(iconTranslationsY + dp(type == FEATURES_BUSINESS ? 9 : 16)); float s = 0.6f + (1f - totalProgress) * 0.4f; float alpha = 1f - (totalProgress > 0.5f ? (totalProgress - 0.5f) / 0.5f : 0f); backgroundView.imageView.setScaleX(s); backgroundView.imageView.setScaleY(s); backgroundView.imageView.setAlpha(alpha); backgroundView.subtitleView.setAlpha(alpha); backgroundView.tierListView.setAlpha(alpha); particlesView.setAlpha(1f - totalProgress); particlesView.setTranslationY(-(particlesView.getMeasuredHeight() - backgroundView.imageView.getMeasuredWidth()) / 2f + backgroundView.getY() + backgroundView.imageFrameLayout.getY()); float toX = dp(72) - backgroundView.titleView.getLeft(); float f = totalProgress > 0.3f ? (totalProgress - 0.3f) / 0.7f : 0f; backgroundView.titleView.setTranslationX(toX * (1f - CubicBezierInterpolator.EASE_OUT_QUINT.getInterpolation(1 - f))); backgroundView.imageView.mRenderer.gradientStartX = (backgroundView.getX() + backgroundView.imageFrameLayout.getX() + getMeasuredWidth() * 0.1f * progress) / getMeasuredWidth(); backgroundView.imageView.mRenderer.gradientStartY = (backgroundView.getY() + backgroundView.imageFrameLayout.getY()) / getMeasuredHeight(); if (!isDialogVisible) { invalidate(); } gradientTools.gradientMatrix(0, 0, getMeasuredWidth(), getMeasuredHeight(), -getMeasuredWidth() * 0.1f * progress, 0); if (whiteBackground) { backgroundPaint.setColor(ColorUtils.blendARGB(getThemedColor(Theme.key_windowBackgroundGray), getThemedColor(Theme.key_windowBackgroundWhite), progressToFull)); canvas.drawRect(0, 0, getMeasuredWidth(), currentYOffset + dp(20), backgroundPaint); } else { canvas.drawRect(0, 0, getMeasuredWidth(), currentYOffset + dp(20), gradientTools.paint); } super.dispatchDraw(canvas); if (parentLayout != null && whiteBackground) { parentLayout.drawHeaderShadow(canvas, (int) (0xFF * progressToFull), actionBar.getBottom()); } } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { if (child == listView) { canvas.save(); canvas.clipRect(0, actionBar.getBottom(), getMeasuredWidth(), getMeasuredHeight()); super.drawChild(canvas, child, drawingTime); canvas.restore(); return true; } return super.drawChild(canvas, child, drawingTime); } }; contentView.setFitsSystemWindows(true); listView = new RecyclerListView(context) { @Override public void onDraw(Canvas canvas) { shadowDrawable.setBounds((int) (-padding.left - dp(16) * progressToFull), currentYOffset - padding.top - dp(16), (int) (getMeasuredWidth() + padding.right + dp(16) * progressToFull), getMeasuredHeight()); shadowDrawable.draw(canvas); super.onDraw(canvas); } }; listView.setLayoutManager(layoutManager = new FillLastLinearLayoutManager(context, dp(68) + statusBarHeight - dp(16), listView)); layoutManager.setFixedLastItemHeight(); listView.setAdapter(new Adapter()); listView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE) { int maxTop = actionBar.getBottom() + dp(16); if (totalProgress > 0.5f) { listView.smoothScrollBy(0, currentYOffset - maxTop); } else { View firstView = null; if (listView.getLayoutManager() != null) { firstView = listView.getLayoutManager().findViewByPosition(0); } if (firstView != null && firstView.getTop() < 0) { listView.smoothScrollBy(0, firstView.getTop()); } } } checkButtonDivider(); } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); contentView.invalidate(); checkButtonDivider(); } }); backgroundView = new BackgroundView(context) { @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return true; } }; particlesView = new StarParticlesView(context); particlesView.setClipWithGradient(); if (type == FEATURES_BUSINESS) { if (whiteBackground) { particlesView.drawable.useGradient = true; particlesView.drawable.useBlur = false; particlesView.drawable.checkBounds = true; particlesView.drawable.isCircle = true; particlesView.drawable.centerOffsetY = dp(-14); particlesView.drawable.minLifeTime = 2000; particlesView.drawable.randLifeTime = 3000; particlesView.drawable.size1 = 16; particlesView.drawable.useRotate = false; particlesView.drawable.type = PremiumPreviewFragment.PREMIUM_FEATURE_BUSINESS; particlesView.drawable.colorKey = Theme.key_premiumGradient2; } else { particlesView.drawable.isCircle = true; particlesView.drawable.centerOffsetY = dp(28); particlesView.drawable.minLifeTime = 2000; particlesView.drawable.randLifeTime = 3000; particlesView.drawable.size1 = 16; particlesView.drawable.useRotate = false; particlesView.drawable.type = PREMIUM_FEATURE_BUSINESS; } } backgroundView.imageView.setStarParticlesView(particlesView); contentView.addView(particlesView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); contentView.addView(backgroundView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); listView.setOnItemClickListener((view, position) -> { if (position == showAdsRow) { TLRPC.UserFull userFull = getMessagesController().getUserFull(getUserConfig().getClientUserId()); if (userFull == null) return; TextCell cell = (TextCell) view; cell.setChecked(!cell.isChecked()); userFull.sponsored_enabled = cell.isChecked(); TLRPC.TL_account_toggleSponsoredMessages req = new TLRPC.TL_account_toggleSponsoredMessages(); req.enabled = userFull.sponsored_enabled; getConnectionsManager().sendRequest(req, (res, err) -> AndroidUtilities.runOnUIThread(() -> { if (err != null) { BulletinFactory.showError(err); } else if (!(res instanceof TLRPC.TL_boolTrue)) { BulletinFactory.of(PremiumPreviewFragment.this).createErrorBulletin(getString(R.string.UnknownError)).show(); } })); getMessagesStorage().updateUserInfo(userFull, false); return; } if (view instanceof PremiumFeatureCell) { PremiumFeatureCell cell = (PremiumFeatureCell) view; if (type == FEATURES_BUSINESS && getUserConfig().isPremium()) { if (cell.data.type == PREMIUM_FEATURE_BUSINESS_LOCATION) { presentFragment(new LocationActivity()); } else if (cell.data.type == PREMIUM_FEATURE_BUSINESS_GREETING_MESSAGES) { presentFragment(new GreetMessagesActivity()); } else if (cell.data.type == PREMIUM_FEATURE_BUSINESS_AWAY_MESSAGES) { presentFragment(new AwayMessagesActivity()); } else if (cell.data.type == PREMIUM_FEATURE_BUSINESS_OPENING_HOURS) { presentFragment(new OpeningHoursActivity()); } else if (cell.data.type == PREMIUM_FEATURE_BUSINESS_CHATBOTS) { presentFragment(new ChatbotsActivity()); } else if (cell.data.type == PREMIUM_FEATURE_BUSINESS_QUICK_REPLIES) { presentFragment(new QuickRepliesActivity()); } else if (cell.data.type == PREMIUM_FEATURE_STORIES) { Bundle args = new Bundle(); args.putLong("dialog_id", UserConfig.getInstance(currentAccount).getClientUserId()); args.putInt("type", MediaActivity.TYPE_STORIES); presentFragment(new MediaActivity(args, null)); } else if (cell.data.type == PREMIUM_FEATURE_EMOJI_STATUS) { showSelectStatusDialog(cell, UserObject.getEmojiStatusDocumentId(getUserConfig().getCurrentUser()), (documentId, until) -> { TLRPC.EmojiStatus emojiStatus; if (documentId == null) { emojiStatus = new TLRPC.TL_emojiStatusEmpty(); } else if (until != null) { emojiStatus = new TLRPC.TL_emojiStatusUntil(); ((TLRPC.TL_emojiStatusUntil) emojiStatus).document_id = documentId; ((TLRPC.TL_emojiStatusUntil) emojiStatus).until = until; } else { emojiStatus = new TLRPC.TL_emojiStatus(); ((TLRPC.TL_emojiStatus) emojiStatus).document_id = documentId; } getMessagesController().updateEmojiStatus(emojiStatus); cell.setEmoji(documentId == null ? 0 : documentId, true); }); } else if (cell.data.type == PREMIUM_FEATURE_FOLDER_TAGS) { presentFragment(new FiltersSetupActivity().highlightTags()); } else if (cell.data.type == PREMIUM_FEATURE_BUSINESS_INTRO) { presentFragment(new BusinessIntroActivity()); } else if (cell.data.type == PREMIUM_FEATURE_BUSINESS_CHAT_LINKS) { presentFragment(new BusinessLinksActivity()); } return; } PremiumPreviewFragment.sentShowFeaturePreview(currentAccount, cell.data.type); SubscriptionTier tier = selectedTierIndex < 0 || selectedTierIndex >= subscriptionTiers.size() ? null : subscriptionTiers.get(selectedTierIndex); showDialog(new PremiumFeatureBottomSheet(PremiumPreviewFragment.this, getContext(), currentAccount, type == FEATURES_BUSINESS, cell.data.type, false, tier)); } }); contentView.addView(listView); premiumButtonView = new PremiumButtonView(context, false, getResourceProvider()); updateButtonText(false); buttonContainer = new FrameLayout(context); buttonDivider = new View(context); buttonDivider.setBackgroundColor(Theme.getColor(Theme.key_divider)); buttonContainer.addView(buttonDivider, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 1)); buttonDivider.getLayoutParams().height = 1; AndroidUtilities.updateViewVisibilityAnimated(buttonDivider, true, 1f, false); buttonContainer.addView(premiumButtonView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.CENTER_VERTICAL, 16, 0, 16, 0)); buttonContainer.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); contentView.addView(buttonContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 68, Gravity.BOTTOM)); fragmentView = contentView; actionBar.setBackground(null); actionBar.setCastShadows(false); actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } } }); actionBar.setForceSkipTouches(true); updateColors(); updateRows(); backgroundView.imageView.startEnterAnimation(-180, 200); if (forcePremium) { AndroidUtilities.runOnUIThread(() -> getMediaDataController().loadPremiumPromo(false), 400); } MediaDataController.getInstance(currentAccount).preloadPremiumPreviewStickers(); sentShowScreenStat(source); return fragmentView; } @Override public boolean isActionBarCrossfadeEnabled() { return false; } public static void buyPremium(BaseFragment fragment) { buyPremium(fragment, "settings"); } public static void fillPremiumFeaturesList(ArrayList<PremiumFeatureData> premiumFeatures, int currentAccount, boolean all) { MessagesController messagesController = MessagesController.getInstance(currentAccount); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_LIMITS, R.drawable.msg_premium_limits, getString("PremiumPreviewLimits", R.string.PremiumPreviewLimits), LocaleController.formatString("PremiumPreviewLimitsDescription", R.string.PremiumPreviewLimitsDescription, messagesController.channelsLimitPremium, messagesController.dialogFiltersLimitPremium, messagesController.dialogFiltersPinnedLimitPremium, messagesController.publicLinksLimitPremium, 4))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_STORIES, R.drawable.msg_filled_stories, getString(R.string.PremiumPreviewStories), LocaleController.formatString(R.string.PremiumPreviewStoriesDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_UPLOAD_LIMIT, R.drawable.msg_premium_uploads, getString("PremiumPreviewUploads", R.string.PremiumPreviewUploads), getString("PremiumPreviewUploadsDescription", R.string.PremiumPreviewUploadsDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_DOWNLOAD_SPEED, R.drawable.msg_premium_speed, getString("PremiumPreviewDownloadSpeed", R.string.PremiumPreviewDownloadSpeed), getString("PremiumPreviewDownloadSpeedDescription", R.string.PremiumPreviewDownloadSpeedDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_VOICE_TO_TEXT, R.drawable.msg_premium_voice, getString("PremiumPreviewVoiceToText", R.string.PremiumPreviewVoiceToText), getString("PremiumPreviewVoiceToTextDescription", R.string.PremiumPreviewVoiceToTextDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_ADS, R.drawable.msg_premium_ads, getString("PremiumPreviewNoAds", R.string.PremiumPreviewNoAds), getString("PremiumPreviewNoAdsDescription", R.string.PremiumPreviewNoAdsDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_REACTIONS, R.drawable.msg_premium_reactions, getString(R.string.PremiumPreviewReactions2), getString(R.string.PremiumPreviewReactions2Description))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_STICKERS, R.drawable.msg_premium_stickers, getString(R.string.PremiumPreviewStickers), getString(R.string.PremiumPreviewStickersDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_ANIMATED_EMOJI, R.drawable.msg_premium_emoji, getString(R.string.PremiumPreviewEmoji), getString(R.string.PremiumPreviewEmojiDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_ADVANCED_CHAT_MANAGEMENT, R.drawable.menu_premium_tools, getString(R.string.PremiumPreviewAdvancedChatManagement), getString(R.string.PremiumPreviewAdvancedChatManagementDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_PROFILE_BADGE, R.drawable.msg_premium_badge, getString(R.string.PremiumPreviewProfileBadge), getString(R.string.PremiumPreviewProfileBadgeDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_ANIMATED_AVATARS, R.drawable.msg_premium_avatar, getString(R.string.PremiumPreviewAnimatedProfiles), getString(R.string.PremiumPreviewAnimatedProfilesDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_SAVED_TAGS, R.drawable.premium_tags, getString(R.string.PremiumPreviewTags2), getString(R.string.PremiumPreviewTagsDescription2))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_APPLICATION_ICONS, R.drawable.msg_premium_icons, getString(R.string.PremiumPreviewAppIcon), getString(R.string.PremiumPreviewAppIconDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_EMOJI_STATUS, R.drawable.premium_status, getString(R.string.PremiumPreviewEmojiStatus), getString(R.string.PremiumPreviewEmojiStatusDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_TRANSLATIONS, R.drawable.msg_premium_translate, getString(R.string.PremiumPreviewTranslations), getString(R.string.PremiumPreviewTranslationsDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_WALLPAPER, R.drawable.premium_wallpaper, getString(R.string.PremiumPreviewWallpaper), getString(R.string.PremiumPreviewWallpaperDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_NAME_COLOR, R.drawable.premium_colors, getString(R.string.PremiumPreviewProfileColor), getString(R.string.PremiumPreviewProfileColorDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_LAST_SEEN, R.drawable.menu_premium_seen, getString(R.string.PremiumPreviewLastSeen), getString(R.string.PremiumPreviewLastSeenDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_MESSAGE_PRIVACY, R.drawable.menu_premium_privacy, getString(R.string.PremiumPreviewMessagePrivacy), getString(R.string.PremiumPreviewMessagePrivacyDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_BUSINESS, R.drawable.filled_premium_business, applyNewSpan(getString(R.string.TelegramBusiness)), getString(R.string.PremiumPreviewBusinessDescription))); if (messagesController.premiumFeaturesTypesToPosition.size() > 0) { for (int i = 0; i < premiumFeatures.size(); i++) { if (messagesController.premiumFeaturesTypesToPosition.get(premiumFeatures.get(i).type, -1) == -1 && !BuildVars.DEBUG_PRIVATE_VERSION) { premiumFeatures.remove(i); i--; } } } Collections.sort(premiumFeatures, (o1, o2) -> { int type1 = messagesController.premiumFeaturesTypesToPosition.get(o1.type, Integer.MAX_VALUE); int type2 = messagesController.premiumFeaturesTypesToPosition.get(o2.type, Integer.MAX_VALUE); return type1 - type2; }); } public static void fillBusinessFeaturesList(ArrayList<PremiumFeatureData> premiumFeatures, int currentAccount, boolean additional) { MessagesController messagesController = MessagesController.getInstance(currentAccount); if (!additional) { premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_BUSINESS_LOCATION, R.drawable.filled_location, getString(R.string.PremiumBusinessLocation), getString(R.string.PremiumBusinessLocationDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_BUSINESS_OPENING_HOURS, R.drawable.filled_premium_hours, getString(R.string.PremiumBusinessOpeningHours), getString(R.string.PremiumBusinessOpeningHoursDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_BUSINESS_QUICK_REPLIES, R.drawable.filled_open_message, getString(R.string.PremiumBusinessQuickReplies), getString(R.string.PremiumBusinessQuickRepliesDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_BUSINESS_GREETING_MESSAGES, R.drawable.premium_status, getString(R.string.PremiumBusinessGreetingMessages), getString(R.string.PremiumBusinessGreetingMessagesDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_BUSINESS_AWAY_MESSAGES, R.drawable.filled_premium_away, getString(R.string.PremiumBusinessAwayMessages), getString(R.string.PremiumBusinessAwayMessagesDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_BUSINESS_CHATBOTS, R.drawable.filled_premium_bots, applyNewSpan(getString(R.string.PremiumBusinessChatbots2)), getString(R.string.PremiumBusinessChatbotsDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_BUSINESS_CHAT_LINKS, R.drawable.filled_premium_chatlink, applyNewSpan(getString(R.string.PremiumBusinessChatLinks)), getString(R.string.PremiumBusinessChatLinksDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_BUSINESS_INTRO, R.drawable.filled_premium_intro, applyNewSpan(getString(R.string.PremiumBusinessIntro)), getString(R.string.PremiumBusinessIntroDescription))); } else { premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_EMOJI_STATUS, R.drawable.filled_premium_status2, getString(R.string.PremiumPreviewBusinessEmojiStatus), getString(R.string.PremiumPreviewBusinessEmojiStatusDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_FOLDER_TAGS, R.drawable.premium_tags, getString(R.string.PremiumPreviewFolderTags), getString(R.string.PremiumPreviewFolderTagsDescription))); premiumFeatures.add(new PremiumFeatureData(PREMIUM_FEATURE_STORIES, R.drawable.filled_premium_camera, getString(R.string.PremiumPreviewBusinessStories), getString(R.string.PremiumPreviewBusinessStoriesDescription))); } if (messagesController.businessFeaturesTypesToPosition.size() > 0) { for (int i = 0; i < premiumFeatures.size(); i++) { if (messagesController.businessFeaturesTypesToPosition.get(premiumFeatures.get(i).type, -1) == -1 && !BuildVars.DEBUG_VERSION) { premiumFeatures.remove(i); i--; } } } Collections.sort(premiumFeatures, (o1, o2) -> { int type1 = messagesController.businessFeaturesTypesToPosition.get(o1.type, Integer.MAX_VALUE); int type2 = messagesController.businessFeaturesTypesToPosition.get(o2.type, Integer.MAX_VALUE); return type1 - type2; }); } public static CharSequence applyNewSpan(String str) { SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(str); spannableStringBuilder.append(" d"); FilterCreateActivity.NewSpan span = new FilterCreateActivity.NewSpan(false); span.setColor(Theme.getColor(Theme.key_premiumGradient1)); spannableStringBuilder.setSpan(span, spannableStringBuilder.length() - 1, spannableStringBuilder.length(), 0); return spannableStringBuilder; } private void updateBackgroundImage() { if (contentView.getMeasuredWidth() == 0 || contentView.getMeasuredHeight() == 0 || backgroundView == null || backgroundView.imageView == null) { return; } if (whiteBackground) { Bitmap bitmap = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); canvas.drawColor(ColorUtils.blendARGB(getThemedColor(Theme.key_premiumGradient2), getThemedColor(Theme.key_dialogBackground), 0.5f)); backgroundView.imageView.setBackgroundBitmap(bitmap); } else { gradientTools.gradientMatrix(0, 0, contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), 0, 0); gradientCanvas.save(); gradientCanvas.scale(100f / contentView.getMeasuredWidth(), 100f / contentView.getMeasuredHeight()); gradientCanvas.drawRect(0, 0, contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), gradientTools.paint); gradientCanvas.restore(); backgroundView.imageView.setBackgroundBitmap(gradientTextureBitmap); } } private void checkButtonDivider() { AndroidUtilities.updateViewVisibilityAnimated(buttonDivider, listView.canScrollVertically(1), 1f, true); } public static void buyPremium(BaseFragment fragment, String source) { buyPremium(fragment, null, source, true); } public static void buyPremium(BaseFragment fragment, String source, boolean forcePremium) { buyPremium(fragment, null, source, forcePremium); } public static void buyPremium(BaseFragment fragment, SubscriptionTier tier, String source) { buyPremium(fragment, tier, source, true); } public static void buyPremium(BaseFragment fragment, SubscriptionTier tier, String source, boolean forcePremium) { buyPremium(fragment, tier, source, forcePremium, null); } public static void buyPremium(BaseFragment fragment, SubscriptionTier tier, String source, boolean forcePremium, BillingFlowParams.SubscriptionUpdateParams updateParams) { if (BuildVars.IS_BILLING_UNAVAILABLE) { fragment.showDialog(new PremiumNotAvailableBottomSheet(fragment)); return; } if (tier == null) { forcePremium = true; TLRPC.TL_help_premiumPromo promo = fragment.getAccountInstance().getMediaDataController().getPremiumPromo(); if (promo != null) { for (TLRPC.TL_premiumSubscriptionOption option : promo.period_options) { if (option.months == 1) { tier = new SubscriptionTier(option); } else if (option.months == 12) { tier = new SubscriptionTier(option); break; } } } } SubscriptionTier selectedTier = tier; PremiumPreviewFragment.sentPremiumButtonClick(); if (BuildVars.useInvoiceBilling()) { Activity activity = fragment.getParentActivity(); if (activity instanceof LaunchActivity) { LaunchActivity launchActivity = (LaunchActivity) activity; if (selectedTier == null || selectedTier.subscriptionOption == null || selectedTier.subscriptionOption.bot_url == null) { if (!TextUtils.isEmpty(fragment.getMessagesController().premiumBotUsername)) { launchActivity.setNavigateToPremiumBot(true); launchActivity.onNewIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("https://t.me/" + fragment.getMessagesController().premiumBotUsername + "?start=" + source))); } else if (!TextUtils.isEmpty(fragment.getMessagesController().premiumInvoiceSlug)) { launchActivity.onNewIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("https://t.me/$" + fragment.getMessagesController().premiumInvoiceSlug))); } } else { Uri uri = Uri.parse(selectedTier.subscriptionOption.bot_url); if (uri.getHost().equals("t.me")) { if (!uri.getPath().startsWith("/$") && !uri.getPath().startsWith("/invoice/")) { launchActivity.setNavigateToPremiumBot(true); } } Browser.openUrl(launchActivity, tier.subscriptionOption.bot_url); } return; } } if (BillingController.PREMIUM_PRODUCT_DETAILS == null) { return; } List<ProductDetails.SubscriptionOfferDetails> offerDetails = BillingController.PREMIUM_PRODUCT_DETAILS.getSubscriptionOfferDetails(); if (offerDetails.isEmpty()) { return; } if (selectedTier.getGooglePlayProductDetails() == null) { selectedTier.setGooglePlayProductDetails(BillingController.PREMIUM_PRODUCT_DETAILS); } if (selectedTier.getOfferDetails() == null) { return; } boolean finalForcePremium = forcePremium; BillingController.getInstance().queryPurchases(BillingClient.ProductType.SUBS, (billingResult1, list) -> AndroidUtilities.runOnUIThread(() -> { if (billingResult1.getResponseCode() == BillingClient.BillingResponseCode.OK) { Runnable onSuccess = () -> { if (fragment instanceof PremiumPreviewFragment) { PremiumPreviewFragment premiumPreviewFragment = (PremiumPreviewFragment) fragment; if (finalForcePremium) { premiumPreviewFragment.setForcePremium(); } premiumPreviewFragment.getMediaDataController().loadPremiumPromo(false); premiumPreviewFragment.listView.smoothScrollToPosition(0); } else { PremiumPreviewFragment previewFragment = new PremiumPreviewFragment(null); if (finalForcePremium) { previewFragment.setForcePremium(); } fragment.presentFragment(previewFragment); } if (fragment.getParentActivity() instanceof LaunchActivity) { try { fragment.getFragmentView().performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); } catch (Exception ignored) { } ((LaunchActivity) fragment.getParentActivity()).getFireworksOverlay().start(); } }; if (list != null && !list.isEmpty() && !fragment.getUserConfig().isPremium()) { for (Purchase purchase : list) { if (purchase.getProducts().contains(BillingController.PREMIUM_PRODUCT_ID)) { TLRPC.TL_payments_assignPlayMarketTransaction req = new TLRPC.TL_payments_assignPlayMarketTransaction(); req.receipt = new TLRPC.TL_dataJSON(); req.receipt.data = purchase.getOriginalJson(); TLRPC.TL_inputStorePaymentPremiumSubscription purpose = new TLRPC.TL_inputStorePaymentPremiumSubscription(); purpose.restore = true; if (updateParams != null) { purpose.upgrade = true; } req.purpose = purpose; fragment.getConnectionsManager().sendRequest(req, (response, error) -> { if (response instanceof TLRPC.Updates) { fragment.getMessagesController().processUpdates((TLRPC.Updates) response, false); AndroidUtilities.runOnUIThread(onSuccess); } else if (error != null) { AndroidUtilities.runOnUIThread(() -> AlertsCreator.processError(fragment.getCurrentAccount(), error, fragment, req)); } }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagInvokeAfter); return; } } } BillingController.getInstance().addResultListener(BillingController.PREMIUM_PRODUCT_ID, billingResult -> { if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) { AndroidUtilities.runOnUIThread(onSuccess); } }); TLRPC.TL_payments_canPurchasePremium req = new TLRPC.TL_payments_canPurchasePremium(); TLRPC.TL_inputStorePaymentPremiumSubscription purpose = new TLRPC.TL_inputStorePaymentPremiumSubscription(); if (updateParams != null) { purpose.upgrade = true; } req.purpose = purpose; fragment.getConnectionsManager().sendRequest(req, (response, error) -> { AndroidUtilities.runOnUIThread(() -> { if (response instanceof TLRPC.TL_boolTrue) { BillingController.getInstance().launchBillingFlow(fragment.getParentActivity(), fragment.getAccountInstance(), purpose, Collections.singletonList( BillingFlowParams.ProductDetailsParams.newBuilder() .setProductDetails(BillingController.PREMIUM_PRODUCT_DETAILS) .setOfferToken(selectedTier.getOfferDetails().getOfferToken()) .build() ), updateParams, false); } else { AlertsCreator.processError(fragment.getCurrentAccount(), error, fragment, req); } }); }); } })); } public static String getPremiumButtonText(int currentAccount, SubscriptionTier tier) { if (BuildVars.IS_BILLING_UNAVAILABLE) { return getString(R.string.SubscribeToPremiumNotAvailable); } int stringResId = R.string.SubscribeToPremium; if (tier == null) { if (BuildVars.useInvoiceBilling()) { TLRPC.TL_help_premiumPromo premiumPromo = MediaDataController.getInstance(currentAccount).getPremiumPromo(); if (premiumPromo != null) { TLRPC.TL_premiumSubscriptionOption selectedOption = null; for (TLRPC.TL_premiumSubscriptionOption option : premiumPromo.period_options) { if (option.months == 12) { selectedOption = option; break; } else if (selectedOption == null && option.months == 1) { selectedOption = option; } } if (selectedOption == null) { return getString(R.string.SubscribeToPremiumNoPrice); } final String price; if (selectedOption.months == 12) { if (MessagesController.getInstance(currentAccount).showAnnualPerMonth) { price = BillingController.getInstance().formatCurrency(selectedOption.amount / 12, selectedOption.currency); } else { stringResId = R.string.SubscribeToPremiumPerYear; price = BillingController.getInstance().formatCurrency(selectedOption.amount, selectedOption.currency); } } else { price = BillingController.getInstance().formatCurrency(selectedOption.amount, selectedOption.currency); } return LocaleController.formatString(stringResId, price); } return getString(R.string.SubscribeToPremiumNoPrice); } String price = null; if (BillingController.PREMIUM_PRODUCT_DETAILS != null) { List<ProductDetails.SubscriptionOfferDetails> details = BillingController.PREMIUM_PRODUCT_DETAILS.getSubscriptionOfferDetails(); if (!details.isEmpty()) { ProductDetails.SubscriptionOfferDetails offerDetails = details.get(0); for (ProductDetails.PricingPhase phase : offerDetails.getPricingPhases().getPricingPhaseList()) { if (phase.getBillingPeriod().equals("P1M")) { // Once per month price = phase.getFormattedPrice(); } else if (phase.getBillingPeriod().equals("P1Y")) { // Once per year if (MessagesController.getInstance(currentAccount).showAnnualPerMonth) { price = BillingController.getInstance().formatCurrency(phase.getPriceAmountMicros() / 12L, phase.getPriceCurrencyCode(), 6); } else { stringResId = R.string.SubscribeToPremiumPerYear; price = BillingController.getInstance().formatCurrency(phase.getPriceAmountMicros(), phase.getPriceCurrencyCode(), 6); } break; } } } } if (price == null) { return getString(R.string.Loading); } return LocaleController.formatString(stringResId, price); } else { if (!BuildVars.useInvoiceBilling() && tier.getOfferDetails() == null) { return getString(R.string.Loading); } final boolean isPremium = UserConfig.getInstance(currentAccount).isPremium(); final boolean isYearTier = tier.getMonths() == 12; String price = isYearTier ? tier.getFormattedPricePerYear() : tier.getFormattedPricePerMonth(); final int resId; if (isPremium) { resId = isYearTier ? R.string.UpgradePremiumPerYear : R.string.UpgradePremiumPerMonth; } else { if (isYearTier) { if (MessagesController.getInstance(currentAccount).showAnnualPerMonth) { resId = R.string.SubscribeToPremium; price = tier.getFormattedPricePerMonth(); } else { resId = R.string.SubscribeToPremiumPerYear; price = tier.getFormattedPrice(); } } else { resId = R.string.SubscribeToPremium; price = tier.getFormattedPricePerMonth(); } } return LocaleController.formatString(resId, price); } } private void measureGradient(int w, int h) { int yOffset = 0; for (int i = 0; i < premiumFeatures.size(); i++) { dummyCell.setData(premiumFeatures.get(i), false); dummyCell.measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.AT_MOST)); premiumFeatures.get(i).yOffset = yOffset; yOffset += dummyCell.getMeasuredHeight(); } for (int i = 0; i < morePremiumFeatures.size(); i++) { dummyCell.setData(morePremiumFeatures.get(i), false); dummyCell.measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.AT_MOST)); morePremiumFeatures.get(i).yOffset = yOffset; yOffset += dummyCell.getMeasuredHeight(); } totalGradientHeight = yOffset; } private void updateRows() { rowCount = 0; sectionRow = -1; privacyRow = -1; moreHeaderRow = -1; moreFeaturesStartRow = -1; moreFeaturesEndRow = -1; showAdsHeaderRow = -1; showAdsRow = -1; showAdsInfoRow = -1; paddingRow = rowCount++; featuresStartRow = rowCount; rowCount += premiumFeatures.size(); featuresEndRow = rowCount; if (type == FEATURES_BUSINESS && getUserConfig().isPremium()) { sectionRow = rowCount++; moreHeaderRow = rowCount++; moreFeaturesStartRow = rowCount; rowCount += morePremiumFeatures.size(); moreFeaturesEndRow = rowCount; } statusRow = rowCount++; lastPaddingRow = rowCount++; if (type == FEATURES_BUSINESS && getUserConfig().isPremium()) { showAdsHeaderRow = rowCount++; showAdsRow = rowCount++; showAdsInfoRow = rowCount++; } AndroidUtilities.updateViewVisibilityAnimated(buttonContainer, !getUserConfig().isPremium() || currentSubscriptionTier != null && currentSubscriptionTier.getMonths() < subscriptionTiers.get(selectedTierIndex).getMonths() && !forcePremium, 1f, false); int buttonHeight = buttonContainer.getVisibility() == View.VISIBLE ? dp(64) : 0; layoutManager.setAdditionalHeight(buttonHeight + statusBarHeight - dp(16)); layoutManager.setMinimumLastViewHeight(buttonHeight); } @Override public boolean isSwipeBackEnabled(MotionEvent event) { return true; } @Override public boolean onFragmentCreate() { if (getMessagesController().premiumFeaturesBlocked()) { return false; } NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.billingProductDetailsUpdated); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.currentUserPremiumStatusChanged); getNotificationCenter().addObserver(this, NotificationCenter.premiumPromoUpdated); if (getMediaDataController().getPremiumPromo() != null) { for (TLRPC.Document document : getMediaDataController().getPremiumPromo().videos) { FileLoader.getInstance(currentAccount).loadFile(document, getMediaDataController().getPremiumPromo(), FileLoader.PRIORITY_HIGH, 0); } } if (type == FEATURES_BUSINESS) { TimezonesController.getInstance(currentAccount).load(); } return super.onFragmentCreate(); } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.billingProductDetailsUpdated); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.currentUserPremiumStatusChanged); getNotificationCenter().removeObserver(this, NotificationCenter.premiumPromoUpdated); } @SuppressLint("NotifyDataSetChanged") @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.billingProductDetailsUpdated || id == NotificationCenter.premiumPromoUpdated) { updateButtonText(false); backgroundView.updatePremiumTiers(); } if (id == NotificationCenter.currentUserPremiumStatusChanged || id == NotificationCenter.premiumPromoUpdated) { backgroundView.updateText(); backgroundView.updatePremiumTiers(); updateRows(); listView.getAdapter().notifyDataSetChanged(); } } private class Adapter extends RecyclerListView.SelectionAdapter { private final static int TYPE_PADDING = 0, TYPE_FEATURE = 1, TYPE_SHADOW_SECTION = 2, TYPE_BUTTON = 3, TYPE_HELP_US = 4, TYPE_SHADOW = 5, TYPE_BOTTOM_PADDING = 6, TYPE_HEADER = 7, TYPE_CHECK = 8; @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view; Context context = parent.getContext(); switch (viewType) { default: case TYPE_PADDING: view = new View(context) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (isLandscapeMode) { firstViewHeight = statusBarHeight + actionBar.getMeasuredHeight() - dp(16); } else { int h = dp(80) + statusBarHeight; if (backgroundView.getMeasuredHeight() + dp(24) > h) { h = backgroundView.getMeasuredHeight() + dp(24); } firstViewHeight = h; } super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(firstViewHeight, MeasureSpec.EXACTLY)); } }; break; case TYPE_SHADOW: view = new TextInfoPrivacyCell(context); break; case TYPE_FEATURE: view = new PremiumFeatureCell(context) { @Override protected void dispatchDraw(Canvas canvas) { AndroidUtilities.rectTmp.set(imageView.getLeft(), imageView.getTop(), imageView.getRight(), imageView.getBottom()); matrix.reset(); matrix.postScale(1f, totalGradientHeight / 100f, 0, 0); matrix.postTranslate(0, -data.yOffset); shader.setLocalMatrix(matrix); canvas.drawRoundRect(AndroidUtilities.rectTmp, dp(8), dp(8), gradientPaint); super.dispatchDraw(canvas); } }; break; case TYPE_SHADOW_SECTION: ShadowSectionCell shadowSectionCell = new ShadowSectionCell(context, 12, Theme.getColor(Theme.key_windowBackgroundGray)); Drawable shadowDrawable = Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.getColor(Theme.key_windowBackgroundGrayShadow)); Drawable background = new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)); CombinedDrawable combinedDrawable = new CombinedDrawable(background, shadowDrawable, 0, 0); combinedDrawable.setFullsize(true); shadowSectionCell.setBackgroundDrawable(combinedDrawable); view = shadowSectionCell; break; case TYPE_HELP_US: view = new AboutPremiumView(context); break; case TYPE_BOTTOM_PADDING: view = new View(context); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray)); break; case TYPE_HEADER: view = new HeaderCell(context); break; case TYPE_CHECK: view = new TextCell(context, 23, false, true, resourceProvider); break; } view.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); return new RecyclerListView.Holder(view); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { if (position >= featuresStartRow && position < featuresEndRow) { ((PremiumFeatureCell) holder.itemView).setData(premiumFeatures.get(position - featuresStartRow), position != featuresEndRow - 1); } else if (position >= moreFeaturesStartRow && position < moreFeaturesEndRow) { ((PremiumFeatureCell) holder.itemView).setData(morePremiumFeatures.get(position - moreFeaturesStartRow), position != moreFeaturesEndRow - 1); } else if (position == sectionRow) { TextInfoPrivacyCell privacyCell = (TextInfoPrivacyCell) holder.itemView; Drawable shadowDrawable = Theme.getThemedDrawable(privacyCell.getContext(), R.drawable.greydivider, Theme.getColor(Theme.key_windowBackgroundGrayShadow)); Drawable background = new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)); CombinedDrawable combinedDrawable = new CombinedDrawable(background, shadowDrawable, 0, 0); combinedDrawable.setFullsize(true); privacyCell.setBackground(combinedDrawable); privacyCell.setText(""); privacyCell.setFixedSize(12); } else if (position == statusRow || position == privacyRow || position == showAdsInfoRow) { TextInfoPrivacyCell privacyCell = (TextInfoPrivacyCell) holder.itemView; Drawable shadowDrawable = Theme.getThemedDrawable(privacyCell.getContext(), R.drawable.greydivider, Theme.getColor(Theme.key_windowBackgroundGrayShadow)); Drawable background = new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)); CombinedDrawable combinedDrawable = new CombinedDrawable(background, shadowDrawable, 0, 0); combinedDrawable.setFullsize(true); privacyCell.setBackground(combinedDrawable); privacyCell.setFixedSize(0); if (position == showAdsInfoRow) { privacyCell.setText(AndroidUtilities.replaceArrows(AndroidUtilities.replaceSingleTag(getString(R.string.ShowAdsInfo), () -> { showDialog(new RevenueSharingAdsInfoBottomSheet(PremiumPreviewFragment.this, getContext(), getResourceProvider())); }), true)); } else if (position == statusRow && type == FEATURES_BUSINESS) { privacyCell.setText(getString(R.string.PremiumPreviewMoreBusinessFeaturesInfo)); } else if (position == statusRow) { TLRPC.TL_help_premiumPromo premiumPromo = getMediaDataController().getPremiumPromo(); if (premiumPromo == null) { return; } SpannableString spannableString = new SpannableString(premiumPromo.status_text); MediaDataController.addTextStyleRuns(premiumPromo.status_entities, premiumPromo.status_text, spannableString); byte t = 0; for (TextStyleSpan span : spannableString.getSpans(0, spannableString.length(), TextStyleSpan.class)) { TextStyleSpan.TextStyleRun run = span.getTextStyleRun(); boolean setRun = false; String url = run.urlEntity != null ? TextUtils.substring(premiumPromo.status_text, run.urlEntity.offset, run.urlEntity.offset + run.urlEntity.length) : null; if (run.urlEntity instanceof TLRPC.TL_messageEntityBotCommand) { spannableString.setSpan(new URLSpanBotCommand(url, t, run), run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (run.urlEntity instanceof TLRPC.TL_messageEntityHashtag || run.urlEntity instanceof TLRPC.TL_messageEntityMention || run.urlEntity instanceof TLRPC.TL_messageEntityCashtag) { spannableString.setSpan(new URLSpanNoUnderline(url, run), run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (run.urlEntity instanceof TLRPC.TL_messageEntityEmail) { spannableString.setSpan(new URLSpanReplacement("mailto:" + url, run), run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (run.urlEntity instanceof TLRPC.TL_messageEntityUrl) { String lowerCase = url.toLowerCase(); if (!lowerCase.contains("://")) { spannableString.setSpan(new URLSpanBrowser("http://" + url, run), run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { spannableString.setSpan(new URLSpanBrowser(url, run), run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } else if (run.urlEntity instanceof TLRPC.TL_messageEntityBankCard) { spannableString.setSpan(new URLSpanNoUnderline("card:" + url, run), run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (run.urlEntity instanceof TLRPC.TL_messageEntityPhone) { String tel = PhoneFormat.stripExceptNumbers(url); if (url.startsWith("+")) { tel = "+" + tel; } spannableString.setSpan(new URLSpanBrowser("tel:" + tel, run), run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (run.urlEntity instanceof TLRPC.TL_messageEntityTextUrl) { URLSpanReplacement spanReplacement = new URLSpanReplacement(run.urlEntity.url, run); spanReplacement.setNavigateToPremiumBot(true); spannableString.setSpan(spanReplacement, run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (run.urlEntity instanceof TLRPC.TL_messageEntityMentionName) { spannableString.setSpan(new URLSpanUserMention("" + ((TLRPC.TL_messageEntityMentionName) run.urlEntity).user_id, t, run), run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (run.urlEntity instanceof TLRPC.TL_inputMessageEntityMentionName) { spannableString.setSpan(new URLSpanUserMention("" + ((TLRPC.TL_inputMessageEntityMentionName) run.urlEntity).user_id.user_id, t, run), run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else if ((run.flags & TextStyleSpan.FLAG_STYLE_MONO) != 0) { spannableString.setSpan(new URLSpanMono(spannableString, run.start, run.end, t, run), run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { setRun = true; spannableString.setSpan(new TextStyleSpan(run), run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } if (!setRun && (run.flags & TextStyleSpan.FLAG_STYLE_SPOILER) != 0) { spannableString.setSpan(new TextStyleSpan(run), run.start, run.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } privacyCell.setText(spannableString); } } else if (position == moreHeaderRow) { ((HeaderCell) holder.itemView).setText(getString(R.string.PremiumPreviewMoreBusinessFeatures)); } else if (position == showAdsHeaderRow) { ((HeaderCell) holder.itemView).setText(getString(R.string.ShowAdsTitle)); } else if (position == showAdsRow) { TLRPC.UserFull userFull = getMessagesController().getUserFull(getUserConfig().getClientUserId()); ((TextCell) holder.itemView).setTextAndCheck(getString(R.string.ShowAds), userFull == null || userFull.sponsored_enabled, false); } } @Override public int getItemCount() { return rowCount; } @Override public int getItemViewType(int position) { if (position == paddingRow) { return TYPE_PADDING; } else if (position >= featuresStartRow && position < featuresEndRow || position >= moreFeaturesStartRow && position < moreFeaturesEndRow) { return TYPE_FEATURE; } else if (position == helpUsRow) { return TYPE_HELP_US; } else if (position == sectionRow || position == statusRow || position == privacyRow || position == showAdsInfoRow) { return TYPE_SHADOW; } else if (position == lastPaddingRow) { return TYPE_BOTTOM_PADDING; } else if (position == moreHeaderRow || position == showAdsHeaderRow) { return TYPE_HEADER; } else if (position == showAdsRow) { return TYPE_CHECK; } return TYPE_PADDING; } @Override public boolean isEnabled(RecyclerView.ViewHolder holder) { return holder.getItemViewType() == TYPE_FEATURE || holder.getItemViewType() == TYPE_CHECK; } } public static class PremiumFeatureData { public final int type; public final int icon; public final CharSequence title; public final String description; public int yOffset; public PremiumFeatureData(int type, int icon, CharSequence title, String description) { this.type = type; this.icon = icon; this.title = title; this.description = description; } } FrameLayout settingsView; private class BackgroundView extends LinearLayout { TextView titleView; private final TextView subtitleView; private final FrameLayout imageFrameLayout; private final GLIconTextureView imageView; private RecyclerListView tierListView; public BackgroundView(Context context) { super(context); setOrientation(VERTICAL); imageFrameLayout = new FrameLayout(context); final int sz = type == FEATURES_BUSINESS ? 175 : 190; addView(imageFrameLayout, LayoutHelper.createLinear(sz, sz, Gravity.CENTER_HORIZONTAL)); imageView = new GLIconTextureView(context, whiteBackground ? GLIconRenderer.DIALOG_STYLE : type == FEATURES_BUSINESS ? GLIconRenderer.BUSINESS_STYLE : GLIconRenderer.FRAGMENT_STYLE, type == FEATURES_BUSINESS ? Icon3D.TYPE_COIN : Icon3D.TYPE_STAR) { @Override public void onLongPress() { super.onLongPress(); if (settingsView != null || !BuildVars.DEBUG_PRIVATE_VERSION) { return; } settingsView = new FrameLayout(context); ScrollView scrollView = new ScrollView(context); LinearLayout linearLayout = new GLIconSettingsView(context, imageView.mRenderer); scrollView.addView(linearLayout); settingsView.addView(scrollView); settingsView.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); contentView.addView(settingsView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.BOTTOM)); ((MarginLayoutParams) settingsView.getLayoutParams()).topMargin = currentYOffset; settingsView.setTranslationY(dp(1000)); settingsView.animate().translationY(1).setDuration(300); } }; imageFrameLayout.addView(imageView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); imageFrameLayout.setClipChildren(false); setClipChildren(false); titleView = new TextView(context); titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 22); titleView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); titleView.setGravity(Gravity.CENTER_HORIZONTAL); addView(titleView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, 0, Gravity.CENTER_HORIZONTAL, 16, type == FEATURES_BUSINESS ? 8 : 20, 16, 0)); subtitleView = new TextView(context); subtitleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); subtitleView.setLineSpacing(dp(2), 1f); subtitleView.setGravity(Gravity.CENTER_HORIZONTAL); addView(subtitleView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, Gravity.CENTER_HORIZONTAL, 16, 7, 16, 0)); tierListView = new RecyclerListView(context) { Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); { paint.setColor(Theme.getColor(Theme.key_dialogBackground)); if (whiteBackground) { paint.setShadowLayer(dp(2), 0, dp(.66f), 0x30000000); } } private Path path = new Path(); @Override public void dispatchDraw(Canvas c) { path.rewind(); AndroidUtilities.rectTmp.set(0, 0, getWidth(), getHeight()); path.addRoundRect(AndroidUtilities.rectTmp, dp(12), dp(12), Path.Direction.CW); c.drawPath(path, paint); c.save(); c.clipPath(path); super.dispatchDraw(c); c.restore(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); measureGradient(w, h); } @Override public boolean onInterceptTouchEvent(MotionEvent e) { if (progressToFull >= 1.0f) { return false; } return super.onInterceptTouchEvent(e); } @Override public boolean dispatchTouchEvent(MotionEvent e) { if (progressToFull >= 1.0f) { return false; } return super.dispatchTouchEvent(e); } }; tierListView.setOverScrollMode(OVER_SCROLL_NEVER); tierListView.setLayoutManager(new LinearLayoutManager(context)); tierListView.setAdapter(new RecyclerListView.SelectionAdapter() { @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { PremiumTierCell premiumTierCell = new PremiumTierCell(context) { @Override protected void dispatchDraw(Canvas canvas) { if (discountView.getVisibility() == VISIBLE) { AndroidUtilities.rectTmp.set(discountView.getLeft(), discountView.getTop(), discountView.getRight(), discountView.getBottom()); tiersGradientTools.gradientMatrix(0, 0, getMeasuredWidth(), totalTiersGradientHeight, 0, -tier.yOffset); canvas.drawRoundRect(AndroidUtilities.rectTmp, dp(6), dp(6), tiersGradientTools.paint); } super.dispatchDraw(canvas); } }; premiumTierCell.setCirclePaintProvider(obj -> { tiersGradientTools.gradientMatrix(0, 0, premiumTierCell.getMeasuredWidth(), totalTiersGradientHeight, 0, -premiumTierCell.getTier().yOffset); return tiersGradientTools.paint; }); return new RecyclerListView.Holder(premiumTierCell); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { PremiumTierCell premiumTier = (PremiumTierCell) holder.itemView; premiumTier.bind(subscriptionTiers.get(position), position != getItemCount() - 1); premiumTier.setChecked(selectedTierIndex == position, false); } @Override public boolean isEnabled(RecyclerView.ViewHolder holder) { return !subscriptionTiers.get(holder.getAdapterPosition()).subscriptionOption.current; } @Override public int getItemCount() { return subscriptionTiers.size(); } }); tierListView.setOnItemClickListener((view, position) -> { if (!view.isEnabled()) { return; } if (view instanceof PremiumTierCell) { PremiumTierCell tierCell = (PremiumTierCell) view; selectedTierIndex = subscriptionTiers.indexOf(tierCell.getTier()); updateButtonText(true); tierCell.setChecked(true, true); for (int i = 0; i < tierListView.getChildCount(); i++) { View ch = tierListView.getChildAt(i); if (ch instanceof PremiumTierCell) { PremiumTierCell otherCell = (PremiumTierCell) ch; if (otherCell.getTier() != tierCell.getTier()) { otherCell.setChecked(false, true); } } } for (int i = 0; i < tierListView.getHiddenChildCount(); i++) { View ch = tierListView.getHiddenChildAt(i); if (ch instanceof PremiumTierCell) { PremiumTierCell otherCell = (PremiumTierCell) ch; if (otherCell.getTier() != tierCell.getTier()) { otherCell.setChecked(false, true); } } } for (int i = 0; i < tierListView.getCachedChildCount(); i++) { View ch = tierListView.getCachedChildAt(i); if (ch instanceof PremiumTierCell) { PremiumTierCell otherCell = (PremiumTierCell) ch; if (otherCell.getTier() != tierCell.getTier()) { otherCell.setChecked(false, true); } } } for (int i = 0; i < tierListView.getAttachedScrapChildCount(); i++) { View ch = tierListView.getAttachedScrapChildAt(i); if (ch instanceof PremiumTierCell) { PremiumTierCell otherCell = (PremiumTierCell) ch; if (otherCell.getTier() != tierCell.getTier()) { otherCell.setChecked(false, true); } } } AndroidUtilities.updateViewVisibilityAnimated(buttonContainer, !getUserConfig().isPremium() || currentSubscriptionTier != null && currentSubscriptionTier.getMonths() < subscriptionTiers.get(selectedTierIndex).getMonths() && !forcePremium); } }); Path path = new Path(); float[] radii = new float[8]; tierListView.setSelectorTransformer(canvas -> { View child = tierListView.getPressedChildView(); int position = child == null ? -1 : tierListView.getChildViewHolder(child).getAdapterPosition(); path.rewind(); Rect selectorRect = tierListView.getSelectorRect(); AndroidUtilities.rectTmp.set(selectorRect.left, selectorRect.top, selectorRect.right, selectorRect.bottom); Arrays.fill(radii, 0); if (position == 0) { Arrays.fill(radii, 0, 4, dp(12)); } if (position == tierListView.getAdapter().getItemCount() - 1) { Arrays.fill(radii, 4, 8, dp(12)); } path.addRoundRect(AndroidUtilities.rectTmp, radii, Path.Direction.CW); canvas.clipPath(path); }); setClipChildren(false); setClipToPadding(false); addView(tierListView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 12, 16, 12, 4)); updatePremiumTiers(); updateText(); } private void measureGradient(int w, int h) { int yOffset = 0; for (int i = 0; i < subscriptionTiers.size(); i++) { dummyTierCell.bind(subscriptionTiers.get(i), false); dummyTierCell.measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.AT_MOST)); subscriptionTiers.get(i).yOffset = yOffset; yOffset += dummyTierCell.getMeasuredHeight(); } totalTiersGradientHeight = yOffset; } @SuppressLint("NotifyDataSetChanged") public void updatePremiumTiers() { subscriptionTiers.clear(); selectedTierIndex = -1; currentSubscriptionTier = null; long pricePerYearMax = 0; if (getMediaDataController().getPremiumPromo() != null) { for (TLRPC.TL_premiumSubscriptionOption option : getMediaDataController().getPremiumPromo().period_options) { if (getUserConfig().isPremium() && !option.can_purchase_upgrade && !option.current) { continue; } SubscriptionTier subscriptionTier = new SubscriptionTier(option); subscriptionTiers.add(subscriptionTier); if (selectAnnualByDefault) { if (option.months == 12) { selectedTierIndex = subscriptionTiers.size() - 1; } } if (option.current) { currentSubscriptionTier = subscriptionTier; } if (BuildVars.useInvoiceBilling()) { if (subscriptionTier.getPricePerYear() > pricePerYearMax) { pricePerYearMax = subscriptionTier.getPricePerYear(); } } } } if (BuildVars.useInvoiceBilling() && getUserConfig().isPremium()) { subscriptionTiers.clear(); currentSubscriptionTier = null; } else if (!BuildVars.useInvoiceBilling() && currentSubscriptionTier != null && !Objects.equals(BillingController.getInstance().getLastPremiumTransaction(), currentSubscriptionTier.subscriptionOption != null ? currentSubscriptionTier.subscriptionOption.transaction != null ? currentSubscriptionTier.subscriptionOption.transaction.replaceAll(TRANSACTION_PATTERN, "$1") : null : null) || currentSubscriptionTier != null && currentSubscriptionTier.getMonths() == 12) { subscriptionTiers.clear(); currentSubscriptionTier = null; } if (BuildVars.useInvoiceBilling()) { for (SubscriptionTier tier : subscriptionTiers) { tier.setPricePerYearRegular(pricePerYearMax); } } else if (BillingController.getInstance().isReady() && BillingController.PREMIUM_PRODUCT_DETAILS != null) { long pricePerMonthMaxStore = 0; for (SubscriptionTier subscriptionTier : subscriptionTiers) { subscriptionTier.setGooglePlayProductDetails(BillingController.PREMIUM_PRODUCT_DETAILS); if (subscriptionTier.getPricePerYear() > pricePerMonthMaxStore) { pricePerMonthMaxStore = subscriptionTier.getPricePerYear(); } } for (SubscriptionTier subscriptionTier : subscriptionTiers) { subscriptionTier.setPricePerYearRegular(pricePerMonthMaxStore); } } if (selectedTierIndex == -1) { for (int i = 0; i < subscriptionTiers.size(); i++) { SubscriptionTier tier = subscriptionTiers.get(i); if (tier.getMonths() == 12) { selectedTierIndex = i; break; } } if (selectedTierIndex == -1) { selectedTierIndex = 0; } } updateButtonText(false); tierListView.getAdapter().notifyDataSetChanged(); } private boolean setTierListViewVisibility; private boolean tierListViewVisible; public void updateText() { if (type == FEATURES_PREMIUM) { titleView.setText(getString(forcePremium ? R.string.TelegramPremiumSubscribedTitle : R.string.TelegramPremium)); subtitleView.setText(AndroidUtilities.replaceTags(getString(getUserConfig().isPremium() || forcePremium ? R.string.TelegramPremiumSubscribedSubtitle : R.string.TelegramPremiumSubtitle))); } else if (type == FEATURES_BUSINESS) { titleView.setText(getString(forcePremium ? R.string.TelegramPremiumSubscribedTitle : R.string.TelegramBusiness)); subtitleView.setText(AndroidUtilities.replaceTags(getString(getUserConfig().isPremium() || forcePremium ? R.string.TelegramBusinessSubscribedSubtitleTemp : R.string.TelegramBusinessSubtitleTemp))); } subtitleView.getLayoutParams().width = Math.min(AndroidUtilities.displaySize.x - dp(42), HintView2.cutInFancyHalf(subtitleView.getText(), subtitleView.getPaint())); boolean tierNotVisible = forcePremium || BuildVars.IS_BILLING_UNAVAILABLE || IS_PREMIUM_TIERS_UNAVAILABLE || subscriptionTiers.size() <= 1; if (!setTierListViewVisibility || !tierNotVisible) { tierListView.setVisibility(tierNotVisible ? GONE : VISIBLE); setTierListViewVisibility = true; } else if (tierListView.getVisibility() == VISIBLE && tierNotVisible && tierListViewVisible == tierNotVisible) { View v = tierListView; ValueAnimator animator = ValueAnimator.ofFloat(1, 0).setDuration(250); animator.addUpdateListener(animation -> { float val = (float) animation.getAnimatedValue(); v.setAlpha(val); v.setScaleX(val); v.setScaleY(val); float f = animator.getAnimatedFraction(); for (int i = 0; i < backgroundView.getChildCount(); i++) { View ch = backgroundView.getChildAt(i); if (ch != tierListView) { float offset = 0; if (ch == imageFrameLayout) { offset -= dp(15) * f; } else { offset += dp(8) * f; } ch.setTranslationY(f * v.getMeasuredHeight() + offset); } } }); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { v.setVisibility(GONE); for (int i = 0; i < backgroundView.getChildCount(); i++) { View ch = backgroundView.getChildAt(i); if (ch != tierListView) { ch.setTranslationY(0); } } } }); animator.setInterpolator(CubicBezierInterpolator.DEFAULT); animator.start(); } tierListViewVisible = !tierNotVisible; } } private void updateButtonText(boolean animated) { if (premiumButtonView == null || getUserConfig().isPremium() && currentSubscriptionTier != null && subscriptionTiers.get(selectedTierIndex).getMonths() < currentSubscriptionTier.getMonths()) { return; } if (LocaleController.isRTL) { animated = false; } if (BuildVars.IS_BILLING_UNAVAILABLE) { premiumButtonView.setButton(getPremiumButtonText(currentAccount, subscriptionTiers.get(selectedTierIndex)), v -> buyPremium(this), animated); return; } if (!BuildVars.useInvoiceBilling() && (!BillingController.getInstance().isReady() || subscriptionTiers.isEmpty() || selectedTierIndex >= subscriptionTiers.size() || subscriptionTiers.get(selectedTierIndex).googlePlayProductDetails == null)) { premiumButtonView.setButton(getString(R.string.Loading), v -> {}, animated); premiumButtonView.setFlickerDisabled(true); return; } if (!subscriptionTiers.isEmpty()) { premiumButtonView.setButton(getPremiumButtonText(currentAccount, subscriptionTiers.get(selectedTierIndex)), v -> { SubscriptionTier tier = subscriptionTiers.get(selectedTierIndex); BillingFlowParams.SubscriptionUpdateParams updateParams = null; if (currentSubscriptionTier != null && currentSubscriptionTier.subscriptionOption != null && currentSubscriptionTier.subscriptionOption.transaction != null) { updateParams = BillingFlowParams.SubscriptionUpdateParams.newBuilder() .setOldPurchaseToken(BillingController.getInstance().getLastPremiumToken()) .setReplaceProrationMode(BillingFlowParams.ProrationMode.IMMEDIATE_AND_CHARGE_FULL_PRICE) .build(); } buyPremium(this, tier, "settings", true, updateParams); }, animated); premiumButtonView.setFlickerDisabled(false); } } @Override public boolean isLightStatusBar() { return whiteBackground; } @Override public void onResume() { super.onResume(); if (backgroundView != null && backgroundView.imageView != null) { backgroundView.imageView.setPaused(false); backgroundView.imageView.setDialogVisible(false); } particlesView.setPaused(false); } @Override public void onPause() { super.onPause(); if (backgroundView != null && backgroundView.imageView != null) { backgroundView.imageView.setDialogVisible(true); } if (particlesView != null) { particlesView.setPaused(true); } } @Override public boolean canBeginSlide() { return backgroundView == null || backgroundView.imageView == null || !backgroundView.imageView.touched; } @Override public ArrayList<ThemeDescription> getThemeDescriptions() { return SimpleThemeDescription.createThemeDescriptions(this::updateColors, Theme.key_premiumGradient1, Theme.key_premiumGradient2, Theme.key_premiumGradient3, Theme.key_premiumGradient4, Theme.key_premiumGradientBackground1, Theme.key_premiumGradientBackground2, Theme.key_premiumGradientBackground3, Theme.key_premiumGradientBackground4, Theme.key_premiumGradientBackgroundOverlay, Theme.key_premiumStarGradient1, Theme.key_premiumStarGradient2, Theme.key_premiumStartSmallStarsColor, Theme.key_premiumStartSmallStarsColor2 ); } private void updateColors() { if (backgroundView == null || actionBar == null) { return; } actionBar.setItemsColor(Theme.getColor(whiteBackground ? Theme.key_windowBackgroundWhiteBlackText : Theme.key_premiumGradientBackgroundOverlay), false); actionBar.setItemsColor(Theme.getColor(whiteBackground ? Theme.key_windowBackgroundWhiteBlackText : Theme.key_premiumGradientBackgroundOverlay), true); actionBar.setItemsBackgroundColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_premiumGradientBackgroundOverlay), 60), false); particlesView.drawable.updateColors(); if (backgroundView != null) { backgroundView.titleView.setTextColor(Theme.getColor(whiteBackground ? Theme.key_windowBackgroundWhiteBlackText : Theme.key_premiumGradientBackgroundOverlay)); backgroundView.subtitleView.setTextColor(Theme.getColor(whiteBackground ? Theme.key_windowBackgroundWhiteBlackText : Theme.key_premiumGradientBackgroundOverlay)); if (backgroundView.imageView != null && backgroundView.imageView.mRenderer != null) { if (whiteBackground) { // backgroundView.imageView.mRenderer.forceNight = true; backgroundView.imageView.mRenderer.colorKey1 = Theme.key_premiumCoinGradient1; backgroundView.imageView.mRenderer.colorKey2 = Theme.key_premiumCoinGradient2; } backgroundView.imageView.mRenderer.updateColors(); } } updateBackgroundImage(); } @Override public boolean onBackPressed() { if (settingsView != null) { closeSetting(); return false; } return super.onBackPressed(); } private void closeSetting() { settingsView.animate().translationY(dp(1000)).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { contentView.removeView(settingsView); settingsView = null; super.onAnimationEnd(animation); } }); } @Override public Dialog showDialog(Dialog dialog) { Dialog d = super.showDialog(dialog); updateDialogVisibility(d != null); return d; } @Override protected void onDialogDismiss(Dialog dialog) { super.onDialogDismiss(dialog); updateDialogVisibility(false); } private void updateDialogVisibility(boolean isVisible) { if (isVisible != isDialogVisible) { isDialogVisible = isVisible; if (backgroundView != null && backgroundView.imageView != null) { backgroundView.imageView.setDialogVisible(isVisible); } particlesView.setPaused(isVisible); contentView.invalidate(); } } private void sentShowScreenStat() { if (source == null) { return; } sentShowScreenStat(source); source = null; } public static void sentShowScreenStat(String source) { ConnectionsManager connectionsManager = ConnectionsManager.getInstance(UserConfig.selectedAccount); TLRPC.TL_help_saveAppLog req = new TLRPC.TL_help_saveAppLog(); TLRPC.TL_inputAppEvent event = new TLRPC.TL_inputAppEvent(); event.time = connectionsManager.getCurrentTime(); event.type = "premium.promo_screen_show"; TLRPC.TL_jsonObject data = new TLRPC.TL_jsonObject(); event.data = data; TLRPC.TL_jsonObjectValue sourceObj = new TLRPC.TL_jsonObjectValue(); TLRPC.JSONValue sourceVal; if (source != null) { TLRPC.TL_jsonString jsonString = new TLRPC.TL_jsonString(); jsonString.value = source; sourceVal = jsonString; } else { sourceVal = new TLRPC.TL_jsonNull(); } sourceObj.key = "source"; sourceObj.value = sourceVal; data.value.add(sourceObj); req.events.add(event); connectionsManager.sendRequest(req, (response, error) -> { }); } public static void sentPremiumButtonClick() { TLRPC.TL_help_saveAppLog req = new TLRPC.TL_help_saveAppLog(); TLRPC.TL_inputAppEvent event = new TLRPC.TL_inputAppEvent(); event.time = ConnectionsManager.getInstance(UserConfig.selectedAccount).getCurrentTime(); event.type = "premium.promo_screen_accept"; event.data = new TLRPC.TL_jsonNull(); req.events.add(event); ConnectionsManager.getInstance(UserConfig.selectedAccount).sendRequest(req, (response, error) -> { }); } public static void sentPremiumBuyCanceled() { TLRPC.TL_help_saveAppLog req = new TLRPC.TL_help_saveAppLog(); TLRPC.TL_inputAppEvent event = new TLRPC.TL_inputAppEvent(); event.time = ConnectionsManager.getInstance(UserConfig.selectedAccount).getCurrentTime(); event.type = "premium.promo_screen_fail"; event.data = new TLRPC.TL_jsonNull(); req.events.add(event); ConnectionsManager.getInstance(UserConfig.selectedAccount).sendRequest(req, (response, error) -> { }); } public static void sentShowFeaturePreview(int currentAccount, int type) { TLRPC.TL_help_saveAppLog req = new TLRPC.TL_help_saveAppLog(); TLRPC.TL_inputAppEvent event = new TLRPC.TL_inputAppEvent(); event.time = ConnectionsManager.getInstance(currentAccount).getCurrentTime(); event.type = "premium.promo_screen_tap"; TLRPC.TL_jsonObject data = new TLRPC.TL_jsonObject(); event.data = data; TLRPC.TL_jsonObjectValue item = new TLRPC.TL_jsonObjectValue(); String value = PremiumPreviewFragment.featureTypeToServerString(type); if (value != null) { TLRPC.TL_jsonString jsonString = new TLRPC.TL_jsonString(); jsonString.value = value; item.value = jsonString; } else { item.value = new TLRPC.TL_jsonNull(); } item.key = "item"; data.value.add(item); req.events.add(event); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { }); } public final static class SubscriptionTier { public final TLRPC.TL_premiumSubscriptionOption subscriptionOption; private int discount; private long pricePerMonth; private long pricePerYear; private long pricePerYearRegular; private ProductDetails googlePlayProductDetails; private ProductDetails.SubscriptionOfferDetails offerDetails; public int yOffset; public SubscriptionTier(TLRPC.TL_premiumSubscriptionOption subscriptionOption) { this.subscriptionOption = subscriptionOption; } public ProductDetails getGooglePlayProductDetails() { return googlePlayProductDetails; } public ProductDetails.SubscriptionOfferDetails getOfferDetails() { checkOfferDetails(); return offerDetails; } public void setGooglePlayProductDetails(ProductDetails googlePlayProductDetails) { this.googlePlayProductDetails = googlePlayProductDetails; } public void setPricePerYearRegular(long pricePerYearRegular) { this.pricePerYearRegular = pricePerYearRegular; } public int getMonths() { return subscriptionOption.months; } public int getDiscount() { if (discount == 0) { if (getPricePerMonth() == 0) { return 0; } if (pricePerYearRegular != 0) { discount = (int) ((1.0 - getPricePerYear() / (double) pricePerYearRegular) * 100); if (discount == 0) { discount = -1; } } } return discount; } public long getPricePerYear() { if (pricePerYear == 0) { long price = getPrice(); if (price != 0) { pricePerYear = (long) ((double) price / subscriptionOption.months * 12); } } return pricePerYear; } public long getPricePerMonth() { if (pricePerMonth == 0) { long price = getPrice(); if (price != 0) { pricePerMonth = price / subscriptionOption.months; } } return pricePerMonth; } public String getFormattedPricePerYearRegular() { if (BuildVars.useInvoiceBilling() || subscriptionOption.store_product == null) { return BillingController.getInstance().formatCurrency(pricePerYearRegular, getCurrency()); } return googlePlayProductDetails == null ? "" : BillingController.getInstance().formatCurrency(pricePerYearRegular, getCurrency(), 6); } public String getFormattedPricePerYear() { if (BuildVars.useInvoiceBilling() || subscriptionOption.store_product == null) { return BillingController.getInstance().formatCurrency(getPricePerYear(), getCurrency()); } return googlePlayProductDetails == null ? "" : BillingController.getInstance().formatCurrency(getPricePerYear(), getCurrency(), 6); } public String getFormattedPricePerMonth() { if (BuildVars.useInvoiceBilling() || subscriptionOption.store_product == null) { return BillingController.getInstance().formatCurrency(getPricePerMonth(), getCurrency()); } return googlePlayProductDetails == null ? "" : BillingController.getInstance().formatCurrency(getPricePerMonth(), getCurrency(), 6); } public String getFormattedPrice() { if (BuildVars.useInvoiceBilling() || subscriptionOption.store_product == null) { return BillingController.getInstance().formatCurrency(getPrice(), getCurrency()); } return googlePlayProductDetails == null ? "" : BillingController.getInstance().formatCurrency(getPrice(), getCurrency(), 6); } public long getPrice() { if (BuildVars.useInvoiceBilling() || subscriptionOption.store_product == null) { return subscriptionOption.amount; } if (googlePlayProductDetails == null) { return 0; } checkOfferDetails(); return offerDetails == null ? 0 : offerDetails.getPricingPhases().getPricingPhaseList().get(0).getPriceAmountMicros(); } public String getCurrency() { if (BuildVars.useInvoiceBilling() || subscriptionOption.store_product == null) { return subscriptionOption.currency; } if (googlePlayProductDetails == null) { return ""; } checkOfferDetails(); return offerDetails == null ? "" : offerDetails.getPricingPhases().getPricingPhaseList().get(0).getPriceCurrencyCode(); } private void checkOfferDetails() { if (googlePlayProductDetails == null) { return; } if (offerDetails == null) { for (ProductDetails.SubscriptionOfferDetails details : googlePlayProductDetails.getSubscriptionOfferDetails()) { String period = details.getPricingPhases().getPricingPhaseList().get(0).getBillingPeriod(); if (getMonths() == 12 ? period.equals("P1Y") : period.equals(String.format(Locale.ROOT, "P%dM", getMonths()))) { offerDetails = details; break; } } } } } private SelectAnimatedEmojiDialog.SelectAnimatedEmojiDialogWindow selectAnimatedEmojiDialog; public void showSelectStatusDialog(PremiumFeatureCell cell, Long documentId, Utilities.Callback2<Long, Integer> onSet) { if (selectAnimatedEmojiDialog != null || cell == null) { return; } final SelectAnimatedEmojiDialog.SelectAnimatedEmojiDialogWindow[] popup = new SelectAnimatedEmojiDialog.SelectAnimatedEmojiDialogWindow[1]; int xoff = 0, yoff = 0; final boolean down = cell.getTop() + cell.getHeight() > listView.getMeasuredHeight() / 2f; AnimatedEmojiDrawable.SwapAnimatedEmojiDrawable scrimDrawable = null; View scrimDrawableParent = null; final int popupHeight = (int) Math.min(AndroidUtilities.dp(410 - 16 - 64), AndroidUtilities.displaySize.y * .75f); final int popupWidth = (int) Math.min(dp(340 - 16), AndroidUtilities.displaySize.x * .95f); if (cell != null && cell.imageDrawable != null) { cell.imageDrawable.removeOldDrawable(); scrimDrawable = cell.imageDrawable; scrimDrawableParent = cell; if (cell.imageDrawable != null) { cell.imageDrawable.play(); cell.updateImageBounds(); AndroidUtilities.rectTmp2.set(cell.imageDrawable.getBounds()); if (down) { yoff = -AndroidUtilities.rectTmp2.centerY() + dp(12) - popupHeight; } else { yoff = -(cell.getHeight() - AndroidUtilities.rectTmp2.centerY()) - AndroidUtilities.dp(16); } xoff = AndroidUtilities.rectTmp2.centerX() - (AndroidUtilities.displaySize.x - popupWidth); } } int type = down ? SelectAnimatedEmojiDialog.TYPE_EMOJI_STATUS_TOP : SelectAnimatedEmojiDialog.TYPE_EMOJI_STATUS; SelectAnimatedEmojiDialog popupLayout = new SelectAnimatedEmojiDialog(PremiumPreviewFragment.this, getContext(), true, xoff, type, true, getResourceProvider(), down ? 24 : 16) { @Override protected void onEmojiSelected(View emojiView, Long documentId, TLRPC.Document document, Integer until) { if (onSet != null) { onSet.run(documentId, until); } if (popup[0] != null) { selectAnimatedEmojiDialog = null; popup[0].dismiss(); } } @Override protected float getScrimDrawableTranslationY() { return 0; } }; popupLayout.useAccentForPlus = true; popupLayout.setSelected(documentId); popupLayout.setSaveState(3); popupLayout.setScrimDrawable(scrimDrawable, scrimDrawableParent); popup[0] = selectAnimatedEmojiDialog = new SelectAnimatedEmojiDialog.SelectAnimatedEmojiDialogWindow(popupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) { @Override public void dismiss() { super.dismiss(); selectAnimatedEmojiDialog = null; } }; popup[0].showAsDropDown(cell, 0, yoff, Gravity.TOP | Gravity.RIGHT); popup[0].dimBehind(); } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/PremiumPreviewFragment.java
2,177
/* * Copyright 2015 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.graphics.Canvas; import android.graphics.Rect; import android.graphics.SurfaceTexture; import androidx.annotation.Nullable; import android.view.Surface; import android.view.SurfaceHolder; 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; /** * Holds EGL state and utility methods for handling an egl 1.0 EGLContext, an EGLDisplay, * and an EGLSurface. */ class EglBase10Impl implements EglBase10 { private static final String TAG = "EglBase10Impl"; // This constant is taken from EGL14.EGL_CONTEXT_CLIENT_VERSION. private static final int EGL_CONTEXT_CLIENT_VERSION = 0x3098; private final EGL10 egl; private EGLContext eglContext; @Nullable private EGLConfig eglConfig; private EGLDisplay eglDisplay; private EGLSurface eglSurface = EGL10.EGL_NO_SURFACE; private EGLSurface eglBackgroundSurface = EGL10.EGL_NO_SURFACE; // EGL wrapper for an actual EGLContext. private static class Context implements EglBase10.Context { private final EGL10 egl; private final EGLContext eglContext; private final EGLConfig eglContextConfig; @Override public EGLContext getRawContext() { return eglContext; } @Override public long getNativeEglContext() { EGLContext previousContext = egl.eglGetCurrentContext(); EGLDisplay currentDisplay = egl.eglGetCurrentDisplay(); EGLSurface previousDrawSurface = egl.eglGetCurrentSurface(EGL10.EGL_DRAW); EGLSurface previousReadSurface = egl.eglGetCurrentSurface(EGL10.EGL_READ); EGLSurface tempEglSurface = null; if (currentDisplay == EGL10.EGL_NO_DISPLAY) { currentDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); } try { if (previousContext != eglContext) { int[] surfaceAttribs = {EGL10.EGL_WIDTH, 1, EGL10.EGL_HEIGHT, 1, EGL10.EGL_NONE}; tempEglSurface = egl.eglCreatePbufferSurface(currentDisplay, eglContextConfig, surfaceAttribs); if (!egl.eglMakeCurrent(currentDisplay, tempEglSurface, tempEglSurface, eglContext)) { throw new RuntimeException( "Failed to make temporary EGL surface active: " + egl.eglGetError()); } } return nativeGetCurrentNativeEGLContext(); } finally { if (tempEglSurface != null) { egl.eglMakeCurrent( currentDisplay, previousDrawSurface, previousReadSurface, previousContext); egl.eglDestroySurface(currentDisplay, tempEglSurface); } } } public Context(EGL10 egl, EGLContext eglContext, EGLConfig eglContextConfig) { this.egl = egl; this.eglContext = eglContext; this.eglContextConfig = eglContextConfig; } } // Create a new context with the specified config type, sharing data with sharedContext. public EglBase10Impl(EGLContext sharedContext, int[] configAttributes) { this.egl = (EGL10) EGLContext.getEGL(); eglDisplay = getEglDisplay(); eglConfig = getEglConfig(egl, eglDisplay, configAttributes); final int openGlesVersion = EglBase.getOpenGlesVersionFromConfig(configAttributes); Logging.d(TAG, "Using OpenGL ES version " + openGlesVersion); eglContext = createEglContext(sharedContext, eglDisplay, eglConfig, openGlesVersion); } @Override public void createSurface(Surface surface) { createSurfaceInternal(new FakeSurfaceHolder(surface), false); } // Create EGLSurface from the Android SurfaceTexture. @Override public void createSurface(SurfaceTexture surfaceTexture) { createSurfaceInternal(surfaceTexture, false); } // Create EGLSurface from either a SurfaceHolder or a SurfaceTexture. private void createSurfaceInternal(Object nativeWindow, boolean background) { if (!(nativeWindow instanceof SurfaceHolder) && !(nativeWindow instanceof SurfaceTexture)) { throw new IllegalStateException("Input must be either a SurfaceHolder or SurfaceTexture"); } checkIsNotReleased(); if (background) { if (eglBackgroundSurface != EGL10.EGL_NO_SURFACE) { throw new RuntimeException("Already has an EGLSurface"); } int[] surfaceAttribs = {EGL10.EGL_NONE}; eglBackgroundSurface = egl.eglCreateWindowSurface(eglDisplay, eglConfig, nativeWindow, surfaceAttribs); if (eglBackgroundSurface == EGL10.EGL_NO_SURFACE) { throw new RuntimeException( "Failed to create window surface: 0x" + Integer.toHexString(egl.eglGetError())); } } else { if (eglSurface != EGL10.EGL_NO_SURFACE) { throw new RuntimeException("Already has an EGLSurface"); } int[] surfaceAttribs = {EGL10.EGL_NONE}; eglSurface = egl.eglCreateWindowSurface(eglDisplay, eglConfig, nativeWindow, surfaceAttribs); if (eglSurface == EGL10.EGL_NO_SURFACE) { throw new RuntimeException( "Failed to create window surface: 0x" + Integer.toHexString(egl.eglGetError())); } } } // Create dummy 1x1 pixel buffer surface so the context can be made current. @Override public void createDummyPbufferSurface() { createPbufferSurface(1, 1); } @Override public void createPbufferSurface(int width, int height) { checkIsNotReleased(); if (eglSurface != EGL10.EGL_NO_SURFACE) { throw new RuntimeException("Already has an EGLSurface"); } int[] surfaceAttribs = {EGL10.EGL_WIDTH, width, EGL10.EGL_HEIGHT, height, EGL10.EGL_NONE}; eglSurface = egl.eglCreatePbufferSurface(eglDisplay, eglConfig, surfaceAttribs); if (eglSurface == EGL10.EGL_NO_SURFACE) { throw new RuntimeException("Failed to create pixel buffer surface with size " + width + "x" + height + ": 0x" + Integer.toHexString(egl.eglGetError())); } } @Override public org.webrtc.EglBase.Context getEglBaseContext() { return new Context(egl, eglContext, eglConfig); } @Override public boolean hasSurface() { return eglSurface != EGL10.EGL_NO_SURFACE; } @Override public int surfaceWidth() { final int widthArray[] = new int[1]; egl.eglQuerySurface(eglDisplay, eglSurface, EGL10.EGL_WIDTH, widthArray); return widthArray[0]; } @Override public int surfaceHeight() { final int heightArray[] = new int[1]; egl.eglQuerySurface(eglDisplay, eglSurface, EGL10.EGL_HEIGHT, heightArray); return heightArray[0]; } @Override public void releaseSurface(boolean background) { if (background) { if (eglBackgroundSurface != EGL10.EGL_NO_SURFACE) { egl.eglDestroySurface(eglDisplay, eglBackgroundSurface); eglBackgroundSurface = EGL10.EGL_NO_SURFACE; } } else { if (eglSurface != EGL10.EGL_NO_SURFACE) { egl.eglDestroySurface(eglDisplay, eglSurface); eglSurface = EGL10.EGL_NO_SURFACE; } } } private void checkIsNotReleased() { if (eglDisplay == EGL10.EGL_NO_DISPLAY || eglContext == EGL10.EGL_NO_CONTEXT || eglConfig == null) { throw new RuntimeException("This object has been released"); } } @Override public void release() { checkIsNotReleased(); releaseSurface(false); releaseSurface(true); detachCurrent(); egl.eglDestroyContext(eglDisplay, eglContext); egl.eglTerminate(eglDisplay); eglContext = EGL10.EGL_NO_CONTEXT; eglDisplay = EGL10.EGL_NO_DISPLAY; eglConfig = null; } @Override public void makeCurrent() { checkIsNotReleased(); if (eglSurface == EGL10.EGL_NO_SURFACE) { throw new RuntimeException("No EGLSurface - can't make current"); } synchronized (EglBase.lock) { if (!egl.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) { throw new RuntimeException( "eglMakeCurrent failed: 0x" + Integer.toHexString(egl.eglGetError())); } } } // Detach the current EGL context, so that it can be made current on another thread. @Override public void detachCurrent() { synchronized (EglBase.lock) { if (!egl.eglMakeCurrent( eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT)) { throw new RuntimeException( "eglDetachCurrent failed: 0x" + Integer.toHexString(egl.eglGetError())); } } } @Override public void swapBuffers(boolean background) { EGLSurface surface = background ? eglBackgroundSurface : eglSurface; checkIsNotReleased(); if (surface == EGL10.EGL_NO_SURFACE) { throw new RuntimeException("No EGLSurface - can't swap buffers"); } synchronized (EglBase.lock) { egl.eglSwapBuffers(eglDisplay, surface); } } @Override public void swapBuffers(long timeStampNs, boolean background) { // Setting presentation time is not supported for EGL 1.0. swapBuffers(background); } @Override public void createBackgroundSurface(SurfaceTexture surface) { createSurfaceInternal(surface, true); } @Override public void makeBackgroundCurrent() { checkIsNotReleased(); if (eglBackgroundSurface == EGL10.EGL_NO_SURFACE) { throw new RuntimeException("No EGLSurface - can't make current"); } synchronized (EglBase.lock) { if (!egl.eglMakeCurrent(eglDisplay, eglBackgroundSurface, eglBackgroundSurface, eglContext)) { throw new RuntimeException( "eglMakeCurrent failed: 0x" + Integer.toHexString(egl.eglGetError())); } } } @Override public boolean hasBackgroundSurface() { return eglBackgroundSurface != EGL10.EGL_NO_SURFACE; } // Return an EGLDisplay, or die trying. private EGLDisplay getEglDisplay() { EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); if (eglDisplay == EGL10.EGL_NO_DISPLAY) { throw new RuntimeException( "Unable to get EGL10 display: 0x" + Integer.toHexString(egl.eglGetError())); } int[] version = new int[2]; if (!egl.eglInitialize(eglDisplay, version)) { throw new RuntimeException( "Unable to initialize EGL10: 0x" + Integer.toHexString(egl.eglGetError())); } return eglDisplay; } // Return an EGLConfig, or die trying. private static EGLConfig getEglConfig(EGL10 egl, EGLDisplay eglDisplay, int[] configAttributes) { EGLConfig[] configs = new EGLConfig[1]; int[] numConfigs = new int[1]; if (!egl.eglChooseConfig(eglDisplay, configAttributes, configs, configs.length, numConfigs)) { throw new RuntimeException( "eglChooseConfig failed: 0x" + Integer.toHexString(egl.eglGetError())); } if (numConfigs[0] <= 0) { throw new RuntimeException("Unable to find any matching EGL config"); } final EGLConfig eglConfig = configs[0]; if (eglConfig == null) { throw new RuntimeException("eglChooseConfig returned null"); } return eglConfig; } // Return an EGLConfig, or die trying. private EGLContext createEglContext(@Nullable EGLContext sharedContext, EGLDisplay eglDisplay, EGLConfig eglConfig, int openGlesVersion) { if (sharedContext != null && sharedContext == EGL10.EGL_NO_CONTEXT) { throw new RuntimeException("Invalid sharedContext"); } int[] contextAttributes = {EGL_CONTEXT_CLIENT_VERSION, openGlesVersion, EGL10.EGL_NONE}; EGLContext rootContext = sharedContext == null ? EGL10.EGL_NO_CONTEXT : sharedContext; final EGLContext eglContext; synchronized (EglBase.lock) { eglContext = egl.eglCreateContext(eglDisplay, eglConfig, rootContext, contextAttributes); } if (eglContext == EGL10.EGL_NO_CONTEXT) { throw new RuntimeException( "Failed to create EGL context: 0x" + Integer.toHexString(egl.eglGetError())); } return eglContext; } /** * We have to wrap Surface in a SurfaceHolder because for some reason eglCreateWindowSurface * couldn't actually take a Surface object until API 17. Older versions fortunately just call * SurfaceHolder.getSurface(), so we'll do that. No other methods are relevant. */ private class FakeSurfaceHolder implements SurfaceHolder { private final Surface surface; FakeSurfaceHolder(Surface surface) { this.surface = surface; } @Override public void addCallback(Callback callback) { } @Override public void removeCallback(Callback callback) { } @Override public boolean isCreating() { return false; } @Deprecated @Override public void setType(int i) { } @Override public void setFixedSize(int i, int i2) { } @Override public void setSizeFromLayout() { } @Override public void setFormat(int i) { } @Override public void setKeepScreenOn(boolean b) { } @Nullable @Override public Canvas lockCanvas() { return null; } @Nullable @Override public Canvas lockCanvas(Rect rect) { return null; } @Override public void unlockCanvasAndPost(Canvas canvas) { } @Nullable @Override public Rect getSurfaceFrame() { return null; } @Override public Surface getSurface() { return surface; } } private static native long nativeGetCurrentNativeEGLContext(); }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/org/webrtc/EglBase10Impl.java
2,178
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2012-19 The Processing Foundation Copyright (c) 2004-12 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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.ui; import processing.app.Base; import processing.app.Formatter; import processing.app.Language; import processing.app.Messages; import processing.app.Mode; import processing.app.Platform; import processing.app.Preferences; import processing.app.Problem; import processing.app.RunnerListener; import processing.app.Sketch; import processing.app.SketchCode; import processing.app.SketchException; import processing.app.Util; import processing.app.contrib.ContributionManager; import processing.app.syntax.*; import processing.core.*; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.Frame; import java.awt.Image; import java.awt.Point; import java.awt.Window; import java.awt.datatransfer.*; import java.awt.event.*; import java.awt.print.*; import java.io.*; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Stack; import java.util.Timer; import java.util.TimerTask; import java.util.stream.Collectors; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.basic.*; import javax.swing.text.*; import javax.swing.text.html.*; import javax.swing.undo.*; /** * Main editor panel for the Processing Development Environment. */ public abstract class Editor extends JFrame implements RunnerListener { protected Base base; protected EditorState state; protected Mode mode; static public final int LEFT_GUTTER = Toolkit.zoom(44); static public final int RIGHT_GUTTER = Toolkit.zoom(12); static public final int GUTTER_MARGIN = Toolkit.zoom(3); protected MarkerColumn errorColumn; // Otherwise, if the window is resized with the message label // set to blank, its preferredSize() will be fuckered static protected final String EMPTY = " " + " " + " "; /** * true if this file has not yet been given a name by the user */ // private boolean untitled; private PageFormat pageFormat; private PrinterJob printerJob; // File and sketch menus for re-inserting items private JMenu fileMenu; // private JMenuItem saveMenuItem; // private JMenuItem saveAsMenuItem; private JMenu sketchMenu; protected EditorHeader header; protected EditorToolbar toolbar; protected JEditTextArea textarea; protected EditorStatus status; protected JSplitPane splitPane; protected EditorFooter footer; protected EditorConsole console; protected ErrorTable errorTable; // currently opened program protected Sketch sketch; // runtime information and window placement private Point sketchWindowLocation; // undo fellers private JMenuItem undoItem, redoItem; protected UndoAction undoAction; protected RedoAction redoAction; protected CutAction cutAction; protected CopyAction copyAction; protected CopyAsHtmlAction copyAsHtmlAction; protected PasteAction pasteAction; /** Menu Actions updated on the opening of the edit menu. */ protected List<UpdatableAction> editMenuUpdatable = new ArrayList<>(); /** The currently selected tab's undo manager */ private UndoManager undo; // used internally for every edit. Groups hotkey-event text manipulations and // groups multi-character inputs into a single undos. private CompoundEdit compoundEdit; // timer to decide when to group characters into an undo private Timer timer; private TimerTask endUndoEvent; // true if inserting text, false if removing text private boolean isInserting; // maintain caret position during undo operations private final Stack<Integer> caretUndoStack = new Stack<>(); private final Stack<Integer> caretRedoStack = new Stack<>(); private FindReplace find; JMenu toolsMenu; JMenu modePopup; Image backgroundGradient; protected List<Problem> problems = Collections.emptyList(); protected Editor(final Base base, String path, final EditorState state, final Mode mode) throws EditorException { super("Processing", state.checkConfig()); this.base = base; this.state = state; this.mode = mode; // Make sure Base.getActiveEditor() never returns null base.checkFirstEditor(this); // This is a Processing window. Get rid of that ugly ass coffee cup. Toolkit.setIcon(this); // add listener to handle window close box hit event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { base.handleClose(Editor.this, false); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods // http://dev.processing.org/bugs/show_bug.cgi?id=440 setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); // When bringing a window to front, let the Base know addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { base.handleActivated(Editor.this); fileMenu.insert(Recent.getMenu(), 2); Toolkit.setMenuMnemsInside(fileMenu); mode.insertImportMenu(sketchMenu); Toolkit.setMenuMnemsInside(sketchMenu); mode.insertToolbarRecentMenu(); } public void windowDeactivated(WindowEvent e) { // TODO call handleActivated(null)? or do we run the risk of the // deactivate call for old window being called after the activate? fileMenu.remove(Recent.getMenu()); mode.removeImportMenu(sketchMenu); mode.removeToolbarRecentMenu(); } }); timer = new Timer(); buildMenuBar(); /* //backgroundGradient = Toolkit.getLibImage("vertical-gradient.png"); backgroundGradient = mode.getGradient("editor", 400, 400); JPanel contentPain = new JPanel() { @Override public void paintComponent(Graphics g) { // super.paintComponent(g); Dimension dim = getSize(); g.drawImage(backgroundGradient, 0, 0, dim.width, dim.height, this); // g.setColor(Color.RED); // g.fillRect(0, 0, dim.width, dim.height); } }; */ //contentPain.setBorder(new EmptyBorder(0, 0, 0, 0)); //System.out.println(contentPain.getBorder()); JPanel contentPain = new JPanel(); // JFrame f = new JFrame(); // f.setContentPane(new JPanel() { // @Override // public void paintComponent(Graphics g) { //// super.paintComponent(g); // Dimension dim = getSize(); // g.drawImage(backgroundGradient, 0, 0, dim.width, dim.height, this); //// g.setColor(Color.RED); //// g.fillRect(0, 0, dim.width, dim.height); // } // }); // f.setResizable(true); // f.setVisible(true); //Container contentPain = getContentPane(); setContentPane(contentPain); contentPain.setLayout(new BorderLayout()); // JPanel pain = new JPanel(); // pain.setOpaque(false); // pain.setLayout(new BorderLayout()); // contentPain.add(pain, BorderLayout.CENTER); // contentPain.setBorder(new EmptyBorder(10, 10, 10, 10)); Box box = Box.createVerticalBox(); Box upper = Box.createVerticalBox(); // upper.setOpaque(false); // box.setOpaque(false); rebuildModePopup(); toolbar = createToolbar(); upper.add(toolbar); header = createHeader(); upper.add(header); textarea = createTextArea(); textarea.setRightClickPopup(new TextAreaPopup()); textarea.setHorizontalOffset(JEditTextArea.leftHandGutter); { // Hack: add Numpad Slash as alternative shortcut for Comment/Uncomment int modifiers = Toolkit.awtToolkit.getMenuShortcutKeyMask(); KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_DIVIDE, modifiers); final String ACTION_KEY = "COMMENT_UNCOMMENT_ALT"; textarea.getInputMap().put(keyStroke, ACTION_KEY); textarea.getActionMap().put(ACTION_KEY, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { handleCommentUncomment(); } }); } textarea.addCaretListener(new CaretListener() { public void caretUpdate(CaretEvent e) { updateEditorStatus(); } }); footer = createFooter(); // build the central panel with the text area & error marker column JPanel editorPanel = new JPanel(new BorderLayout()); errorColumn = new MarkerColumn(this, textarea.getMinimumSize().height); editorPanel.add(errorColumn, BorderLayout.EAST); textarea.setBounds(0, 0, errorColumn.getX() - 1, textarea.getHeight()); editorPanel.add(textarea); upper.add(editorPanel); // set colors and fonts for the painter object PdeTextArea pta = getPdeTextArea(); if (pta != null) { pta.setMode(mode); } splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, footer); // disable this because it hides the message area (Google Code issue #745) splitPane.setOneTouchExpandable(false); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the upper pane splitPane.setResizeWeight(1D); // remove any ugly borders added by PLAFs (doesn't fix everything) splitPane.setBorder(null); // remove an ugly border around anything in a SplitPane !$*&!% UIManager.getDefaults().put("SplitPane.border", BorderFactory.createEmptyBorder()); // set the height per our gui design splitPane.setDividerSize(EditorStatus.HIGH); // override the look of the SplitPane so that it's identical across OSes splitPane.setUI(new BasicSplitPaneUI() { public BasicSplitPaneDivider createDefaultDivider() { status = new EditorStatus(this, Editor.this); return status; } @Override public void finishDraggingTo(int location) { super.finishDraggingTo(location); // JSplitPane issue: if you only make the lower component visible at // the last minute, its minmum size is ignored. if (location > splitPane.getMaximumDividerLocation()) { splitPane.setDividerLocation(splitPane.getMaximumDividerLocation()); } } }); box.add(splitPane); contentPain.add(box); // end an undo-chunk any time the caret moves unless it's when text is edited textarea.addCaretListener(new CaretListener() { String lastText = textarea.getText(); public void caretUpdate(CaretEvent e) { String newText = textarea.getText(); if (lastText.equals(newText) && isDirectEdit() && !textarea.isOverwriteEnabled()) { endTextEditHistory(); } lastText = newText; } }); textarea.addKeyListener(toolbar); contentPain.setTransferHandler(new FileDropHandler()); // Finish preparing Editor pack(); // Set the window bounds and the divider location before setting it visible state.apply(this); // Set the minimum size for the editor window int minWidth = Toolkit.zoom(Preferences.getInteger("editor.window.width.min")); int minHeight = Toolkit.zoom(Preferences.getInteger("editor.window.height.min")); setMinimumSize(new Dimension(minWidth, minHeight)); // Bring back the general options for the editor applyPreferences(); // Make textField get the focus whenever frame is activated. // http://download.oracle.com/javase/tutorial/uiswing/misc/focus.html // May not be necessary, but helps avoid random situations with // the editor not being able to request its own focus. addWindowFocusListener(new WindowAdapter() { public void windowGainedFocus(WindowEvent e) { textarea.requestFocusInWindow(); } }); // TODO: Subclasses can't initialize anything before Doc Open happens since // super() has to be the first line in subclass constructor; we might // want to keep constructor light and call methods later [jv 160318] // Open the document that was passed in handleOpenInternal(path); // Add a window listener to watch for changes to the files in the sketch addWindowFocusListener(new ChangeDetector(this)); // Try to enable fancy fullscreen on OSX if (Platform.isMacOS()) { try { Class util = Class.forName("com.apple.eawt.FullScreenUtilities"); Class params[] = new Class[]{Window.class, Boolean.TYPE}; Method method = util.getMethod("setWindowCanFullScreen", params); method.invoke(util, this, true); } catch (Exception e) { Messages.loge("Could not enable OSX fullscreen", e); } } } /* protected List<ToolContribution> getCoreTools() { return coreTools; } public List<ToolContribution> getToolContribs() { return contribTools; } public void removeToolContrib(ToolContribution tc) { contribTools.remove(tc); } */ protected JEditTextArea createTextArea() { return new JEditTextArea(new PdeTextAreaDefaults(mode), new PdeInputHandler(this)); } public EditorFooter createFooter() { EditorFooter ef = new EditorFooter(this); console = new EditorConsole(this); ef.addPanel(console, Language.text("editor.footer.console"), "/lib/footer/console"); return ef; } public void addErrorTable(EditorFooter ef) { JScrollPane scrollPane = new JScrollPane(); errorTable = new ErrorTable(this); scrollPane.setBorder(BorderFactory.createEmptyBorder()); scrollPane.setViewportView(errorTable); ef.addPanel(scrollPane, Language.text("editor.footer.errors"), "/lib/footer/error"); } public EditorState getEditorState() { return state; } /** * Handles files dragged & dropped from the desktop and into the editor * window. Dragging files into the editor window is the same as using * "Sketch &rarr; Add File" for each file. */ class FileDropHandler extends TransferHandler { public boolean canImport(TransferHandler.TransferSupport support) { return !sketch.isReadOnly(); } @SuppressWarnings("unchecked") public boolean importData(TransferHandler.TransferSupport support) { int successful = 0; if (!canImport(support)) { return false; } try { Transferable transferable = support.getTransferable(); DataFlavor uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String"); if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { List list = (List) transferable.getTransferData(DataFlavor.javaFileListFlavor); for (int i = 0; i < list.size(); i++) { File file = (File) list.get(i); if (sketch.addFile(file)) { successful++; } } } else if (transferable.isDataFlavorSupported(uriListFlavor)) { // Some platforms (Mac OS X and Linux, when this began) preferred // this method of moving files. String data = (String)transferable.getTransferData(uriListFlavor); String[] pieces = PApplet.splitTokens(data, "\r\n"); for (int i = 0; i < pieces.length; i++) { if (pieces[i].startsWith("#")) continue; String path = null; if (pieces[i].startsWith("file:///")) { path = pieces[i].substring(7); } else if (pieces[i].startsWith("file:/")) { path = pieces[i].substring(5); } if (sketch.addFile(new File(path))) { successful++; } } } } catch (Exception e) { Messages.showWarning("Drag & Drop Problem", "An error occurred while trying to add files to the sketch.", e); return false; } statusNotice(Language.pluralize("editor.status.drag_and_drop.files_added", successful)); return true; } } public Base getBase() { return base; } public Mode getMode() { return mode; } public void repaintHeader() { header.repaint(); } public void rebuildHeader() { header.rebuild(); } public void rebuildModePopup() { modePopup = new JMenu(); ButtonGroup modeGroup = new ButtonGroup(); for (final Mode m : base.getModeList()) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(m.getTitle()); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!sketch.isModified()) { if (!base.changeMode(m)) { reselectMode(); Messages.showWarning(Language.text("warn.cannot_change_mode.title"), Language.interpolate("warn.cannot_change_mode.body", m)); } } else { reselectMode(); Messages.showWarning("Save", "Please save the sketch before changing the mode."); } } }); modePopup.add(item); modeGroup.add(item); if (mode == m) { item.setSelected(true); } } modePopup.addSeparator(); JMenuItem addLib = new JMenuItem(Language.text("toolbar.add_mode")); addLib.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ContributionManager.openModes(); } }); modePopup.add(addLib); Toolkit.setMenuMnemsInside(modePopup); } // Re-select the old checkbox, because it was automatically // updated by Java, even though the Mode could not be changed. // https://github.com/processing/processing/issues/2615 private void reselectMode() { for (Component c : getModePopup().getComponents()) { if (c instanceof JRadioButtonMenuItem) { if (((JRadioButtonMenuItem)c).getText() == mode.getTitle()) { ((JRadioButtonMenuItem)c).setSelected(true); break; } } } } public JPopupMenu getModePopup() { return modePopup.getPopupMenu(); } // public JMenu getModeMenu() { // return modePopup; // } public EditorConsole getConsole() { return console; } // public Settings getTheme() { // return mode.getTheme(); // } public EditorHeader createHeader() { return new EditorHeader(this); } abstract public EditorToolbar createToolbar(); public void rebuildToolbar() { toolbar.rebuild(); toolbar.revalidate(); // necessary to handle sub-components } abstract public Formatter createFormatter(); // protected void setPlacement(int[] location) { // setBounds(location[0], location[1], location[2], location[3]); // if (location[4] != 0) { // splitPane.setDividerLocation(location[4]); // } // } // // // protected int[] getPlacement() { // int[] location = new int[5]; // // // Get the dimensions of the Frame // Rectangle bounds = getBounds(); // location[0] = bounds.x; // location[1] = bounds.y; // location[2] = bounds.width; // location[3] = bounds.height; // // // Get the current placement of the divider // location[4] = splitPane.getDividerLocation(); // // return location; // } protected void setDividerLocation(int pos) { splitPane.setDividerLocation(pos); } protected int getDividerLocation() { return splitPane.getDividerLocation(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Read and apply new values from the preferences, either because * the app is just starting up, or the user just finished messing * with things in the Preferences window. */ protected void applyPreferences() { // Update fonts and other items controllable from the prefs textarea.getPainter().updateAppearance(); textarea.repaint(); console.updateAppearance(); // All of this code was specific to using an external editor. /* // // apply the setting for 'use external editor' // boolean external = Preferences.getBoolean("editor.external"); // textarea.setEditable(!external); // saveMenuItem.setEnabled(!external); // saveAsMenuItem.setEnabled(!external); TextAreaPainter painter = textarea.getPainter(); // if (external) { // // disable line highlight and turn off the caret when disabling // Color color = mode.getColor("editor.external.bgcolor"); // painter.setBackground(color); // painter.setLineHighlightEnabled(false); // textarea.setCaretVisible(false); // } else { Color color = mode.getColor("editor.bgcolor"); painter.setBackground(color); boolean highlight = Preferences.getBoolean("editor.linehighlight"); painter.setLineHighlightEnabled(highlight); textarea.setCaretVisible(true); // } // apply changes to the font size for the editor // painter.setFont(Preferences.getFont("editor.font")); // in case tab expansion stuff has changed // removing this, just checking prefs directly instead // listener.applyPreferences(); // in case moved to a new location // For 0125, changing to async version (to be implemented later) //sketchbook.rebuildMenus(); // For 0126, moved into Base, which will notify all editors. //base.rebuildMenusAsync(); */ } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . protected void buildMenuBar() { JMenuBar menubar = new JMenuBar(); fileMenu = buildFileMenu(); menubar.add(fileMenu); menubar.add(buildEditMenu()); menubar.add(buildSketchMenu()); // For 3.0a4 move mode menu to the left of the Tool menu JMenu modeMenu = buildModeMenu(); if (modeMenu != null) { menubar.add(modeMenu); } toolsMenu = new JMenu(Language.text("menu.tools")); base.populateToolsMenu(toolsMenu); menubar.add(toolsMenu); menubar.add(buildHelpMenu()); Toolkit.setMenuMnemonics(menubar); setJMenuBar(menubar); } abstract public JMenu buildFileMenu(); // public JMenu buildFileMenu(Editor editor) { // return buildFileMenu(editor, null); // } // // // // most of these items are per-mode // protected JMenu buildFileMenu(Editor editor, JMenuItem[] exportItems) { protected JMenu buildFileMenu(JMenuItem[] exportItems) { JMenuItem item; JMenu fileMenu = new JMenu(Language.text("menu.file")); item = Toolkit.newJMenuItem(Language.text("menu.file.new"), 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleNew(); } }); fileMenu.add(item); item = Toolkit.newJMenuItem(Language.text("menu.file.open"), 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleOpenPrompt(); } }); fileMenu.add(item); // fileMenu.add(base.getSketchbookMenu()); item = Toolkit.newJMenuItemShift(Language.text("menu.file.sketchbook"), 'K'); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { mode.showSketchbookFrame(); } }); fileMenu.add(item); item = Toolkit.newJMenuItemShift(Language.text("menu.file.examples"), 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { mode.showExamplesFrame(); } }); fileMenu.add(item); item = Toolkit.newJMenuItem(Language.text("menu.file.close"), 'W'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleClose(Editor.this, false); } }); fileMenu.add(item); item = Toolkit.newJMenuItem(Language.text("menu.file.save"), 'S'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSave(false); } }); // saveMenuItem = item; fileMenu.add(item); item = Toolkit.newJMenuItemShift(Language.text("menu.file.save_as"), 'S'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveAs(); } }); // saveAsMenuItem = item; fileMenu.add(item); if (exportItems != null) { for (JMenuItem ei : exportItems) { fileMenu.add(ei); } } fileMenu.addSeparator(); item = Toolkit.newJMenuItemShift(Language.text("menu.file.page_setup"), 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePageSetup(); } }); fileMenu.add(item); item = Toolkit.newJMenuItem(Language.text("menu.file.print"), 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrint(); } }); fileMenu.add(item); // Mac OS X already has its own preferences and quit menu. // That's right! Think different, b*tches! if (!Platform.isMacOS()) { fileMenu.addSeparator(); item = Toolkit.newJMenuItem(Language.text("menu.file.preferences"), ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handlePrefs(); } }); fileMenu.add(item); fileMenu.addSeparator(); item = Toolkit.newJMenuItem(Language.text("menu.file.quit"), 'Q'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleQuit(); } }); fileMenu.add(item); } return fileMenu; } // public void setSaveItem(JMenuItem item) { // saveMenuItem = item; // } // public void setSaveAsItem(JMenuItem item) { // saveAsMenuItem = item; // } protected JMenu buildEditMenu() { JMenu menu = new JMenu(Language.text("menu.edit")); JMenuItem item; undoItem = Toolkit.newJMenuItem(undoAction = new UndoAction(), 'Z'); menu.add(undoItem); redoItem = new JMenuItem(redoAction = new RedoAction()); redoItem.setAccelerator(Toolkit.getKeyStrokeExt("menu.edit.redo")); menu.add(redoItem); menu.addSeparator(); item = Toolkit.newJMenuItem(cutAction = new CutAction(), 'X'); editMenuUpdatable.add(cutAction); menu.add(item); item = Toolkit.newJMenuItem(copyAction = new CopyAction(), 'C'); editMenuUpdatable.add(copyAction); menu.add(item); item = Toolkit.newJMenuItemShift(copyAsHtmlAction = new CopyAsHtmlAction(), 'C'); editMenuUpdatable.add(copyAsHtmlAction); menu.add(item); item = Toolkit.newJMenuItem(pasteAction = new PasteAction(), 'V'); editMenuUpdatable.add(pasteAction); menu.add(item); item = Toolkit.newJMenuItem(Language.text("menu.edit.select_all"), 'A'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); menu.add(item); /* menu.addSeparator(); item = Toolkit.newJMenuItem("Delete Selected Lines", 'D'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleDeleteLines(); } }); menu.add(item); item = new JMenuItem("Move Selected Lines Up"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_UP, Event.ALT_MASK)); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleMoveLines(true); } }); menu.add(item); item = new JMenuItem("Move Selected Lines Down"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Event.ALT_MASK)); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleMoveLines(false); } }); menu.add(item); */ menu.addSeparator(); item = Toolkit.newJMenuItem(Language.text("menu.edit.auto_format"), 'T'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleAutoFormat(); } }); menu.add(item); item = Toolkit.newJMenuItemExt("menu.edit.comment_uncomment"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCommentUncomment(); } }); menu.add(item); item = Toolkit.newJMenuItemExt("menu.edit.increase_indent"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(true); } }); menu.add(item); item = Toolkit.newJMenuItemExt("menu.edit.decrease_indent"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(false); } }); menu.add(item); menu.addSeparator(); item = Toolkit.newJMenuItem(Language.text("menu.edit.find"), 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this); } // https://github.com/processing/processing/issues/3457 String selection = getSelectedText(); if (selection != null && selection.length() != 0 && !selection.contains("\n")) { find.setFindText(selection); } find.setVisible(true); } }); menu.add(item); UpdatableAction action; item = Toolkit.newJMenuItem(action = new FindNextAction(), 'G'); editMenuUpdatable.add(action); menu.add(item); item = Toolkit.newJMenuItemShift(action = new FindPreviousAction(), 'G'); editMenuUpdatable.add(action); menu.add(item); item = Toolkit.newJMenuItem(action = new SelectionForFindAction(), 'E'); editMenuUpdatable.add(action); menu.add(item); // Update copy/cut state on selection/de-selection menu.addMenuListener(new MenuListener() { // UndoAction and RedoAction do this for themselves. @Override public void menuCanceled(MenuEvent e) { for (UpdatableAction a : editMenuUpdatable) { a.setEnabled(true); } } @Override public void menuDeselected(MenuEvent e) { for (UpdatableAction a : editMenuUpdatable) { a.setEnabled(true); } } @Override public void menuSelected(MenuEvent e) { for (UpdatableAction a : editMenuUpdatable) { a.updateState(); } } }); return menu; } abstract public JMenu buildSketchMenu(); protected JMenu buildSketchMenu(JMenuItem[] runItems) { JMenuItem item; sketchMenu = new JMenu(Language.text("menu.sketch")); for (JMenuItem mi : runItems) { sketchMenu.add(mi); } sketchMenu.addSeparator(); sketchMenu.add(mode.getImportMenu()); item = Toolkit.newJMenuItem(Language.text("menu.sketch.show_sketch_folder"), 'K'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Platform.openFolder(sketch.getFolder()); } }); sketchMenu.add(item); item.setEnabled(Platform.openFolderAvailable()); item = new JMenuItem(Language.text("menu.sketch.add_file")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sketch.handleAddFile(); } }); sketchMenu.add(item); if (runItems != null && runItems.length != 0) { sketchMenu.addSeparator(); } // final Editor editorName = this; sketchMenu.addMenuListener(new MenuListener() { // Menu Listener that populates the menu only when the menu is opened List<JMenuItem> menuList = new ArrayList<>(); @Override public void menuSelected(MenuEvent event) { JMenuItem item; for (final Editor editor : base.getEditors()) { //if (Editor.this.getSketch().getName().trim().contains(editor2.getSketch().getName().trim())) if (getSketch().getMainFilePath().equals(editor.getSketch().getMainFilePath())) { item = new JCheckBoxMenuItem(editor.getSketch().getName()); item.setSelected(true); } else { item = new JMenuItem(editor.getSketch().getName()); } item.setText(editor.getSketch().getName() + " (" + editor.getMode().getTitle() + ")"); // Action listener to bring the appropriate sketch in front item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { editor.setState(Frame.NORMAL); editor.setVisible(true); editor.toFront(); } }); sketchMenu.add(item); menuList.add(item); Toolkit.setMenuMnemsInside(sketchMenu); } } @Override public void menuDeselected(MenuEvent event) { for (JMenuItem item : menuList) { sketchMenu.remove(item); } menuList.clear(); } @Override public void menuCanceled(MenuEvent event) { menuDeselected(event); } }); return sketchMenu; } abstract public void handleImportLibrary(String name); public void librariesChanged() { } public void codeFolderChanged() { } public void sketchChanged() { } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . public JMenu getToolMenu() { return toolsMenu; } /* public JMenu getToolMenu() { if (toolsMenu == null) { rebuildToolMenu(); } return toolsMenu; } public void removeTool() { rebuildToolMenu(); } */ /** * Clears the Tool menu and runs the gc so that contributions can be updated * without classes still being in use. */ public void clearToolMenu() { toolsMenu.removeAll(); System.gc(); } /** * Updates update count in the UI. Called on EDT. * @param count number of available updates */ public void setUpdatesAvailable(int count) { footer.setUpdateCount(count); } /** * Override this if you want a special menu for your particular 'mode'. */ public JMenu buildModeMenu() { return null; } /* protected void addToolMenuItem(JMenu menu, String className) { try { Class<?> toolClass = Class.forName(className); final Tool tool = (Tool) toolClass.newInstance(); JMenuItem item = new JMenuItem(tool.getMenuTitle()); tool.init(Editor.this); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { EventQueue.invokeLater(tool); } }); menu.add(item); } catch (Exception e) { e.printStackTrace(); } } protected JMenu addInternalTools(JMenu menu) { addToolMenuItem(menu, "processing.app.tools.CreateFont"); addToolMenuItem(menu, "processing.app.tools.ColorSelector"); addToolMenuItem(menu, "processing.app.tools.Archiver"); if (Platform.isMacOS()) { addToolMenuItem(menu, "processing.app.tools.InstallCommander"); } return menu; } */ /* // testing internal web server to serve up docs from a zip file item = new JMenuItem("Web Server Test"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //WebServer ws = new WebServer(); SwingUtilities.invokeLater(new Runnable() { public void run() { try { int port = WebServer.launch("/Users/fry/coconut/processing/build/shared/reference.zip"); Base.openURL("http://127.0.0.1:" + port + "/reference/setup_.html"); } catch (IOException e1) { e1.printStackTrace(); } } }); } }); menu.add(item); */ /* item = new JMenuItem("Browser Test"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Base.openURL("http://processing.org/learning/gettingstarted/"); //JFrame browserFrame = new JFrame("Browser"); BrowserStartup bs = new BrowserStartup("jar:file:/Users/fry/coconut/processing/build/shared/reference.zip!/reference/setup_.html"); bs.initUI(); bs.launch(); } }); menu.add(item); */ abstract public JMenu buildHelpMenu(); public void showReference(String filename) { File file = new File(mode.getReferenceFolder(), filename); showReferenceFile(file); } /** * Given the .html file, displays it in the default browser. * * @param file */ public void showReferenceFile(File file) { try { file = file.getCanonicalFile(); } catch (IOException e) { e.printStackTrace(); } // Prepend with file:// and also encode spaces & other characters Platform.openURL(file.toURI().toString()); } static public void showChanges() { // http://code.google.com/p/processing/issues/detail?id=1520 if (!Base.isCommandLine()) { Platform.openURL("https://github.com/processing/processing/wiki/Changes"); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Subclass if you want to have setEnabled(canDo()); called when your menu * is opened. */ abstract class UpdatableAction extends AbstractAction { public UpdatableAction(String name) { super(name); } abstract public boolean canDo(); public void updateState() { setEnabled(canDo()); } } class CutAction extends UpdatableAction { public CutAction() { super(Language.text("menu.edit.cut")); } @Override public void actionPerformed(ActionEvent e) { handleCut(); } public boolean canDo() { return textarea.isSelectionActive(); } } class CopyAction extends UpdatableAction { public CopyAction() { super(Language.text("menu.edit.copy")); } @Override public void actionPerformed(ActionEvent e) { handleCopy(); } public boolean canDo() { return textarea.isSelectionActive(); } } class CopyAsHtmlAction extends UpdatableAction { public CopyAsHtmlAction() { super(Language.text("menu.edit.copy_as_html")); } @Override public void actionPerformed(ActionEvent e) { handleCopyAsHTML(); } public boolean canDo() { return textarea.isSelectionActive(); } } class PasteAction extends UpdatableAction { public PasteAction() { super(Language.text("menu.edit.paste")); } @Override public void actionPerformed(ActionEvent e) { textarea.paste(); sketch.setModified(true); } public boolean canDo() { return getToolkit().getSystemClipboard() .isDataFlavorAvailable(DataFlavor.stringFlavor); } } class UndoAction extends AbstractAction { public UndoAction() { super(Language.text("menu.edit.undo")); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { stopCompoundEdit(); try { final Integer caret = caretUndoStack.pop(); caretRedoStack.push(caret); textarea.setCaretPosition(caret); textarea.scrollToCaret(); } catch (Exception ignore) { } try { undo.undo(); } catch (CannotUndoException ex) { //System.out.println("Unable to undo: " + ex); //ex.printStackTrace(); } updateUndoState(); redoAction.updateRedoState(); if (sketch != null) { sketch.setModified(!getText().equals(sketch.getCurrentCode().getSavedProgram())); // Go through all tabs; Replace All, Rename or Undo could have changed them for (SketchCode sc : sketch.getCode()) { if (sc.getDocument() != null) { try { sc.setModified(!sc.getDocumentText().equals(sc.getSavedProgram())); } catch (BadLocationException ignore) { } } } repaintHeader(); } } protected void updateUndoState() { if (undo.canUndo() || compoundEdit != null && compoundEdit.isInProgress()) { this.setEnabled(true); undoItem.setEnabled(true); String newUndoPresentationName = Language.text("menu.edit.undo"); if (undo.getUndoPresentationName().equals("Undo addition")) { newUndoPresentationName += " "+Language.text("menu.edit.action.addition"); } else if (undo.getUndoPresentationName().equals("Undo deletion")) { newUndoPresentationName += " "+Language.text("menu.edit.action.deletion"); } undoItem.setText(newUndoPresentationName); putValue(Action.NAME, newUndoPresentationName); // if (sketch != null) { // sketch.setModified(true); // 0107, removed for 0196 // } } else { this.setEnabled(false); undoItem.setEnabled(false); undoItem.setText(Language.text("menu.edit.undo")); putValue(Action.NAME, Language.text("menu.edit.undo")); // if (sketch != null) { // sketch.setModified(false); // 0107 // } } } } class RedoAction extends AbstractAction { public RedoAction() { super(Language.text("menu.edit.redo")); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { stopCompoundEdit(); try { undo.redo(); } catch (CannotRedoException ex) { //System.out.println("Unable to redo: " + ex); //ex.printStackTrace(); } try { final Integer caret = caretRedoStack.pop(); caretUndoStack.push(caret); textarea.setCaretPosition(caret); } catch (Exception ignore) { } updateRedoState(); undoAction.updateUndoState(); if (sketch != null) { sketch.setModified(!getText().equals(sketch.getCurrentCode().getSavedProgram())); // Go through all tabs; Replace All, Rename or Undo could have changed them for (SketchCode sc : sketch.getCode()) { if (sc.getDocument() != null) { try { sc.setModified(!sc.getDocumentText().equals(sc.getSavedProgram())); } catch (BadLocationException ignore) { } } } repaintHeader(); } } protected void updateRedoState() { if (undo.canRedo()) { redoItem.setEnabled(true); String newRedoPresentationName = Language.text("menu.edit.redo"); if (undo.getRedoPresentationName().equals("Redo addition")) { newRedoPresentationName += " " + Language.text("menu.edit.action.addition"); } else if (undo.getRedoPresentationName().equals("Redo deletion")) { newRedoPresentationName += " " + Language.text("menu.edit.action.deletion"); } redoItem.setText(newRedoPresentationName); putValue(Action.NAME, newRedoPresentationName); } else { this.setEnabled(false); redoItem.setEnabled(false); redoItem.setText(Language.text("menu.edit.redo")); putValue(Action.NAME, Language.text("menu.edit.redo")); } } } class FindNextAction extends UpdatableAction { public FindNextAction() { super(Language.text("menu.edit.find_next")); } @Override public void actionPerformed(ActionEvent e) { if (find != null) find.findNext(); } public boolean canDo() { return find != null && find.canFindNext(); } } class FindPreviousAction extends UpdatableAction { public FindPreviousAction() { super(Language.text("menu.edit.find_previous")); } @Override public void actionPerformed(ActionEvent e) { if (find != null) find.findPrevious(); } public boolean canDo() { return find != null && find.canFindNext(); } } class SelectionForFindAction extends UpdatableAction { public SelectionForFindAction() { super(Language.text("menu.edit.use_selection_for_find")); } @Override public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this); } find.setFindText(getSelectedText()); } public boolean canDo() { return textarea.isSelectionActive(); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // these will be done in a more generic way soon, more like: // setHandler("action name", Runnable); // but for the time being, working out the kinks of how many things to // abstract from the editor in this fashion. // public void setHandlers(Runnable runHandler, Runnable presentHandler, // Runnable stopHandler, // Runnable exportHandler, Runnable exportAppHandler) { // this.runHandler = runHandler; // this.presentHandler = presentHandler; // this.stopHandler = stopHandler; // this.exportHandler = exportHandler; // this.exportAppHandler = exportAppHandler; // } // public void resetHandlers() { // runHandler = new DefaultRunHandler(); // presentHandler = new DefaultPresentHandler(); // stopHandler = new DefaultStopHandler(); // exportHandler = new DefaultExportHandler(); // exportAppHandler = new DefaultExportAppHandler(); // } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Gets the current sketch object. */ public Sketch getSketch() { return sketch; } /** * Get the JEditTextArea object for use (not recommended). This should only * be used in obscure cases that really need to hack the internals of the * JEditTextArea. Most tools should only interface via the get/set functions * found in this class. This will maintain compatibility with future releases, * which will not use JEditTextArea. */ public JEditTextArea getTextArea() { return textarea; } public PdeTextArea getPdeTextArea() { return (textarea instanceof PdeTextArea) ? (PdeTextArea) textarea : null; } /** * Get the contents of the current buffer. Used by the Sketch class. */ public String getText() { return textarea.getText(); } /** * Get a range of text from the current buffer. */ public String getText(int start, int stop) { return textarea.getText(start, stop - start); } /** * Replace the entire contents of the front-most tab. Note that this does * a compound edit, so internal callers may want to use textarea.setText() * if this is part of a larger compound edit. */ public void setText(String what) { startCompoundEdit(); textarea.setText(what); stopCompoundEdit(); } public void insertText(String what) { startCompoundEdit(); int caret = getCaretOffset(); setSelection(caret, caret); textarea.setSelectedText(what); stopCompoundEdit(); } public String getSelectedText() { return textarea.getSelectedText(); } public void setSelectedText(String what) { textarea.setSelectedText(what); } public void setSelectedText(String what, boolean ever) { textarea.setSelectedText(what, ever); } public void setSelection(int start, int stop) { // make sure that a tool isn't asking for a bad location start = PApplet.constrain(start, 0, textarea.getDocumentLength()); stop = PApplet.constrain(stop, 0, textarea.getDocumentLength()); textarea.select(start, stop); } /** * Get the position (character offset) of the caret. With text selected, * this will be the last character actually selected, no matter the direction * of the selection. That is, if the user clicks and drags to select lines * 7 up to 4, then the caret position will be somewhere on line four. */ public int getCaretOffset() { return textarea.getCaretPosition(); } /** * True if some text is currently selected. */ public boolean isSelectionActive() { return textarea.isSelectionActive(); } /** * Get the beginning point of the current selection. */ public int getSelectionStart() { return textarea.getSelectionStart(); } /** * Get the end point of the current selection. */ public int getSelectionStop() { return textarea.getSelectionStop(); } /** * Get text for a specified line. */ public String getLineText(int line) { return textarea.getLineText(line); } /** * Replace the text on a specified line. */ public void setLineText(int line, String what) { startCompoundEdit(); textarea.select(getLineStartOffset(line), getLineStopOffset(line)); textarea.setSelectedText(what); stopCompoundEdit(); } /** * Get character offset for the start of a given line of text. */ public int getLineStartOffset(int line) { return textarea.getLineStartOffset(line); } /** * Get character offset for end of a given line of text. */ public int getLineStopOffset(int line) { return textarea.getLineStopOffset(line); } /** * Get the number of lines in the currently displayed buffer. */ public int getLineCount() { return textarea.getLineCount(); } /** * Use before a manipulating text to group editing operations together * as a single undo. Use stopCompoundEdit() once finished. */ public void startCompoundEdit() { // Call endTextEditHistory() before starting a new CompoundEdit, // because there's a timer that's possibly set off for 3 seconds after // which endTextEditHistory() is called, which means that things get // messed up. Hence, manually call this method so that auto-format gets // undone in one fell swoop if the user calls auto-formats within 3 // seconds of typing in the last character. Then start a new compound // edit so that the auto-format can be undone in one go. // https://github.com/processing/processing/issues/3003 endTextEditHistory(); // also calls stopCompoundEdit() //stopCompoundEdit(); compoundEdit = new CompoundEdit(); caretUndoStack.push(textarea.getCaretPosition()); caretRedoStack.clear(); } /** * Use with startCompoundEdit() to group edit operations in a single undo. */ public void stopCompoundEdit() { if (compoundEdit != null) { compoundEdit.end(); undo.addEdit(compoundEdit); undoAction.updateUndoState(); redoAction.updateRedoState(); compoundEdit = null; } } public int getScrollPosition() { return textarea.getVerticalScrollPosition(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Switch between tabs, this swaps out the Document object * that's currently being manipulated. */ public void setCode(SketchCode code) { SyntaxDocument document = (SyntaxDocument) code.getDocument(); if (document == null) { // this document not yet inited document = new SyntaxDocument() { @Override public void beginCompoundEdit() { if (compoundEdit == null) startCompoundEdit(); super.beginCompoundEdit(); } @Override public void endCompoundEdit() { stopCompoundEdit(); super.endCompoundEdit(); } }; code.setDocument(document); // turn on syntax highlighting document.setTokenMarker(mode.getTokenMarker(code)); // insert the program text into the document object try { document.insertString(0, code.getProgram(), null); } catch (BadLocationException bl) { bl.printStackTrace(); } // set up this guy's own undo manager // code.undo = new UndoManager(); document.addDocumentListener(new DocumentListener() { public void removeUpdate(DocumentEvent e) { if (isInserting && isDirectEdit() && !textarea.isOverwriteEnabled()) { endTextEditHistory(); } isInserting = false; } public void insertUpdate(DocumentEvent e) { if (!isInserting && !textarea.isOverwriteEnabled() && isDirectEdit()) { endTextEditHistory(); } if (!textarea.isOverwriteEnabled()) { isInserting = true; } } public void changedUpdate(DocumentEvent e) { endTextEditHistory(); } }); // connect the undo listener to the editor document.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { // if an edit is in progress, reset the timer if (endUndoEvent != null) { endUndoEvent.cancel(); endUndoEvent = null; startTimerEvent(); } // if this edit is just getting started, create a compound edit if (compoundEdit == null) { startCompoundEdit(); startTimerEvent(); } compoundEdit.addEdit(e.getEdit()); undoAction.updateUndoState(); redoAction.updateRedoState(); } }); } // update the document object that's in use textarea.setDocument(document, code.getSelectionStart(), code.getSelectionStop(), code.getScrollPosition()); // textarea.requestFocus(); // get the caret blinking textarea.requestFocusInWindow(); // required for caret blinking this.undo = code.getUndo(); undoAction.updateUndoState(); redoAction.updateRedoState(); } /** * @return true if the text is being edited from direct input from typing and * not shortcuts that manipulate text */ boolean isDirectEdit() { return endUndoEvent != null; } void startTimerEvent() { endUndoEvent = new TimerTask() { public void run() { EventQueue.invokeLater(Editor.this::endTextEditHistory); } }; timer.schedule(endUndoEvent, 3000); // let the gc eat the cancelled events timer.purge(); } void endTextEditHistory() { if (endUndoEvent != null) { endUndoEvent.cancel(); endUndoEvent = null; } stopCompoundEdit(); } public void removeNotify() { timer.cancel(); super.removeNotify(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Implements Edit &rarr; Cut. */ public void handleCut() { textarea.cut(); sketch.setModified(true); } /** * Implements Edit &rarr; Copy. */ public void handleCopy() { textarea.copy(); } /** * Implements Edit &rarr; Copy as HTML. */ public void handleCopyAsHTML() { textarea.copyAsHTML(); statusNotice(Language.text("editor.status.copy_as_html")); } /** * Implements Edit &rarr; Paste. */ public void handlePaste() { textarea.paste(); sketch.setModified(true); } /** * Implements Edit &rarr; Select All. */ public void handleSelectAll() { textarea.selectAll(); } // /** // * @param moveUp // * true to swap the selected lines with the line above, false to swap // * with the line beneath // */ /* public void handleMoveLines(boolean moveUp) { startCompoundEdit(); int startLine = textarea.getSelectionStartLine(); int stopLine = textarea.getSelectionStopLine(); // if more than one line is selected and none of the characters of the end // line are selected, don't move that line if (startLine != stopLine && textarea.getSelectionStop() == textarea.getLineStartOffset(stopLine)) stopLine--; int replacedLine = moveUp ? startLine - 1 : stopLine + 1; if (replacedLine < 0 || replacedLine >= textarea.getLineCount()) return; final String source = getText(); int replaceStart = textarea.getLineStartOffset(replacedLine); int replaceEnd = textarea.getLineStopOffset(replacedLine); if (replaceEnd == source.length() + 1) replaceEnd--; int selectionStart = textarea.getLineStartOffset(startLine); int selectionEnd = textarea.getLineStopOffset(stopLine); if (selectionEnd == source.length() + 1) selectionEnd--; String replacedText = source.substring(replaceStart, replaceEnd); String selectedText = source.substring(selectionStart, selectionEnd); if (replacedLine == textarea.getLineCount() - 1) { replacedText += "\n"; selectedText = selectedText.substring(0, selectedText.length() - 1); } else if (stopLine == textarea.getLineCount() - 1) { selectedText += "\n"; replacedText = replacedText.substring(0, replacedText.length() - 1); } int newSelectionStart, newSelectionEnd; if (moveUp) { // Change the selection, then change the line above textarea.select(selectionStart, selectionEnd); textarea.setSelectedText(replacedText); textarea.select(replaceStart, replaceEnd); textarea.setSelectedText(selectedText); newSelectionStart = textarea.getLineStartOffset(startLine - 1); newSelectionEnd = textarea.getLineStopOffset(stopLine - 1) - 1; } else { // Change the line beneath, then change the selection textarea.select(replaceStart, replaceEnd); textarea.setSelectedText(selectedText); textarea.select(selectionStart, selectionEnd); textarea.setSelectedText(replacedText); newSelectionStart = textarea.getLineStartOffset(startLine + 1); newSelectionEnd = textarea.getLineStopOffset(stopLine + 1) - 1; } textarea.select(newSelectionStart, newSelectionEnd); stopCompoundEdit(); } */ /* public void handleDeleteLines() { int startLine = textarea.getSelectionStartLine(); int stopLine = textarea.getSelectionStopLine(); int start = textarea.getLineStartOffset(startLine); int end = textarea.getLineStopOffset(stopLine); if (end == getText().length() + 1) end--; textarea.select(start, end); textarea.setSelectedText(""); } */ public void handleAutoFormat() { final String source = getText(); try { final String formattedText = createFormatter().format(source); // save current (rough) selection point int selectionEnd = getSelectionStop(); // boolean wasVisible = // textarea.getSelectionStopLine() >= textarea.getFirstLine() && // textarea.getSelectionStopLine() < textarea.getLastLine(); // make sure the caret would be past the end of the text if (formattedText.length() < selectionEnd - 1) { selectionEnd = formattedText.length() - 1; } if (formattedText.equals(source)) { statusNotice(Language.text("editor.status.autoformat.no_changes")); } else { // replace with new bootiful text startCompoundEdit(); // selectionEnd hopefully at least in the neighborhood int scrollPos = textarea.getVerticalScrollPosition(); textarea.setText(formattedText); setSelection(selectionEnd, selectionEnd); // Put the scrollbar position back, otherwise it jumps on each format. // Since we're not doing a good job of maintaining position anyway, // a more complicated workaround here is fairly pointless. // http://code.google.com/p/processing/issues/detail?id=1533 if (scrollPos != textarea.getVerticalScrollPosition()) { textarea.setVerticalScrollPosition(scrollPos); } stopCompoundEdit(); sketch.setModified(true); statusNotice(Language.text("editor.status.autoformat.finished")); } } catch (final Exception e) { statusError(e); } } abstract public String getCommentPrefix(); protected void handleCommentUncomment() { // log("Entering handleCommentUncomment()"); startCompoundEdit(); String prefix = getCommentPrefix(); int prefixLen = prefix.length(); int startLine = textarea.getSelectionStartLine(); int stopLine = textarea.getSelectionStopLine(); int lastLineStart = textarea.getLineStartOffset(stopLine); int selectionStop = textarea.getSelectionStop(); // If the selection ends at the beginning of the last line, // then don't (un)comment that line. if (selectionStop == lastLineStart) { // Though if there's no selection, don't do that if (textarea.isSelectionActive()) { stopLine--; } } // If the text is empty, ignore the user. // Also ensure that all lines are commented (not just the first) // when determining whether to comment or uncomment. boolean commented = true; for (int i = startLine; commented && (i <= stopLine); i++) { String lineText = textarea.getLineText(i).trim(); if (lineText.length() == 0) { continue; //ignore blank lines } commented = lineText.startsWith(prefix); } // log("Commented: " + commented); // This is the min line start offset of the selection, which is added to // all lines while adding a comment. Required when commenting // lines which have uneven whitespaces in the beginning. Makes the // commented lines look more uniform. int lso = Math.abs(textarea.getLineStartNonWhiteSpaceOffset(startLine) - textarea.getLineStartOffset(startLine)); if (!commented) { // get min line start offset of all selected lines for (int line = startLine+1; line <= stopLine; line++) { String lineText = textarea.getLineText(line); if (lineText.trim().length() == 0) { continue; //ignore blank lines } int so = Math.abs(textarea.getLineStartNonWhiteSpaceOffset(line) - textarea.getLineStartOffset(line)); lso = Math.min(lso, so); } } for (int line = startLine; line <= stopLine; line++) { int location = textarea.getLineStartNonWhiteSpaceOffset(line); String lineText = textarea.getLineText(line); if (lineText.trim().length() == 0) continue; //ignore blank lines if (commented) { // remove a comment textarea.select(location, location + prefixLen); textarea.setSelectedText(""); } else { // add a comment location = textarea.getLineStartOffset(line) + lso; textarea.select(location, location); textarea.setSelectedText(prefix); } } // Subtract one from the end, otherwise selects past the current line. // (Which causes subsequent calls to keep expanding the selection) textarea.select(textarea.getLineStartOffset(startLine), textarea.getLineStopOffset(stopLine) - 1); stopCompoundEdit(); sketch.setModified(true); } public void handleIndent() { handleIndentOutdent(true); } public void handleOutdent() { handleIndentOutdent(false); } public void handleIndentOutdent(boolean indent) { int tabSize = Preferences.getInteger("editor.tabs.size"); String tabString = Editor.EMPTY.substring(0, tabSize); startCompoundEdit(); int startLine = textarea.getSelectionStartLine(); int stopLine = textarea.getSelectionStopLine(); // If the selection ends at the beginning of the last line, // then don't (un)comment that line. int lastLineStart = textarea.getLineStartOffset(stopLine); int selectionStop = textarea.getSelectionStop(); if (selectionStop == lastLineStart) { // Though if there's no selection, don't do that if (textarea.isSelectionActive()) { stopLine--; } } for (int line = startLine; line <= stopLine; line++) { int location = textarea.getLineStartOffset(line); if (indent) { textarea.select(location, location); textarea.setSelectedText(tabString); } else { // outdent int last = Math.min(location + tabSize, textarea.getDocumentLength()); textarea.select(location, last); // Don't eat code if it's not indented if (tabString.equals(textarea.getSelectedText())) { textarea.setSelectedText(""); } } } // Subtract one from the end, otherwise selects past the current line. // (Which causes subsequent calls to keep expanding the selection) textarea.select(textarea.getLineStartOffset(startLine), textarea.getLineStopOffset(stopLine) - 1); stopCompoundEdit(); sketch.setModified(true); } static public boolean checkParen(char[] array, int index, int stop) { // boolean paren = false; // int stepper = i + 1; // while (stepper < mlength) { // if (array[stepper] == '(') { // paren = true; // break; // } // stepper++; // } while (index < stop) { // if (array[index] == '(') { // return true; // } else if (!Character.isWhitespace(array[index])) { // return false; // } switch (array[index]) { case '(': return true; case ' ': case '\t': case '\n': case '\r': index++; break; default: // System.out.println("defaulting because " + array[index] + " " + PApplet.hex(array[index])); return false; } } // System.out.println("exiting " + new String(array, index, stop - index)); return false; } protected boolean functionable(char c) { return (c == '_') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } /** * Check the current selection for reference. If no selection is active, * expand the current selection. * @return */ protected String referenceCheck(boolean selectIfFound) { int start = textarea.getSelectionStart(); int stop = textarea.getSelectionStop(); if (stop < start) { int temp = stop; stop = start; start = temp; } char[] c = textarea.getText().toCharArray(); // System.out.println("checking reference"); if (start == stop) { while (start > 0 && functionable(c[start - 1])) { start--; } while (stop < c.length && functionable(c[stop])) { stop++; } // System.out.println("start is stop"); } String text = new String(c, start, stop - start).trim(); // System.out.println(" reference piece is '" + text + "'"); if (checkParen(c, stop, c.length)) { text += "_"; } String ref = mode.lookupReference(text); if (selectIfFound) { textarea.select(start, stop); } return ref; } protected void handleFindReference() { String ref = referenceCheck(true); if (ref != null) { showReference(ref + ".html"); } else { String text = textarea.getSelectedText(); if (text == null) { statusNotice(Language.text("editor.status.find_reference.select_word_first")); } else { statusNotice(Language.interpolate("editor.status.find_reference.not_available", text.trim())); } } } /* protected void handleFindReference() { String text = textarea.getSelectedText().trim(); if (text.length() == 0) { statusNotice("First select a word to find in the reference."); } else { char[] c = textarea.getText().toCharArray(); int after = Math.max(textarea.getSelectionStart(), textarea.getSelectionStop()); if (checkParen(c, after, c.length)) { text += "_"; System.out.println("looking up ref for " + text); } String referenceFile = mode.lookupReference(text); System.out.println("reference file is " + referenceFile); if (referenceFile == null) { statusNotice("No reference available for \"" + text + "\""); } else { showReference(referenceFile + ".html"); } } } protected void handleFindReference() { String text = textarea.getSelectedText().trim(); if (text.length() == 0) { statusNotice("First select a word to find in the reference."); } else { String referenceFile = mode.lookupReference(text); //System.out.println("reference file is " + referenceFile); if (referenceFile == null) { statusNotice("No reference available for \"" + text + "\""); } else { showReference(referenceFile + ".html"); } } } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Set the location of the sketch run window. Used by Runner to update the * Editor about window drag events while the sketch is running. */ public void setSketchLocation(Point p) { sketchWindowLocation = p; } /** * Get the last location of the sketch's run window. Used by Runner to make * the window show up in the same location as when it was last closed. */ public Point getSketchLocation() { return sketchWindowLocation; } // public void internalCloseRunner() { // mode.internalCloseRunner(this); // } public boolean isDebuggerEnabled() { return false; } public void toggleBreakpoint(int lineIndex) { } /** * Check if the sketch is modified and ask user to save changes. * @return false if canceling the close/quit operation */ public boolean checkModified() { if (!sketch.isModified()) return true; // As of Processing 1.0.10, this always happens immediately. // http://dev.processing.org/bugs/show_bug.cgi?id=1456 // With Java 7u40 on OS X, need to bring the window forward. toFront(); if (!Platform.isMacOS()) { String prompt = Language.interpolate("close.unsaved_changes", sketch.getName()); int result = JOptionPane.showConfirmDialog(this, prompt, Language.text("menu.file.close"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { return handleSave(true); } else if (result == JOptionPane.NO_OPTION) { return true; // ok to continue } else if (result == JOptionPane.CANCEL_OPTION || result == JOptionPane.CLOSED_OPTION) { return false; } else { throw new IllegalStateException(); } } else { // This code is disabled unless Java 1.5 is being used on Mac OS X // because of a Java bug that prevents the initial value of the // dialog from being set properly (at least on my MacBook Pro). // The bug causes the "Don't Save" option to be the highlighted, // blinking, default. This sucks. But I'll tell you what doesn't // suck--workarounds for the Mac and Apple's snobby attitude about it! // I think it's nifty that they treat their developers like dirt. // Pane formatting adapted from the quaqua guide // http://www.randelshofer.ch/quaqua/guide/joptionpane.html JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>" + Language.interpolate("save.title", sketch.getName()) + "</b>" + "<p>" + Language.text("save.hint") + "</p>", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { Language.text("save.btn.save"), Language.text("prompt.cancel"), Language.text("save.btn.dont_save") }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", Integer.valueOf(2)); JDialog dialog = pane.createDialog(this, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { // save (and close/quit) return handleSave(true); } else if (result == options[2]) { // don't save (still close/quit) return true; } else { // cancel? return false; } } } /** * Second stage of open, occurs after having checked to see if the * modifications (if any) to the previous sketch need to be saved. * Because this method is called in Editor's constructor, a subclass * shouldn't rely on any of its variables being initialized already. */ protected void handleOpenInternal(String path) throws EditorException { // check to make sure that this .pde file is // in a folder of the same name final File file = new File(path); final File parentFile = new File(file.getParent()); final String parentName = parentFile.getName(); final String defaultName = parentName + "." + mode.getDefaultExtension(); final File altFile = new File(file.getParent(), defaultName); if (defaultName.equals(file.getName())) { // no beef with this guy } else if (altFile.exists()) { // The user selected a source file from the same sketch, // but open the file with the default extension instead. path = altFile.getAbsolutePath(); } else if (!mode.canEdit(file)) { final String modeName = mode.getTitle().equals("Java") ? "Processing" : (mode.getTitle() + " Mode"); throw new EditorException(modeName + " can only open its own sketches\n" + "and other files ending in " + mode.getDefaultExtension()); } else { final String properParent = file.getName().substring(0, file.getName().lastIndexOf('.')); Object[] options = { Language.text("prompt.ok"), Language.text("prompt.cancel") }; String prompt = "The file \"" + file.getName() + "\" needs to be inside\n" + "a sketch folder named \"" + properParent + "\".\n" + "Create this folder, move the file, and continue?"; int result = JOptionPane.showOptionDialog(this, prompt, "Moving", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { // create properly named folder File properFolder = new File(file.getParent(), properParent); if (properFolder.exists()) { throw new EditorException("A folder named \"" + properParent + "\" " + "already exists. Can't open sketch."); } if (!properFolder.mkdirs()) { throw new EditorException("Could not create the sketch folder."); } // copy the sketch inside File properPdeFile = new File(properFolder, file.getName()); File origPdeFile = new File(path); try { Util.copyFile(origPdeFile, properPdeFile); } catch (IOException e) { throw new EditorException("Could not copy to a proper location.", e); } // remove the original file, so user doesn't get confused origPdeFile.delete(); // update with the new path path = properPdeFile.getAbsolutePath(); } else { //if (result == JOptionPane.NO_OPTION) { // Catch all other cases, including Cancel or ESC //return false; throw new EditorException(); } } try { sketch = new Sketch(path, this); } catch (IOException e) { throw new EditorException("Could not create the sketch.", e); } header.rebuild(); updateTitle(); // Disable untitled setting from previous document, if any // untitled = false; // Store information on who's open and running // (in case there's a crash or something that can't be recovered) // TODO this probably need not be here because of the Recent menu, right? Preferences.save(); } /** * Set the title of the PDE window based on the current sketch, i.e. * something like "sketch_070752a - Processing 0126" */ public void updateTitle() { setTitle(sketch.getName() + " | Processing " + Base.getVersionName()); if (!sketch.isUntitled()) { // set current file for OS X so that cmd-click in title bar works File sketchFile = sketch.getMainFile(); getRootPane().putClientProperty("Window.documentFile", sketchFile); } else { // per other applications, don't set this until the file has been saved getRootPane().putClientProperty("Window.documentFile", null); } // toolbar.setText(sketch.getName()); } /** * Actually handle the save command. If 'immediately' is set to false, * this will happen in another thread so that the message area * will update and the save button will stay highlighted while the * save is happening. If 'immediately' is true, then it will happen * immediately. This is used during a quit, because invokeLater() * won't run properly while a quit is happening. This fixes * <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=276">Bug 276</A>. */ public boolean handleSave(boolean immediately) { // handleStop(); // 0136 if (sketch.isUntitled()) { return handleSaveAs(); // need to get the name, user might also cancel here } else if (immediately) { handleSaveImpl(); } else { EventQueue.invokeLater(new Runnable() { public void run() { handleSaveImpl(); } }); } return true; } protected void handleSaveImpl() { statusNotice(Language.text("editor.status.saving")); try { if (sketch.save()) { statusNotice(Language.text("editor.status.saving.done")); } else { statusEmpty(); } } catch (Exception e) { // show the error as a message in the window statusError(e); // zero out the current action, // so that checkModified2 will just do nothing //checkModifiedMode = 0; // this is used when another operation calls a save } } public boolean handleSaveAs() { statusNotice(Language.text("editor.status.saving")); try { if (sketch.saveAs()) { //statusNotice(Language.text("editor.status.saving.done")); // status is now printed from Sketch so that "Done Saving." // is only printed after Save As when progress bar is shown. } else { statusNotice(Language.text("editor.status.saving.canceled")); return false; } } catch (Exception e) { // show the error as a message in the window statusError(e); } return true; } /* public void handleSaveAs() { statusNotice(Language.text("editor.status.saving")); sketch.saveAs(); } public void handleSaveAsSuccess() { statusNotice(Language.text("editor.status.saving.done")); } public void handleSaveAsCanceled() { statusNotice(Language.text("editor.status.saving.canceled")); } public void handleSaveAsError(Exception e) { statusError(e); } */ /** * Handler for File &rarr; Page Setup. */ public void handlePageSetup() { //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat == null) { pageFormat = printerJob.defaultPage(); } pageFormat = printerJob.pageDialog(pageFormat); //System.out.println("page format is " + pageFormat); } /** * Handler for File &rarr; Print. */ public void handlePrint() { statusNotice(Language.text("editor.status.printing")); StringBuilder html = new StringBuilder("<html><body>"); for (SketchCode tab : sketch.getCode()) { html.append("<b>" + tab.getPrettyName() + "</b><br>"); html.append(textarea.getTextAsHtml((SyntaxDocument)tab.getDocument())); html.append("<br>"); } html.setLength(html.length() - 4); // Don't want last <br>. html.append("</body></html>"); JTextPane jtp = new JTextPane(); // Needed for good line wrapping; otherwise one very long word breaks // wrapping for the whole document. jtp.setEditorKit(new HTMLEditorKit() { public ViewFactory getViewFactory() { return new HTMLFactory() { public View create(Element e) { View v = super.create(e); if (!(v instanceof javax.swing.text.html.ParagraphView)) return v; else return new javax.swing.text.html.ParagraphView(e) { protected SizeRequirements calculateMinorAxisRequirements( int axis, SizeRequirements r) { r = super.calculateMinorAxisRequirements(axis, r); r.minimum = 1; return r; } }; } }; } }); jtp.setFont(new Font(Preferences.get("editor.font.family"), Font.PLAIN, 10)); jtp.setText(html.toString().replace("\n", "<br>") // Not in a <pre>. .replaceAll("(?<!&nbsp;)&nbsp;", " ")); // Allow line wrap. //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat != null) { //System.out.println("setting page format " + pageFormat); printerJob.setPrintable(jtp.getPrintable(null, null), pageFormat); } else { printerJob.setPrintable(jtp.getPrintable(null, null)); } // set the name of the job to the code name printerJob.setJobName(sketch.getCurrentCode().getPrettyName()); if (printerJob.printDialog()) { try { printerJob.print(); statusNotice(Language.text("editor.status.printing.done")); } catch (PrinterException pe) { statusError(Language.text("editor.status.printing.error")); pe.printStackTrace(); } } else { statusNotice(Language.text("editor.status.printing.canceled")); } //printerJob = null; // clear this out? } /** * Grab current contents of the sketch window, advance the console, * stop any other running sketches... not in that order. * It's essential that this function be called by any Mode subclass, * otherwise current edits may not be stored for getProgram(). */ public void prepareRun() { internalCloseRunner(); statusEmpty(); // do this to advance/clear the terminal window / dos prompt / etc for (int i = 0; i < 10; i++) System.out.println(); // clear the console on each run, unless the user doesn't want to if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } // make sure the user didn't hide the sketch folder sketch.ensureExistence(); // make sure any edits have been stored //current.setProgram(editor.getText()); // Go through all tabs; Replace All, Rename or Undo could have changed them for (SketchCode sc : sketch.getCode()) { if (sc.getDocument() != null) { try { sc.setProgram(sc.getDocumentText()); } catch (BadLocationException e) { } } } // // if an external editor is being used, need to grab the // // latest version of the code from the file. // if (Preferences.getBoolean("editor.external")) { // sketch.reload(); // } } /** * Halt the current runner for whatever reason. Might be the VM dying, * the window closing, an error... */ abstract public void internalCloseRunner(); abstract public void deactivateRun(); // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . public ErrorTable getErrorTable() { return errorTable; } /** * Called by ErrorTable when a row is selected. Action taken is specific * to each Mode, based on the object passed in. */ public void errorTableClick(Object item) { highlight((Problem) item); } public void errorTableDoubleClick(Object item) { } /** * Handle whether the tiny red error indicator is shown near * the error button at the bottom of the PDE */ public void updateErrorToggle(boolean hasErrors) { if (errorTable != null) { footer.setNotification(errorTable.getParent(), hasErrors); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Show an error in the status bar. */ public void statusError(String what) { status.error(what); //new Exception("deactivating RUN").printStackTrace(); // toolbar.deactivate(EditorToolbar.RUN); } /** * Show an exception in the editor status bar. */ public void statusError(Exception e) { e.printStackTrace(); // if (e == null) { // System.err.println("Editor.statusError() was passed a null exception."); // return; // } if (e instanceof SketchException) { SketchException re = (SketchException) e; // Make sure something is printed into the console // Status bar is volatile if (!re.isStackTraceEnabled()) { System.err.println(re.getMessage()); } // Move the cursor to the line before updating the status bar, otherwise // status message might get hidden by a potential message caused by moving // the cursor to a line with warning in it if (re.hasCodeIndex()) { sketch.setCurrentCode(re.getCodeIndex()); } if (re.hasCodeLine()) { int line = re.getCodeLine(); // subtract one from the end so that the \n ain't included if (line >= textarea.getLineCount()) { // The error is at the end of this current chunk of code, // so the last line needs to be selected. line = textarea.getLineCount() - 1; if (textarea.getLineText(line).length() == 0) { // The last line may be zero length, meaning nothing to select. // If so, back up one more line. line--; } } if (line < 0 || line >= textarea.getLineCount()) { System.err.println("Bad error line: " + line); } else { textarea.select(textarea.getLineStartOffset(line), textarea.getLineStopOffset(line) - 1); } } } // Since this will catch all Exception types, spend some time figuring // out which kind and try to give a better error message to the user. String mess = e.getMessage(); if (mess != null) { String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } // The phrase "RuntimeException" isn't useful for most users String rxString = "RuntimeException: "; if (mess.startsWith(rxString)) { mess = mess.substring(rxString.length()); } // This is just confusing for most PDE users (save it for Eclipse users) String illString = "IllegalArgumentException: "; if (mess.startsWith(illString)) { mess = mess.substring(illString.length()); } // This is confusing and common with the size() and fullScreen() changes String illState = "IllegalStateException: "; if (mess.startsWith(illState)) { mess = mess.substring(illState.length()); } statusError(mess); } // e.printStackTrace(); } /** * Show a notice message in the editor status bar. */ public void statusNotice(String msg) { if (msg == null) { new IllegalArgumentException("This code called statusNotice(null)").printStackTrace(); msg = ""; } status.notice(msg); } public void clearNotice(String msg) { if (status.message.equals(msg)) { statusEmpty(); } } /** * Returns the current notice message in the editor status bar. */ public String getStatusMessage() { return status.message; } /** * Returns the current notice message in the editor status bar. */ public int getStatusMode() { return status.mode; } // /** // * Returns the current mode of the editor status bar: NOTICE, ERR or EDIT. // */ // public int getStatusMode() { // return status.mode; // } /** * Clear the status area. */ public void statusEmpty() { statusNotice(EMPTY); } public void statusMessage(String message, int type) { if (EventQueue.isDispatchThread()) { status.message(message, type); } else { EventQueue.invokeLater(() -> statusMessage(message, type)); } } public void startIndeterminate() { status.startIndeterminate(); } public void stopIndeterminate() { status.stopIndeterminate(); } public void statusHalt() { // stop called by someone else } public boolean isHalted() { return false; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . public void setProblemList(List<Problem> problems) { this.problems = problems; boolean hasErrors = problems.stream().anyMatch(Problem::isError); updateErrorTable(problems); errorColumn.updateErrorPoints(problems); textarea.repaint(); updateErrorToggle(hasErrors); updateEditorStatus(); } /** * Updates the error table in the Error Window. */ public void updateErrorTable(List<Problem> problems) { if (errorTable != null) { errorTable.clearRows(); for (Problem p : problems) { String message = p.getMessage(); errorTable.addRow(p, message, sketch.getCode(p.getTabIndex()).getPrettyName(), Integer.toString(p.getLineNumber() + 1)); // Added +1 because lineNumbers internally are 0-indexed } } } public void highlight(Problem p) { if (p != null) { highlight(p.getTabIndex(), p.getStartOffset(), p.getStopOffset()); } } public void highlight(int tabIndex, int startOffset, int stopOffset) { // Switch to tab toFront(); sketch.setCurrentCode(tabIndex); // Make sure offsets are in bounds int length = textarea.getDocumentLength(); startOffset = PApplet.constrain(startOffset, 0, length); stopOffset = PApplet.constrain(stopOffset, 0, length); // Highlight the code textarea.select(startOffset, stopOffset); // Scroll to error line textarea.scrollToCaret(); repaint(); } public List<Problem> getProblems() { return problems; } /** * Updates editor status bar, depending on whether the caret is on an error * line or not */ public void updateEditorStatus() { Problem problem = findProblem(textarea.getCaretLine()); if (problem != null) { int type = problem.isError() ? EditorStatus.CURSOR_LINE_ERROR : EditorStatus.CURSOR_LINE_WARNING; statusMessage(problem.getMessage(), type); } else { switch (getStatusMode()) { case EditorStatus.CURSOR_LINE_ERROR: case EditorStatus.CURSOR_LINE_WARNING: statusEmpty(); break; } } } /** * @return the Problem for the most relevant error or warning on 'line', * defaults to the first error, if there are no errors first warning. */ protected Problem findProblem(int line) { List<Problem> problems = findProblems(line); for (Problem p : problems) { if (p.isError()) return p; } return problems.isEmpty() ? null : problems.get(0); } public List<Problem> findProblems(int line) { int currentTab = getSketch().getCurrentCodeIndex(); return problems.stream() .filter(p -> p.getTabIndex() == currentTab) .filter(p -> { int pStartLine = p.getLineNumber(); int pEndOffset = p.getStopOffset(); int pEndLine = textarea.getLineOfOffset(pEndOffset); return line >= pStartLine && line <= pEndLine; }) .collect(Collectors.toList()); } public void repaintErrorBar() { errorColumn.repaint(); } public void showConsole() { footer.setPanel(console); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static Font font; static Color textColor; static Color bgColorWarning; static Color bgColorError; public void statusToolTip(JComponent comp, String message, boolean error) { if (font == null) { font = Toolkit.getSansFont(Toolkit.zoom(9), Font.PLAIN); textColor = mode.getColor("errors.selection.fgcolor"); bgColorWarning = mode.getColor("errors.selection.warning.bgcolor"); bgColorError = mode.getColor("errors.selection.error.bgcolor"); } Color bgColor = error ? bgColorError : bgColorWarning; int m = Toolkit.zoom(3); String css = String.format("margin: %d %d %d %d; ", -m, -m, -m, -m) + String.format("padding: %d %d %d %d; ", m, m, m, m) + "background: #" + PApplet.hex(bgColor.getRGB(), 8).substring(2) + ";" + "font-family: " + font.getFontName() + ", sans-serif;" + "font-size: " + font.getSize() + "px;"; String content = "<html> <div style='" + css + "'>" + message + "</div> </html>"; comp.setToolTipText(content); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Returns the edit popup menu. */ class TextAreaPopup extends JPopupMenu { JMenuItem cutItem, copyItem, discourseItem, pasteItem, referenceItem; public TextAreaPopup() { JMenuItem item; cutItem = new JMenuItem(Language.text("menu.edit.cut")); cutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCut(); } }); this.add(cutItem); copyItem = new JMenuItem(Language.text("menu.edit.copy")); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCopy(); } }); this.add(copyItem); discourseItem = new JMenuItem(Language.text("menu.edit.copy_as_html")); discourseItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCopyAsHTML(); } }); this.add(discourseItem); pasteItem = new JMenuItem(Language.text("menu.edit.paste")); pasteItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePaste(); } }); this.add(pasteItem); item = new JMenuItem(Language.text("menu.edit.select_all")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSelectAll(); } }); this.add(item); this.addSeparator(); item = new JMenuItem(Language.text("menu.edit.comment_uncomment")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCommentUncomment(); } }); this.add(item); item = new JMenuItem("\u2192 " + Language.text("menu.edit.increase_indent")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(true); } }); this.add(item); item = new JMenuItem("\u2190 " + Language.text("menu.edit.decrease_indent")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(false); } }); this.add(item); this.addSeparator(); referenceItem = new JMenuItem(Language.text("find_in_reference")); referenceItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleFindReference(); } }); this.add(referenceItem); Toolkit.setMenuMnemonics(this); } // if no text is selected, disable copy and cut menu items public void show(Component component, int x, int y) { // if (textarea.isSelectionActive()) { // cutItem.setEnabled(true); // copyItem.setEnabled(true); // discourseItem.setEnabled(true); // //// String sel = textarea.getSelectedText().trim(); //// String referenceFile = mode.lookupReference(sel); //// referenceItem.setEnabled(referenceFile != null); // // } else { // cutItem.setEnabled(false); // copyItem.setEnabled(false); // discourseItem.setEnabled(false); //// referenceItem.setEnabled(false); // } // Centralize the checks for each item at the Action. // boolean active = textarea.isSelectionActive(); cutItem.setEnabled(cutAction.canDo()); copyItem.setEnabled(copyAction.canDo()); discourseItem.setEnabled(copyAsHtmlAction.canDo()); pasteItem.setEnabled(pasteAction.canDo()); referenceItem.setEnabled(referenceCheck(false) != null); super.show(component, x, y); } } }
processing/processing
app/src/processing/app/ui/Editor.java
2,179
/* * Copyright 2017 Darian Sastre [email protected] * 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. * * ************************************************************************ * * This model was created by Hakan Kjellerstrand ([email protected]) */ package com.google.ortools.contrib; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; public class DietMIP { static { System.loadLibrary("jniortools"); } private static MPSolver createSolver(String solverType) { try { return new MPSolver("MIPDiet", MPSolver.OptimizationProblemType.valueOf(solverType)); } catch (java.lang.IllegalArgumentException e) { System.err.println("Bad solver type: " + e); return null; } } private static void solve(String solverType) { MPSolver solver = createSolver(solverType); double infinity = MPSolver.infinity(); int n = 4; // variables number int m = 4; // constraints number int[] price = { 50, 20, 30, 80 }; int[] limits = { 500, 6, 10, 8 }; int[] calories = { 400, 200, 150, 500 }; int[] chocolate = { 3, 2, 0, 0 }; int[] sugar = { 2, 2, 4, 4 }; int[] fat = { 2, 4, 1, 5 }; int[][] values = { calories, chocolate, sugar, fat }; MPVariable[] x = solver.makeIntVarArray(n, 0, 100, "x"); MPObjective objective = solver.objective(); MPConstraint[] targets = new MPConstraint[4]; for (int i = 0; i < n; i++) { objective.setCoefficient(x[i], price[i]); // constraints targets[i] = solver.makeConstraint(limits[i], infinity); for (int j = 0; j < m; j++) { targets[i].setCoefficient(x[j], values[i][j]); } } final MPSolver.ResultStatus resultStatus = solver.solve(); /** printing */ if (resultStatus != MPSolver.ResultStatus.OPTIMAL) { System.err.println("The problem does not have an optimal solution!"); return; } else { System.out.println("Optimal objective value = " + solver.objective().value()); System.out.print("Item quantities: "); System.out.print((int) x[0].solutionValue() + " "); System.out.print((int) x[1].solutionValue() + " "); System.out.print((int) x[2].solutionValue() + " "); System.out.print((int) x[3].solutionValue() + " "); } } public static void main(String[] args) throws Exception { solve("CBC_MIXED_INTEGER_PROGRAMMING"); } }
lucasfcnunes/or-tools
examples/contrib/DietMIP.java
2,180
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2012-19 The Processing Foundation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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.ui; import java.awt.BasicStroke; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.FontFormatException; import java.awt.FontMetrics; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Window; import java.awt.datatransfer.Clipboard; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.image.ImageObserver; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import javax.swing.Action; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JRootPane; import javax.swing.KeyStroke; import javax.swing.border.EmptyBorder; import processing.app.Language; import processing.app.Messages; import processing.app.Platform; import processing.app.Preferences; import processing.app.Util; import processing.core.PApplet; import processing.data.StringList; /** * Utility functions for base that require a java.awt.Toolkit object. These * are broken out from Base as we start moving toward the possibility of the * code running in headless mode. */ public class Toolkit { static final java.awt.Toolkit awtToolkit = java.awt.Toolkit.getDefaultToolkit(); /** Command on Mac OS X, Ctrl on Windows and Linux */ static final int SHORTCUT_KEY_MASK = awtToolkit.getMenuShortcutKeyMask(); /** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */ static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK | SHORTCUT_KEY_MASK; /** Command-Shift on Mac OS X, Ctrl-Shift on Windows and Linux */ static final int SHORTCUT_SHIFT_KEY_MASK = ActionEvent.SHIFT_MASK | SHORTCUT_KEY_MASK; /** Command-W on Mac OS X, Ctrl-W on Windows and Linux */ static public final KeyStroke WINDOW_CLOSE_KEYSTROKE = KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK); static final String BAD_KEYSTROKE = "'%s' is not understood, please re-read the Java reference for KeyStroke"; /** * Standardized width for buttons. Mac OS X 10.3 wants 70 as its default, * Windows XP needs 66, and my Ubuntu machine needs 80+, so 80 seems proper. * This is now stored in the languages file since this may need to be larger * for languages that are consistently wider than English. */ static public int getButtonWidth() { // Made into a method so that calling Toolkit methods doesn't require // the languages to be loaded, and with that, Base initialized completely return zoom(Integer.parseInt(Language.text("preferences.button.width"))); } /** * Return the correct KeyStroke per locale and platform. * Also checks for any additional overrides in preferences.txt. * @param base the localization key for the menu item * (.keystroke and .platform will be added to the end) * @return KeyStroke for base + .keystroke + .platform * (or the value from preferences) or null if none found */ static public KeyStroke getKeyStrokeExt(String base) { String key = base + ".keystroke"; // see if there's an override in preferences.txt String sequence = Preferences.get(key); if (sequence != null) { KeyStroke ks = KeyStroke.getKeyStroke(sequence); if (ks != null) { return ks; // user did good, we're all set } else { System.err.format(BAD_KEYSTROKE, sequence); } } sequence = Language.text(key + "." + Platform.getName()); KeyStroke ks = KeyStroke.getKeyStroke(sequence); if (ks == null) { // this can only happen if user has screwed up their language files System.err.format(BAD_KEYSTROKE, sequence); //return KeyStroke.getKeyStroke(0, 0); // badness } return ks; } /** * Create a menu item and set its KeyStroke by name (so it can be stored * in the language settings or the preferences. Syntax is here: * https://docs.oracle.com/javase/8/docs/api/javax/swing/KeyStroke.html#getKeyStroke-java.lang.String- * @param sequence the name, as outlined by the KeyStroke API * @param fallback what to use if getKeyStroke() comes back null */ static public JMenuItem newJMenuItemExt(String base) { JMenuItem menuItem = new JMenuItem(Language.text(base)); KeyStroke ks = getKeyStrokeExt(base); // will print error if necessary if (ks != null) { menuItem.setAccelerator(ks); } return menuItem; } /** * A software engineer, somewhere, needs to have their abstraction * taken away. Who crafts the sort of API that would require a * five-line helper function just to set the shortcut key for a * menu item? */ static public JMenuItem newJMenuItem(String title, int what) { JMenuItem menuItem = new JMenuItem(title); int modifiers = awtToolkit.getMenuShortcutKeyMask(); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } /** * @param action: use an Action, which sets the title, reaction * and enabled-ness all by itself. */ static public JMenuItem newJMenuItem(Action action, int what) { JMenuItem menuItem = new JMenuItem(action); int modifiers = awtToolkit.getMenuShortcutKeyMask(); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } /** * Like newJMenuItem() but adds shift as a modifier for the shortcut. */ static public JMenuItem newJMenuItemShift(String title, int what) { JMenuItem menuItem = new JMenuItem(title); int modifiers = awtToolkit.getMenuShortcutKeyMask(); modifiers |= ActionEvent.SHIFT_MASK; menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } /** * Like newJMenuItem() but adds shift as a modifier for the shortcut. */ static public JMenuItem newJMenuItemShift(Action action, int what) { JMenuItem menuItem = new JMenuItem(action); int modifiers = awtToolkit.getMenuShortcutKeyMask(); modifiers |= ActionEvent.SHIFT_MASK; menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } /** * Same as newJMenuItem(), but adds the ALT (on Linux and Windows) * or OPTION (on Mac OS X) key as a modifier. This function should almost * never be used, because it's bad for non-US keyboards that use ALT in * strange and wondrous ways. */ static public JMenuItem newJMenuItemAlt(String title, int what) { JMenuItem menuItem = new JMenuItem(title); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK)); return menuItem; } static public JCheckBoxMenuItem newJCheckBoxMenuItem(String title, int what) { JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(title); int modifiers = awtToolkit.getMenuShortcutKeyMask(); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } static public void addDisabledItem(JMenu menu, String title) { JMenuItem item = new JMenuItem(title); item.setEnabled(false); menu.add(item); } /** * Removes all mnemonics, then sets a mnemonic for each menu and menu item * recursively by these rules: * <ol> * <li> It tries to assign one of <a href="http://techbase.kde.org/Projects/Usability/HIG/Keyboard_Accelerators"> * KDE's defaults</a>.</li> * <li> Failing that, it loops through the first letter of each word, where a word * is a block of Unicode "alphabetical" chars, looking for an upper-case ASCII mnemonic * that is not taken. This is to try to be relevant, by using a letter well-associated * with the command. (MS guidelines) </li> * <li> Ditto, but with lowercase. </li> * <li> Next, it tries the second ASCII character, if its width &gt;= half the width of * 'A'. </li> * <li> If the first letters are all taken/non-ASCII, then it loops through the * ASCII letters in the item, widest to narrowest, seeing if any of them is not taken. * To improve readability, it discriminates against decenders (qypgj), imagining they * have 2/3 their actual width. (MS guidelines: avoid decenders). It also discriminates * against vowels, imagining they have 2/3 their actual width. (MS and Gnome guidelines: * avoid vowels.) </li> * <li>Failing that, it will loop left-to-right for an available digit. This is a last * resort because the normal setMnemonic dislikes them.</li> * <li> If that doesn't work, it doesn't assign a mnemonic. </li> * </ol> * * As a special case, strings starting "sketchbook \u2192 " have that bit ignored * because otherwise the Recent menu looks awful. However, the name <tt>"sketchbook \u2192 * Sketch"</tt>, for example, will have the 'S' of "Sketch" chosen, but the 's' of 'sketchbook * will get underlined. * No letter by an underscore will be assigned. * Disabled on Mac, per Apple guidelines. * <tt>menu</tt> may contain nulls. * * Author: George Bateman. Initial work Myer Nore. * @param menu * A menu, a list of menus or an array of menu items to set mnemonics for. */ static public void setMenuMnemonics(JMenuItem... menu) { if (Platform.isMacOS()) return; if (menu.length == 0) return; // The English is http://techbase.kde.org/Projects/Usability/HIG/Keyboard_Accelerators, // made lowercase. // Nothing but [a-z] except for '&' before mnemonics and regexes for changable text. final String[] kdePreDefStrs = { "&file", "&new", "&open", "open&recent", "&save", "save&as", "saveacop&y", "saveas&template", "savea&ll", "reloa&d", "&print", "printpre&view", "&import", "e&xport", "&closefile", "clos&eallfiles", "&quit", "&edit", "&undo", "re&do", "cu&t", "&copy", "&paste", "&delete", "select&all", "dese&lect", "&find", "find&next", "findpre&vious", "&replace", "&gotoline", "&view", "&newview", "close&allviews", "&splitview", "&removeview", "splitter&orientation", "&horizontal", "&vertical", "view&mode", "&fullscreenmode", "&zoom", "zoom&in", "zoom&out", "zoomtopage&width", "zoomwhole&page", "zoom&factor", "&insert", "&format", "&go", "&up", "&back", "&forward", "&home", "&go", "&previouspage", "&nextpage", "&firstpage", "&lastpage", "read&updocument", "read&downdocument", "&back", "&forward", "&gotopage", "&bookmarks", "&addbookmark", "bookmark&tabsasfolder", "&editbookmarks", "&newbookmarksfolder", "&tools", "&settings", "&toolbars", "configure&shortcuts", "configuretool&bars", "&configure.*", "&help", ".+&handbook", "&whatsthis", "report&bug", "&aboutprocessing", "about&kde", "&beenden", "&suchen", // de "&preferncias", "&sair", // Preferências; pt "&rechercher" }; // fr Pattern[] kdePreDefPats = new Pattern[kdePreDefStrs.length]; for (int i = 0; i < kdePreDefStrs.length; i++) { kdePreDefPats[i] = Pattern.compile(kdePreDefStrs[i].replace("&","")); } final Pattern nonAAlpha = Pattern.compile("[^A-Za-z]"); FontMetrics fmTmp = null; for (JMenuItem m : menu) { if (m != null) { fmTmp = m.getFontMetrics(m.getFont()); break; } } if (fmTmp == null) return; // All null menuitems; would fail. final FontMetrics fm = fmTmp; // Hack for accessing variable in comparator. final Comparator<Character> charComparator = new Comparator<Character>() { char[] baddies = "qypgjaeiouQAEIOU".toCharArray(); public int compare(Character ch1, Character ch2) { // Discriminates against descenders for readability, per MS // Human Interface Guide, and vowels per MS and Gnome. float w1 = fm.charWidth(ch1), w2 = fm.charWidth(ch2); for (char bad : baddies) { if (bad == ch1) w1 *= 0.66f; if (bad == ch2) w2 *= 0.66f; } return (int)Math.signum(w2 - w1); } }; // Holds only [0-9a-z], not uppercase. // Prevents X != x, so "Save" and "Save As" aren't both given 'a'. final List<Character> taken = new ArrayList<>(menu.length); char firstChar; char[] cleanChars; Character[] cleanCharas; // METHOD 1: attempt to assign KDE defaults. for (JMenuItem jmi : menu) { if (jmi == null) continue; if (jmi.getText() == null) continue; jmi.setMnemonic(0); // Reset all mnemonics. String asciiName = nonAAlpha.matcher(jmi.getText()).replaceAll(""); String lAsciiName = asciiName.toLowerCase(); for (int i = 0; i < kdePreDefStrs.length; i++) { if (kdePreDefPats[i].matcher(lAsciiName).matches()) { char mnem = asciiName.charAt(kdePreDefStrs[i].indexOf("&")); jmi.setMnemonic(mnem); jmi.setDisplayedMnemonicIndex(jmi.getText().indexOf(mnem)); taken.add((char)(mnem | 32)); // to lowercase break; } } } // Where KDE defaults fail, use an algorithm. algorithmicAssignment: for (JMenuItem jmi : menu) { if (jmi == null) continue; if (jmi.getText() == null) continue; if (jmi.getMnemonic() != 0) continue; // Already assigned. // The string can't be made lower-case as that would spoil // the width comparison. String cleanString = jmi.getText(); if (cleanString.startsWith("sketchbook \u2192 ")) cleanString = cleanString.substring(13); if (cleanString.length() == 0) continue; // First, ban letters by underscores. final List<Character> banned = new ArrayList<>(); for (int i = 0; i < cleanString.length(); i++) { if (cleanString.charAt(i) == '_') { if (i > 0) banned.add(Character.toLowerCase(cleanString.charAt(i - 1))); if (i + 1 < cleanString.length()) banned.add(Character.toLowerCase(cleanString.charAt(i + 1))); } } // METHOD 2: Uppercase starts of words. // Splitting into blocks of ASCII letters wouldn't work // because there could be non-ASCII letters in a word. for (String wd : cleanString.split("[^\\p{IsAlphabetic}]")) { if (wd.length() == 0) continue; firstChar = wd.charAt(0); if (taken.contains(Character.toLowerCase(firstChar))) continue; if (banned.contains(Character.toLowerCase(firstChar))) continue; if ('A' <= firstChar && firstChar <= 'Z') { jmi.setMnemonic(firstChar); jmi.setDisplayedMnemonicIndex(jmi.getText().indexOf(firstChar)); taken.add((char)(firstChar | 32)); // tolowercase continue algorithmicAssignment; } } // METHOD 3: Lowercase starts of words. for (String wd : cleanString.split("[^\\p{IsAlphabetic}]")) { if (wd.length() == 0) continue; firstChar = wd.charAt(0); if (taken.contains(Character.toLowerCase(firstChar))) continue; if (banned.contains(Character.toLowerCase(firstChar))) continue; if ('a' <= firstChar && firstChar <= 'z') { jmi.setMnemonic(firstChar); jmi.setDisplayedMnemonicIndex(jmi.getText().indexOf(firstChar)); taken.add(firstChar); // is lowercase continue algorithmicAssignment; } } // METHOD 4: Second wide-enough ASCII letter. cleanString = nonAAlpha.matcher(jmi.getText()).replaceAll(""); if (cleanString.length() >= 2) { char ascii2nd = cleanString.charAt(1); if (!taken.contains((char)(ascii2nd|32)) && !banned.contains((char)(ascii2nd|32)) && fm.charWidth('A') <= 2*fm.charWidth(ascii2nd)) { jmi.setMnemonic(ascii2nd); jmi.setDisplayedMnemonicIndex(jmi.getText().indexOf(ascii2nd)); taken.add((char)(ascii2nd|32)); continue algorithmicAssignment; } } // METHOD 5: charComparator over all ASCII letters. cleanChars = cleanString.toCharArray(); cleanCharas = new Character[cleanChars.length]; for (int i = 0; i < cleanChars.length; i++) { cleanCharas[i] = cleanChars[i]; } Arrays.sort(cleanCharas, charComparator); // sorts in increasing order for (char mnem : cleanCharas) { if (taken.contains(Character.toLowerCase(mnem))) continue; if (banned.contains(Character.toLowerCase(mnem))) continue; // NB: setMnemonic(char) doesn't want [^A-Za-z] jmi.setMnemonic(mnem); jmi.setDisplayedMnemonicIndex(jmi.getText().indexOf(mnem)); taken.add(Character.toLowerCase(mnem)); continue algorithmicAssignment; } // METHOD 6: Digits as last resort. for (char digit : jmi.getText().replaceAll("[^0-9]", "").toCharArray()) { if (taken.contains(digit)) continue; if (banned.contains(digit)) continue; jmi.setMnemonic(KeyEvent.VK_0 + digit - '0'); // setDisplayedMnemonicIndex() unneeded: no case issues. taken.add(digit); continue algorithmicAssignment; } } // Finally, RECURSION. for (JMenuItem jmi : menu) { if (jmi instanceof JMenu) setMenuMnemsInside((JMenu) jmi); } } /** * As setMenuMnemonics(JMenuItem...). */ static public void setMenuMnemonics(JMenuBar menubar) { JMenuItem[] items = new JMenuItem[menubar.getMenuCount()]; for (int i = 0; i < items.length; i++) { items[i] = menubar.getMenu(i); } setMenuMnemonics(items); } /** * As setMenuMnemonics(JMenuItem...). */ static public void setMenuMnemonics(JPopupMenu menu) { ArrayList<JMenuItem> items = new ArrayList<>(); for (Component c : menu.getComponents()) { if (c instanceof JMenuItem) items.add((JMenuItem)c); } setMenuMnemonics(items.toArray(new JMenuItem[items.size()])); } /** * Calls setMenuMnemonics(JMenuItem...) on the sub-elements only. */ static public void setMenuMnemsInside(JMenu menu) { JMenuItem[] items = new JMenuItem[menu.getItemCount()]; for (int i = 0; i < items.length; i++) { items[i] = menu.getItem(i); } setMenuMnemonics(items); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static public Dimension getScreenSize() { return awtToolkit.getScreenSize(); } /** * Return an Image object from inside the Processing 'lib' folder. * Moved here so that Base can stay headless. */ static public Image getLibImage(String filename) { ImageIcon icon = getLibIcon(filename); return (icon == null) ? null : icon.getImage(); } /** * Get an ImageIcon from the Processing 'lib' folder. * @since 3.0a6 */ static public ImageIcon getLibIcon(String filename) { File file = Platform.getContentFile("lib/" + filename); if (!file.exists()) { // System.err.println("does not exist: " + file); return null; } return new ImageIcon(file.getAbsolutePath()); } static public ImageIcon getIconX(File dir, String base) { return getIconX(dir, base, 0); } /** * Get an icon of the format base-NN.png where NN is the size, but if it's * a hidpi display, get the NN*2 version automatically, sized at NN */ static public ImageIcon getIconX(File dir, String base, int size) { final int scale = Toolkit.highResImages() ? 2 : 1; String filename = (size == 0) ? (base + "-" + scale + "x.png") : (base + "-" + (size*scale) + ".png"); File file = new File(dir, filename); if (!file.exists()) { return null; } ImageIcon outgoing = new ImageIcon(file.getAbsolutePath()) { @Override public int getIconWidth() { return Toolkit.zoom(super.getIconWidth()) / scale; } @Override public int getIconHeight() { return Toolkit.zoom(super.getIconHeight()) / scale; } @Override public synchronized void paintIcon(Component c, Graphics g, int x, int y) { ImageObserver imageObserver = getImageObserver(); if (imageObserver == null) { imageObserver = c; } g.drawImage(getImage(), x, y, getIconWidth(), getIconHeight(), imageObserver); } }; return outgoing; } /** * Get an image icon with hi-dpi support. Pulls 1x or 2x versions of the * file depending on the display type, but sizes them based on 1x. */ static public ImageIcon getLibIconX(String base) { return getLibIconX(base, 0); } static public ImageIcon getLibIconX(String base, int size) { return getIconX(Platform.getContentFile("lib"), base, size); } /** * Create a JButton with an icon, and set its disabled and pressed images * to be the same image, so that 2x versions of the icon work properly. */ static public JButton createIconButton(String title, String base) { ImageIcon icon = Toolkit.getLibIconX(base); return createIconButton(title, icon); } /** Same as above, but with no text title (follows JButton constructor) */ static public JButton createIconButton(String base) { return createIconButton(null, base); } static public JButton createIconButton(String title, Icon icon) { JButton button = new JButton(title, icon); button.setDisabledIcon(icon); button.setPressedIcon(icon); return button; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static List<Image> iconImages; // Deprecated version of the function, but can't get rid of it without // breaking tools and modes (they'd only require a recompile, but they would // no longer be backwards compatible. static public void setIcon(Frame frame) { setIcon((Window) frame); } /** * Give this Frame the Processing icon set. Ignored on OS X, because they * thought different and made this function set the minified image of the * window, not the window icon for the dock or cmd-tab. */ static public void setIcon(Window window) { if (!Platform.isMacOS()) { if (iconImages == null) { iconImages = new ArrayList<>(); final int[] sizes = { 16, 32, 48, 64, 128, 256, 512 }; for (int sz : sizes) { iconImages.add(Toolkit.getLibImage("icons/pde-" + sz + ".png")); } } window.setIconImages(iconImages); } } static public Shape createRoundRect(float x1, float y1, float x2, float y2, float tl, float tr, float br, float bl) { GeneralPath path = new GeneralPath(); // vertex(x1+tl, y1); if (tr != 0) { path.moveTo(x2-tr, y1); path.quadTo(x2, y1, x2, y1+tr); } else { path.moveTo(x2, y1); } if (br != 0) { path.lineTo(x2, y2-br); path.quadTo(x2, y2, x2-br, y2); } else { path.lineTo(x2, y2); } if (bl != 0) { path.lineTo(x1+bl, y2); path.quadTo(x1, y2, x1, y2-bl); } else { path.lineTo(x1, y2); } if (tl != 0) { path.lineTo(x1, y1+tl); path.quadTo(x1, y1, x1+tl, y1); } else { path.lineTo(x1, y1); } path.closePath(); return path; } /** * Registers key events for a Ctrl-W and ESC with an ActionListener * that will take care of disposing the window. */ static public void registerWindowCloseKeys(JRootPane root, ActionListener disposer) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); root.registerKeyboardAction(disposer, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); int modifiers = awtToolkit.getMenuShortcutKeyMask(); stroke = KeyStroke.getKeyStroke('W', modifiers); root.registerKeyboardAction(disposer, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static public void beep() { awtToolkit.beep(); } static public Clipboard getSystemClipboard() { return awtToolkit.getSystemClipboard(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Create an Image to be used as an offscreen drawing context, * automatically doubling the size if running on a retina display. */ static public Image offscreenGraphics(Component comp, int width, int height) { int m = Toolkit.isRetina() ? 2 : 1; //return comp.createImage(m * dpi(width), m * dpi(height)); return comp.createImage(m * width, m * height); } /** * Handles scaling for high-res displays, also sets text anti-aliasing * options to be far less ugly than the defaults. * Moved to a utility function because it's used in several classes. * @return a Graphics2D object, as a bit o sugar */ static public Graphics2D prepareGraphics(Graphics g) { Graphics2D g2 = (Graphics2D) g; //float z = zoom * (Toolkit.isRetina() ? 2 : 1); if (Toolkit.isRetina()) { // scale everything 2x, will be scaled down when drawn to the screen g2.scale(2, 2); } //g2.scale(z, z); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); if (Toolkit.isRetina()) { // Looks great on retina, not so great (with our font) on 1x g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); } zoomStroke(g2); return g2; } // /** // * Prepare and offscreen image that's sized for this Component, 1x or 2x // * depending on whether this is a retina display or not. // * @param comp // * @param image // * @return // */ // static public Image prepareOffscreen(Component comp, Image image) { // Dimension size = comp.getSize(); // Image offscreen = image; // if (image == null || // image.getWidth(null) != size.width || // image.getHeight(null) != size.height) { // if (Toolkit.highResDisplay()) { // offscreen = comp.createImage(size.width*2, size.height*2); // } else { // offscreen = comp.createImage(size.width, size.height); // } // } // return offscreen; // } // static final Color CLEAR_COLOR = new Color(0, true); // // static public void clearGraphics(Graphics g, int width, int height) { // g.setColor(CLEAR_COLOR); // g.fillRect(0, 0, width, height); // } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static float zoom = 0; /* // http://stackoverflow.com/a/35029265 static public void zoomSwingFonts() { Set<Object> keySet = UIManager.getLookAndFeelDefaults().keySet(); Object[] keys = keySet.toArray(new Object[keySet.size()]); for (Object key : keys) { if (key != null && key.toString().toLowerCase().contains("font")) { System.out.println(key); Font font = UIManager.getDefaults().getFont(key); if (font != null) { font = font.deriveFont(font.getSize() * zoom); UIManager.put(key, font); } } } } */ static final StringList zoomOptions = new StringList("100%", "150%", "200%", "300%"); static public int zoom(int pixels) { if (zoom == 0) { zoom = parseZoom(); } // Deal with 125% scaling badness // https://github.com/processing/processing/issues/4902 return (int) Math.ceil(zoom * pixels); } static public Dimension zoom(int w, int h) { return new Dimension(zoom(w), zoom(h)); } static public final int BORDER = Toolkit.zoom(Platform.isMacOS() ? 20 : 13); static public void setBorder(JComponent comp) { setBorder(comp, BORDER, BORDER, BORDER, BORDER); } static public void setBorder(JComponent comp, int top, int left, int bottom, int right) { comp.setBorder(new EmptyBorder(Toolkit.zoom(top), Toolkit.zoom(left), Toolkit.zoom(bottom), Toolkit.zoom(right))); } static private float parseZoom() { if (Preferences.getBoolean("editor.zoom.auto")) { float newZoom = Platform.getSystemDPI() / 96f; String percentSel = ((int) (newZoom*100)) + "%"; Preferences.set("editor.zoom", percentSel); return newZoom; } else { String zoomSel = Preferences.get("editor.zoom"); if (zoomOptions.hasValue(zoomSel)) { // shave off the % symbol at the end zoomSel = zoomSel.substring(0, zoomSel.length() - 1); return PApplet.parseInt(zoomSel, 100) / 100f; } else { Preferences.set("editor.zoom", "100%"); return 1; } } } static BasicStroke zoomStroke; static private void zoomStroke(Graphics2D g2) { if (zoom != 1) { if (zoomStroke == null || zoomStroke.getLineWidth() != zoom) { zoomStroke = new BasicStroke(zoom); } g2.setStroke(zoomStroke); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // Changed to retinaProp instead of highResProp because only Mac // "retina" displays use this mechanism for high-resolution scaling. static Boolean retinaProp; static public boolean highResImages() { return isRetina() || (zoom > 1); } static public boolean isRetina() { if (retinaProp == null) { retinaProp = checkRetina(); } return retinaProp; } // This should probably be reset each time there's a display change. // A 5-minute search didn't turn up any such event in the Java API. // Also, should we use the Toolkit associated with the editor window? static private boolean checkRetina() { if (Platform.isMacOS()) { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = env.getDefaultScreenDevice(); try { Field field = device.getClass().getDeclaredField("scale"); if (field != null) { field.setAccessible(true); Object scale = field.get(device); if (scale instanceof Integer && ((Integer)scale).intValue() == 2) { return true; } } } catch (Exception ignore) { } } return false; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // Gets the plain (not bold, not italic) version of each static private List<Font> getMonoFontList() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); Font[] fonts = ge.getAllFonts(); List<Font> outgoing = new ArrayList<>(); // Using AffineTransform.getScaleInstance(100, 100) doesn't change sizes FontRenderContext frc = new FontRenderContext(new AffineTransform(), Preferences.getBoolean("editor.antialias"), true); // use fractional metrics for (Font font : fonts) { if (font.getStyle() == Font.PLAIN && font.canDisplay('i') && font.canDisplay('M') && font.canDisplay(' ') && font.canDisplay('.')) { // The old method just returns 1 or 0, and using deriveFont(size) // is overkill. It also causes deprecation warnings // @SuppressWarnings("deprecation") // FontMetrics fm = awtToolkit.getFontMetrics(font); //FontMetrics fm = awtToolkit.getFontMetrics(font.deriveFont(24)); // System.out.println(fm.charWidth('i') + " " + fm.charWidth('M')); // if (fm.charWidth('i') == fm.charWidth('M') && // fm.charWidth('M') == fm.charWidth(' ') && // fm.charWidth(' ') == fm.charWidth('.')) { double w = font.getStringBounds(" ", frc).getWidth(); if (w == font.getStringBounds("i", frc).getWidth() && w == font.getStringBounds("M", frc).getWidth() && w == font.getStringBounds(".", frc).getWidth()) { // //PApplet.printArray(font.getAvailableAttributes()); // Map<TextAttribute,?> attr = font.getAttributes(); // System.out.println(font.getFamily() + " > " + font.getName()); // System.out.println(font.getAttributes()); // System.out.println(" " + attr.get(TextAttribute.WEIGHT)); // System.out.println(" " + attr.get(TextAttribute.POSTURE)); outgoing.add(font); // System.out.println(" good " + w); } } } return outgoing; } static public String[] getMonoFontFamilies() { StringList families = new StringList(); for (Font font : getMonoFontList()) { families.appendUnique(font.getFamily()); } families.sort(); return families.array(); } static Font monoFont; static Font monoBoldFont; static Font sansFont; static Font sansBoldFont; static public String getMonoFontName() { if (monoFont == null) { // create a dummy version if the font has never been loaded (rare) getMonoFont(12, Font.PLAIN); } return monoFont.getName(); } static public Font getMonoFont(int size, int style) { if (monoFont == null) { try { monoFont = createFont("SourceCodePro-Regular.ttf", size); monoBoldFont = createFont("SourceCodePro-Bold.ttf", size); // https://github.com/processing/processing/issues/2886 // https://github.com/processing/processing/issues/4944 String lang = Language.getLanguage(); if ("el".equals(lang) || "ar".equals(lang) || Locale.CHINESE.getLanguage().equals(lang) || Locale.JAPANESE.getLanguage().equals(lang) || Locale.KOREAN.getLanguage().equals(lang)) { sansFont = new Font("Monospaced", Font.PLAIN, size); sansBoldFont = new Font("Monospaced", Font.BOLD, size); } } catch (Exception e) { Messages.loge("Could not load mono font", e); monoFont = new Font("Monospaced", Font.PLAIN, size); monoBoldFont = new Font("Monospaced", Font.BOLD, size); } } if (style == Font.BOLD) { if (size == monoBoldFont.getSize()) { return monoBoldFont; } else { return monoBoldFont.deriveFont((float) size); } } else { if (size == monoFont.getSize()) { return monoFont; } else { return monoFont.deriveFont((float) size); } } } static public String getSansFontName() { if (sansFont == null) { // create a dummy version if the font has never been loaded (rare) getSansFont(12, Font.PLAIN); } return sansFont.getName(); } static public Font getSansFont(int size, int style) { if (sansFont == null) { try { sansFont = createFont("ProcessingSansPro-Regular.ttf", size); sansBoldFont = createFont("ProcessingSansPro-Semibold.ttf", size); // https://github.com/processing/processing/issues/2886 // https://github.com/processing/processing/issues/4944 String lang = Language.getLanguage(); if ("el".equals(lang) || "ar".equals(lang) || Locale.CHINESE.getLanguage().equals(lang) || Locale.JAPANESE.getLanguage().equals(lang) || Locale.KOREAN.getLanguage().equals(lang)) { sansFont = new Font("SansSerif", Font.PLAIN, size); sansBoldFont = new Font("SansSerif", Font.BOLD, size); } } catch (Exception e) { Messages.loge("Could not load sans font", e); sansFont = new Font("SansSerif", Font.PLAIN, size); sansBoldFont = new Font("SansSerif", Font.BOLD, size); } } if (style == Font.BOLD) { if (size == sansBoldFont.getSize()) { return sansBoldFont; } else { return sansBoldFont.deriveFont((float) size); } } else { if (size == sansFont.getSize()) { return sansFont; } else { return sansFont.deriveFont((float) size); } } } /** * Get a font from the lib/fonts folder. Our default fonts are also * installed there so that the monospace (and others) can be used by other * font listing calls (i.e. it appears in the list of monospace fonts in * the Preferences window, and can be used by HTMLEditorKit for WebFrame). */ static private Font createFont(String filename, int size) throws IOException, FontFormatException { boolean registerFont = false; // try the JRE font directory first File fontFile = new File(System.getProperty("java.home"), "lib/fonts/" + filename); // else fall back to our own content dir if (!fontFile.exists()) { fontFile = Platform.getContentFile("lib/fonts/" + filename); registerFont = true; } if (!fontFile.exists()) { String msg = "Could not find required fonts. "; // This gets the JAVA_HOME for the *local* copy of the JRE installed with // Processing. If it's not using the local JRE, it may be because of this // launch4j bug: https://github.com/processing/processing/issues/3543 if (Util.containsNonASCII(Platform.getJavaHome().getAbsolutePath())) { msg += "Trying moving Processing\n" + "to a location with only ASCII characters in the path."; } else { msg += "Please reinstall Processing."; } Messages.showError("Font Sadness", msg, null); } BufferedInputStream input = new BufferedInputStream(new FileInputStream(fontFile)); Font font = Font.createFont(Font.TRUETYPE_FONT, input); input.close(); if (registerFont) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(font); } return font.deriveFont((float) size); } /** * Synthesized replacement for FontMetrics.getAscent(), which is dreadfully * inaccurate and inconsistent across platforms. */ static public double getAscent(Graphics g) { Graphics2D g2 = (Graphics2D) g; FontRenderContext frc = g2.getFontRenderContext(); //return new TextLayout("H", font, frc).getBounds().getHeight(); return new TextLayout("H", g.getFont(), frc).getBounds().getHeight(); } static public int getMenuItemIndex(JMenu menu, JMenuItem item) { int index = 0; for (Component comp : menu.getMenuComponents()) { if (comp == item) { return index; } index++; } return -1; } }
processing/processing
app/src/processing/app/ui/Toolkit.java
2,181
package com.baeldung.mapper; import org.mapstruct.AfterMapping; import org.mapstruct.BeforeMapping; import org.mapstruct.Mapper; import org.mapstruct.MappingTarget; import com.baeldung.dto.CarDTO; import com.baeldung.dto.FuelType; import com.baeldung.entity.BioDieselCar; import com.baeldung.entity.Car; import com.baeldung.entity.ElectricCar; @Mapper public abstract class CarsMapper { @BeforeMapping protected void enrichDTOWithFuelType(Car car, @MappingTarget CarDTO carDto) { if (car instanceof ElectricCar) carDto.setFuelType(FuelType.ELECTRIC); if (car instanceof BioDieselCar) carDto.setFuelType(FuelType.BIO_DIESEL); } @AfterMapping protected void convertNameToUpperCase(@MappingTarget CarDTO carDto) { carDto.setName(carDto.getName().toUpperCase()); } public abstract CarDTO toCarDto(Car car); }
eugenp/tutorials
mapstruct/src/main/java/com/baeldung/mapper/CarsMapper.java
2,182
/* -*- 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) 2005-13 Ben Fry and Casey Reas This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.awt; import java.awt.*; import java.awt.font.TextAttribute; import java.awt.geom.*; import java.awt.image.*; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import processing.core.*; /** * Subclass for PGraphics that implements the graphics API using Java2D. * <p> * To get access to the Java 2D "Graphics2D" object for the default * renderer, use: * <PRE> * Graphics2D g2 = (Graphics2D) g.getNative(); * </PRE> * This will let you do Graphics2D calls directly, but is not supported * in any way shape or form. Which just means "have fun, but don't complain * if it breaks." * <p> * Advanced <a href="http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-Desktop/html/java2d.html">debugging notes</a> for Java2D. */ public class PGraphicsJava2D extends PGraphics { //// BufferStrategy strategy; //// BufferedImage bimage; //// VolatileImage vimage; // Canvas canvas; //// boolean useCanvas = true; // boolean useCanvas = false; //// boolean useRetina = true; //// boolean useOffscreen = true; // ~40fps // boolean useOffscreen = false; public Graphics2D g2; // protected BufferedImage offscreen; Composite defaultComposite; GeneralPath gpath; // path for contours so gpath can be closed GeneralPath auxPath; boolean openContour; /// break the shape at the next vertex (next vertex() call is a moveto()) boolean breakShape; /// coordinates for internal curve calculation float[] curveCoordX; float[] curveCoordY; float[] curveDrawX; float[] curveDrawY; int transformCount; AffineTransform[] transformStack = new AffineTransform[MATRIX_STACK_DEPTH]; double[] transform = new double[6]; Line2D.Float line = new Line2D.Float(); Ellipse2D.Float ellipse = new Ellipse2D.Float(); Rectangle2D.Float rect = new Rectangle2D.Float(); Arc2D.Float arc = new Arc2D.Float(); protected Color tintColorObject; protected Color fillColorObject; public boolean fillGradient; public Paint fillGradientObject; protected Stroke strokeObject; protected Color strokeColorObject; public boolean strokeGradient; public Paint strokeGradientObject; Font fontObject; ////////////////////////////////////////////////////////////// // INTERNAL public PGraphicsJava2D() { } //public void setParent(PApplet parent) //public void setPrimary(boolean primary) //public void setPath(String path) // /** // * Called in response to a resize event, handles setting the // * new width and height internally, as well as re-allocating // * the pixel buffer for the new size. // * // * Note that this will nuke any cameraMode() settings. // */ // @Override // public void setSize(int iwidth, int iheight) { // ignore // width = iwidth; // height = iheight; // // allocate(); // reapplySettings(); // } // @Override // protected void allocate() { // //surface.initImage(this, width, height); // surface.initImage(this); // } /* @Override protected void allocate() { // Tried this with RGB instead of ARGB for the primarySurface version, // but didn't see any performance difference (OS X 10.6, Java 6u24). // For 0196, also attempted RGB instead of ARGB, but that causes // strange things to happen with blending. // image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); if (primarySurface) { if (useCanvas) { if (canvas != null) { parent.removeListeners(canvas); parent.remove(canvas); } canvas = new Canvas(); canvas.setIgnoreRepaint(true); // parent.setLayout(new BorderLayout()); // parent.add(canvas, BorderLayout.CENTER); parent.add(canvas); // canvas.validate(); // parent.doLayout(); if (canvas.getWidth() != width || canvas.getHeight() != height) { PApplet.debug("PGraphicsJava2D comp size being set to " + width + "x" + height); canvas.setSize(width, height); } else { PApplet.debug("PGraphicsJava2D comp size already " + width + "x" + height); } parent.addListeners(canvas); // canvas.createBufferStrategy(1); // g2 = (Graphics2D) canvas.getGraphics(); } else { parent.updateListeners(parent); // in case they're already there // using a compatible image here doesn't seem to provide any performance boost if (useOffscreen) { // Needs to be RGB otherwise there's a major performance hit [0204] // http://code.google.com/p/processing/issues/detail?id=729 image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // GraphicsConfiguration gc = parent.getGraphicsConfiguration(); // image = gc.createCompatibleImage(width, height); offscreen = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // offscreen = gc.createCompatibleImage(width, height); g2 = (Graphics2D) offscreen.getGraphics(); } else { // System.out.println("hopefully faster " + width + " " + height); // new Exception().printStackTrace(System.out); GraphicsConfiguration gc = canvas.getGraphicsConfiguration(); // If not realized (off-screen, i.e the Color Selector Tool), // gc will be null. if (gc == null) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); gc = ge.getDefaultScreenDevice().getDefaultConfiguration(); } image = gc.createCompatibleImage(width, height); g2 = (Graphics2D) image.getGraphics(); } } } else { // not the primary surface // Since this buffer's offscreen anyway, no need for the extra offscreen // buffer. However, unlike the primary surface, this feller needs to be // ARGB so that blending ("alpha" compositing) will work properly. image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); g2 = (Graphics2D) image.getGraphics(); } */ /* if (primarySurface) { Canvas canvas = ((PSurfaceAWT) surface).canvas; GraphicsConfiguration gc = canvas.getGraphicsConfiguration(); // If not realized (off-screen, i.e the Color Selector Tool), // gc will be null. if (gc == null) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); gc = ge.getDefaultScreenDevice().getDefaultConfiguration(); } image = gc.createCompatibleImage(width, height); g2 = (Graphics2D) image.getGraphics(); } else { } g2 = (Graphics2D) image.getGraphics(); } */ //public void dispose() @Override public PSurface createSurface() { return surface = new PSurfaceAWT(this); } /** * Still need a means to get the java.awt.Image object, since getNative() * is going to return the {@link Graphics2D} object. */ @Override public Image getImage() { return image; } /** Returns the java.awt.Graphics2D object used by this renderer. */ @Override public Object getNative() { return g2; } ////////////////////////////////////////////////////////////// // FRAME // @Override // public boolean canDraw() { // return true; // } // @Override // public void requestDraw() { //// EventQueue.invokeLater(new Runnable() { //// public void run() { // parent.handleDraw(); //// } //// }); // } // Graphics2D g2old; public Graphics2D checkImage() { if (image == null || ((BufferedImage) image).getWidth() != width*pixelDensity || ((BufferedImage) image).getHeight() != height*pixelDensity) { // ((VolatileImage) image).getWidth() != width || // ((VolatileImage) image).getHeight() != height) { // image = new BufferedImage(width * pixelFactor, height * pixelFactor // format == RGB ? BufferedImage.TYPE_INT_ARGB); // Commenting this out, because we are not drawing directly to the screen [jv 2018-06-01] // // GraphicsConfiguration gc = null; // if (surface != null) { // Component comp = null; //surface.getComponent(); // if (comp == null) { //// System.out.println("component null, but parent.frame is " + parent.frame); // comp = parent.frame; // } // if (comp != null) { // gc = comp.getGraphicsConfiguration(); // } // } // // If not realized (off-screen, i.e the Color Selector Tool), gc will be null. // if (gc == null) { // //System.err.println("GraphicsConfiguration null in initImage()"); // GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); // gc = ge.getDefaultScreenDevice().getDefaultConfiguration(); // } // Formerly this was broken into separate versions based on offscreen or // not, but we may as well create a compatible image; it won't hurt, right? // P.S.: Three years later, I'm happy to report it did in fact hurt [jv 2018-06-01] int wide = width * pixelDensity; int high = height * pixelDensity; // System.out.println("re-creating image"); // For now we expect non-premultiplied INT ARGB and the compatible image // might not be it... create the image directly. It's important that the // image has all four bands, otherwise we get garbage alpha during blending // (see https://github.com/processing/processing/pull/2645, // https://github.com/processing/processing/pull/3523) // // image = gc.createCompatibleImage(wide, high, Transparency.TRANSLUCENT); image = new BufferedImage(wide, high, BufferedImage.TYPE_INT_ARGB); } return (Graphics2D) image.getGraphics(); } @Override public void beginDraw() { g2 = checkImage(); // Calling getGraphics() seems to nuke several settings. // It seems to be re-creating a new Graphics2D object each time. // https://github.com/processing/processing/issues/3331 if (strokeObject != null) { g2.setStroke(strokeObject); } // https://github.com/processing/processing/issues/2617 if (fontObject != null) { g2.setFont(fontObject); } // https://github.com/processing/processing/issues/4019 if (blendMode != 0) { blendMode(blendMode); } handleSmooth(); /* // NOTE: Calling image.getGraphics() will create a new Graphics context, // even if it's for the same image that's already had a context created. // Seems like a speed/memory issue, and also requires that all smoothing, // stroke, font and other props be reset. Can't find a good answer about // whether getGraphics() and dispose() on each frame is 1) better practice // and 2) minimal overhead, however. Instinct suggests #1 may be true, // but #2 seems a problem. if (primarySurface && !useOffscreen) { GraphicsConfiguration gc = canvas.getGraphicsConfiguration(); if (false) { if (image == null || ((VolatileImage) image).validate(gc) == VolatileImage.IMAGE_INCOMPATIBLE) { image = gc.createCompatibleVolatileImage(width, height); g2 = (Graphics2D) image.getGraphics(); reapplySettings = true; } } else { if (image == null) { image = gc.createCompatibleImage(width, height); PApplet.debug("created new image, type is " + image); g2 = (Graphics2D) image.getGraphics(); reapplySettings = true; } } } if (useCanvas && primarySurface) { if (parent.frameCount == 0) { canvas.createBufferStrategy(2); strategy = canvas.getBufferStrategy(); PApplet.debug("PGraphicsJava2D.beginDraw() strategy is " + strategy); BufferCapabilities caps = strategy.getCapabilities(); caps = strategy.getCapabilities(); PApplet.debug("PGraphicsJava2D.beginDraw() caps are " + " flipping: " + caps.isPageFlipping() + " front/back accel: " + caps.getFrontBufferCapabilities().isAccelerated() + " " + "/" + caps.getBackBufferCapabilities().isAccelerated()); } GraphicsConfiguration gc = canvas.getGraphicsConfiguration(); if (bimage == null || bimage.getWidth() != width || bimage.getHeight() != height) { PApplet.debug("PGraphicsJava2D creating new image"); bimage = gc.createCompatibleImage(width, height); // image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); g2 = bimage.createGraphics(); defaultComposite = g2.getComposite(); reapplySettings = true; } } */ checkSettings(); resetMatrix(); // reset model matrix vertexCount = 0; } /** * Smoothing for Java2D is 2 for bilinear, and 3 for bicubic (the default). * Internally, smooth(1) is the default, smooth(0) is noSmooth(). */ protected void handleSmooth() { if (smooth == 0) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } else { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (smooth == 1 || smooth == 3) { // default is bicubic g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); } else if (smooth == 2) { g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } // http://docs.oracle.com/javase/tutorial/2d/text/renderinghints.html // Oracle Java text anti-aliasing on OS X looks like s*t compared to the // text rendering with Apple's old Java 6. Below, several attempts to fix: g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // Turns out this is the one that actually makes things work. // Kerning is still screwed up, however. g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); // g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, // RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); // g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, // RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); // g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, // RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); } } @Override public void endDraw() { // hm, mark pixels as changed, because this will instantly do a full // copy of all the pixels to the surface.. so that's kind of a mess. //updatePixels(); if (primaryGraphics) { /* //if (canvas != null) { if (useCanvas) { //System.out.println(canvas); // alternate version //canvas.repaint(); // ?? what to do for swapping buffers // System.out.println("endDraw() frameCount is " + parent.frameCount); // if (parent.frameCount != 0) { redraw(); // } } else if (useOffscreen) { // don't copy the pixels/data elements of the buffered image directly, // since it'll disable the nice speedy pipeline stuff, sending all drawing // into a world of suck that's rough 6 trillion times slower. synchronized (image) { //System.out.println("inside j2d sync"); image.getGraphics().drawImage(offscreen, 0, 0, null); } } else { // changed to not dispose and get on each frame, // otherwise a new Graphics context is used on each frame // g2.dispose(); // System.out.println("not doing anything special in endDraw()"); } */ } else { // TODO this is probably overkill for most tasks... loadPixels(); } // // Marking as modified, and then calling updatePixels() in // // the super class, which just sets the mx1, my1, mx2, my2 // // coordinates of the modified area. This avoids doing the // // full copy of the pixels to the surface in this.updatePixels(). // setModified(); // super.updatePixels(); // Marks pixels as modified so that the pixels will be updated. // Also sets mx1/y1/x2/y2 so that OpenGL will pick it up. setModified(); g2.dispose(); } /* private void redraw() { // only need this check if the validate() call will use redraw() // if (strategy == null) return; do { PApplet.debug("PGraphicsJava2D.redraw() top of outer do { } block"); do { PApplet.debug("PGraphicsJava2D.redraw() top of inner do { } block"); PApplet.debug("strategy is " + strategy); Graphics bsg = strategy.getDrawGraphics(); // if (vimage != null) { // bsg.drawImage(vimage, 0, 0, null); // } else { bsg.drawImage(bimage, 0, 0, null); // if (parent.frameCount == 0) { // try { // ImageIO.write(image, "jpg", new java.io.File("/Users/fry/Desktop/buff.jpg")); // } catch (IOException e) { // e.printStackTrace(); // } // } // } bsg.dispose(); // the strategy version // g2.dispose(); // if (!strategy.contentsLost()) { // if (parent.frameCount != 0) { // Toolkit.getDefaultToolkit().sync(); // } // } else { // System.out.println("XXXXX strategy contents lost"); // } // } // } } while (strategy.contentsRestored()); PApplet.debug("PGraphicsJava2D.redraw() showing strategy"); strategy.show(); } while (strategy.contentsLost()); PApplet.debug("PGraphicsJava2D.redraw() out of do { } block"); } */ ////////////////////////////////////////////////////////////// // SETTINGS //protected void checkSettings() @Override protected void defaultSettings() { // if (!useCanvas) { // // Papered over another threading issue... // // See if this comes back now that the other issue is fixed. //// while (g2 == null) { //// try { //// System.out.println("sleeping until g2 is available"); //// Thread.sleep(5); //// } catch (InterruptedException e) { } //// } defaultComposite = g2.getComposite(); // } super.defaultSettings(); } //protected void reapplySettings() ////////////////////////////////////////////////////////////// // HINT @Override public void hint(int which) { // take care of setting the hint super.hint(which); // Avoid badness when drawing shorter strokes. // http://code.google.com/p/processing/issues/detail?id=1068 // Unfortunately cannot always be enabled, because it makes the // stroke in many standard Processing examples really gross. if (which == ENABLE_STROKE_PURE) { g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); } else if (which == DISABLE_STROKE_PURE) { g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT); } } ////////////////////////////////////////////////////////////// // SHAPE CREATION @Override protected PShape createShapeFamily(int type) { return new PShape(this, type); } @Override protected PShape createShapePrimitive(int kind, float... p) { return new PShape(this, kind, p); } // @Override // public PShape createShape(PShape source) { // return PShapeOpenGL.createShape2D(this, source); // } /* protected PShape createShapeImpl(PGraphicsJava2D pg, int type) { PShape shape = null; if (type == PConstants.GROUP) { shape = new PShape(pg, PConstants.GROUP); } else if (type == PShape.PATH) { shape = new PShape(pg, PShape.PATH); } else if (type == PShape.GEOMETRY) { shape = new PShape(pg, PShape.GEOMETRY); } // defaults to false, don't assign it and make complexity for overrides //shape.set3D(false); return shape; } */ /* static protected PShape createShapeImpl(PGraphicsJava2D pg, int kind, float... p) { PShape shape = null; int len = p.length; if (kind == POINT) { if (len != 2) { showWarning("Wrong number of parameters"); return null; } shape = new PShape(pg, PShape.PRIMITIVE); shape.setKind(POINT); } else if (kind == LINE) { if (len != 4) { showWarning("Wrong number of parameters"); return null; } shape = new PShape(pg, PShape.PRIMITIVE); shape.setKind(LINE); } else if (kind == TRIANGLE) { if (len != 6) { showWarning("Wrong number of parameters"); return null; } shape = new PShape(pg, PShape.PRIMITIVE); shape.setKind(TRIANGLE); } else if (kind == QUAD) { if (len != 8) { showWarning("Wrong number of parameters"); return null; } shape = new PShape(pg, PShape.PRIMITIVE); shape.setKind(QUAD); } else if (kind == RECT) { if (len != 4 && len != 5 && len != 8 && len != 9) { showWarning("Wrong number of parameters"); return null; } shape = new PShape(pg, PShape.PRIMITIVE); shape.setKind(RECT); } else if (kind == ELLIPSE) { if (len != 4 && len != 5) { showWarning("Wrong number of parameters"); return null; } shape = new PShape(pg, PShape.PRIMITIVE); shape.setKind(ELLIPSE); } else if (kind == ARC) { if (len != 6 && len != 7) { showWarning("Wrong number of parameters"); return null; } shape = new PShape(pg, PShape.PRIMITIVE); shape.setKind(ARC); } else if (kind == BOX) { showWarning("Primitive not supported in 2D"); } else if (kind == SPHERE) { showWarning("Primitive not supported in 2D"); } else { showWarning("Unrecognized primitive type"); } if (shape != null) { shape.setParams(p); } // defaults to false, don't assign it and make complexity for overrides //shape.set3D(false); return shape; } */ ////////////////////////////////////////////////////////////// // SHAPES @Override public void beginShape(int kind) { //super.beginShape(kind); shape = kind; vertexCount = 0; curveVertexCount = 0; // set gpath to null, because when mixing curves and straight // lines, vertexCount will be set back to zero, so vertexCount == 1 // is no longer a good indicator of whether the shape is new. // this way, just check to see if gpath is null, and if it isn't // then just use it to continue the shape. gpath = null; auxPath = null; } //public boolean edge(boolean e) //public void normal(float nx, float ny, float nz) { //public void textureMode(int mode) @Override public void texture(PImage image) { showMethodWarning("texture"); } @Override public void vertex(float x, float y) { curveVertexCount = 0; //float vertex[]; if (vertexCount == vertices.length) { float[][] temp = new float[vertexCount<<1][VERTEX_FIELD_COUNT]; System.arraycopy(vertices, 0, temp, 0, vertexCount); vertices = temp; //message(CHATTER, "allocating more vertices " + vertices.length); } // not everyone needs this, but just easier to store rather // than adding another moving part to the code... vertices[vertexCount][X] = x; vertices[vertexCount][Y] = y; vertexCount++; switch (shape) { case POINTS: point(x, y); break; case LINES: if ((vertexCount % 2) == 0) { line(vertices[vertexCount-2][X], vertices[vertexCount-2][Y], x, y); } break; case TRIANGLES: if ((vertexCount % 3) == 0) { triangle(vertices[vertexCount - 3][X], vertices[vertexCount - 3][Y], vertices[vertexCount - 2][X], vertices[vertexCount - 2][Y], x, y); } break; case TRIANGLE_STRIP: if (vertexCount >= 3) { triangle(vertices[vertexCount - 2][X], vertices[vertexCount - 2][Y], vertices[vertexCount - 1][X], vertices[vertexCount - 1][Y], vertices[vertexCount - 3][X], vertices[vertexCount - 3][Y]); } break; case TRIANGLE_FAN: if (vertexCount >= 3) { // This is an unfortunate implementation because the stroke for an // adjacent triangle will be repeated. However, if the stroke is not // redrawn, it will replace the adjacent line (when it lines up // perfectly) or show a faint line (when off by a small amount). // The alternative would be to wait, then draw the shape as a // polygon fill, followed by a series of vertices. But that's a // poor method when used with PDF, DXF, or other recording objects, // since discrete triangles would likely be preferred. triangle(vertices[0][X], vertices[0][Y], vertices[vertexCount - 2][X], vertices[vertexCount - 2][Y], x, y); } break; case QUAD: case QUADS: if ((vertexCount % 4) == 0) { quad(vertices[vertexCount - 4][X], vertices[vertexCount - 4][Y], vertices[vertexCount - 3][X], vertices[vertexCount - 3][Y], vertices[vertexCount - 2][X], vertices[vertexCount - 2][Y], x, y); } break; case QUAD_STRIP: // 0---2---4 // | | | // 1---3---5 if ((vertexCount >= 4) && ((vertexCount % 2) == 0)) { quad(vertices[vertexCount - 4][X], vertices[vertexCount - 4][Y], vertices[vertexCount - 2][X], vertices[vertexCount - 2][Y], x, y, vertices[vertexCount - 3][X], vertices[vertexCount - 3][Y]); } break; case POLYGON: if (gpath == null) { gpath = new GeneralPath(); gpath.moveTo(x, y); } else if (breakShape) { gpath.moveTo(x, y); breakShape = false; } else { gpath.lineTo(x, y); } break; } } @Override public void vertex(float x, float y, float z) { showDepthWarningXYZ("vertex"); } @Override public void vertex(float[] v) { vertex(v[X], v[Y]); } @Override public void vertex(float x, float y, float u, float v) { showVariationWarning("vertex(x, y, u, v)"); } @Override public void vertex(float x, float y, float z, float u, float v) { showDepthWarningXYZ("vertex"); } @Override public void beginContour() { if (openContour) { PGraphics.showWarning("Already called beginContour()"); return; } // draw contours to auxiliary path so main path can be closed later GeneralPath contourPath = auxPath; auxPath = gpath; gpath = contourPath; if (contourPath != null) { // first contour does not break breakShape = true; } openContour = true; } @Override public void endContour() { if (!openContour) { PGraphics.showWarning("Need to call beginContour() first"); return; } // close this contour if (gpath != null) gpath.closePath(); // switch back to main path GeneralPath contourPath = gpath; gpath = auxPath; auxPath = contourPath; openContour = false; } @Override public void endShape(int mode) { if (openContour) { // correct automagically, notify user endContour(); PGraphics.showWarning("Missing endContour() before endShape()"); } if (gpath != null) { // make sure something has been drawn if (shape == POLYGON) { if (mode == CLOSE) { gpath.closePath(); } if (auxPath != null) { gpath.append(auxPath, false); } drawShape(gpath); } } shape = 0; } ////////////////////////////////////////////////////////////// // CLIPPING @Override protected void clipImpl(float x1, float y1, float x2, float y2) { g2.setClip(new Rectangle2D.Float(x1, y1, x2 - x1, y2 - y1)); } @Override public void noClip() { g2.setClip(null); } ////////////////////////////////////////////////////////////// // BLEND /** * ( begin auto-generated from blendMode.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref Rendering * @param mode the blending mode to use */ @Override protected void blendModeImpl() { if (blendMode == BLEND) { g2.setComposite(defaultComposite); } else { g2.setComposite(new Composite() { @Override public CompositeContext createContext(ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints) { return new BlendingContext(blendMode); } }); } } // Blending implementation cribbed from portions of Romain Guy's // demo and terrific writeup on blending modes in Java 2D. // http://www.curious-creature.org/2006/09/20/new-blendings-modes-for-java2d/ private static final class BlendingContext implements CompositeContext { private int mode; private BlendingContext(int mode) { this.mode = mode; } public void dispose() { } public void compose(Raster src, Raster dstIn, WritableRaster dstOut) { // not sure if this is really necessary, since we control our buffers if (src.getSampleModel().getDataType() != DataBuffer.TYPE_INT || dstIn.getSampleModel().getDataType() != DataBuffer.TYPE_INT || dstOut.getSampleModel().getDataType() != DataBuffer.TYPE_INT) { throw new IllegalStateException("Source and destination must store pixels as INT."); } int width = Math.min(src.getWidth(), dstIn.getWidth()); int height = Math.min(src.getHeight(), dstIn.getHeight()); int[] srcPixels = new int[width]; int[] dstPixels = new int[width]; for (int y = 0; y < height; y++) { src.getDataElements(0, y, width, 1, srcPixels); dstIn.getDataElements(0, y, width, 1, dstPixels); for (int x = 0; x < width; x++) { dstPixels[x] = blendColor(dstPixels[x], srcPixels[x], mode); } dstOut.setDataElements(0, y, width, 1, dstPixels); } } } ////////////////////////////////////////////////////////////// // BEZIER VERTICES @Override public void bezierVertex(float x1, float y1, float x2, float y2, float x3, float y3) { bezierVertexCheck(); gpath.curveTo(x1, y1, x2, y2, x3, y3); } @Override public void bezierVertex(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { showDepthWarningXYZ("bezierVertex"); } ////////////////////////////////////////////////////////////// // QUADRATIC BEZIER VERTICES @Override public void quadraticVertex(float ctrlX, float ctrlY, float endX, float endY) { bezierVertexCheck(); Point2D cur = gpath.getCurrentPoint(); float x1 = (float) cur.getX(); float y1 = (float) cur.getY(); bezierVertex(x1 + ((ctrlX-x1)*2/3.0f), y1 + ((ctrlY-y1)*2/3.0f), endX + ((ctrlX-endX)*2/3.0f), endY + ((ctrlY-endY)*2/3.0f), endX, endY); } @Override public void quadraticVertex(float x2, float y2, float z2, float x4, float y4, float z4) { showDepthWarningXYZ("quadVertex"); } ////////////////////////////////////////////////////////////// // CURVE VERTICES @Override protected void curveVertexCheck() { super.curveVertexCheck(); if (curveCoordX == null) { curveCoordX = new float[4]; curveCoordY = new float[4]; curveDrawX = new float[4]; curveDrawY = new float[4]; } } @Override protected void curveVertexSegment(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { curveCoordX[0] = x1; curveCoordY[0] = y1; curveCoordX[1] = x2; curveCoordY[1] = y2; curveCoordX[2] = x3; curveCoordY[2] = y3; curveCoordX[3] = x4; curveCoordY[3] = y4; curveToBezierMatrix.mult(curveCoordX, curveDrawX); curveToBezierMatrix.mult(curveCoordY, curveDrawY); // since the paths are continuous, // only the first point needs the actual moveto if (gpath == null) { gpath = new GeneralPath(); gpath.moveTo(curveDrawX[0], curveDrawY[0]); } gpath.curveTo(curveDrawX[1], curveDrawY[1], curveDrawX[2], curveDrawY[2], curveDrawX[3], curveDrawY[3]); } @Override public void curveVertex(float x, float y, float z) { showDepthWarningXYZ("curveVertex"); } ////////////////////////////////////////////////////////////// // RENDERER //public void flush() ////////////////////////////////////////////////////////////// // POINT, LINE, TRIANGLE, QUAD @Override public void point(float x, float y) { if (stroke) { // if (strokeWeight > 1) { line(x, y, x + EPSILON, y + EPSILON); // } else { // set((int) screenX(x, y), (int) screenY(x, y), strokeColor); // } } } @Override public void line(float x1, float y1, float x2, float y2) { line.setLine(x1, y1, x2, y2); strokeShape(line); } @Override public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { gpath = new GeneralPath(); gpath.moveTo(x1, y1); gpath.lineTo(x2, y2); gpath.lineTo(x3, y3); gpath.closePath(); drawShape(gpath); } @Override public void quad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { GeneralPath gp = new GeneralPath(); gp.moveTo(x1, y1); gp.lineTo(x2, y2); gp.lineTo(x3, y3); gp.lineTo(x4, y4); gp.closePath(); drawShape(gp); } ////////////////////////////////////////////////////////////// // RECT //public void rectMode(int mode) //public void rect(float a, float b, float c, float d) @Override protected void rectImpl(float x1, float y1, float x2, float y2) { rect.setFrame(x1, y1, x2-x1, y2-y1); drawShape(rect); } ////////////////////////////////////////////////////////////// // ELLIPSE //public void ellipseMode(int mode) //public void ellipse(float a, float b, float c, float d) @Override protected void ellipseImpl(float x, float y, float w, float h) { ellipse.setFrame(x, y, w, h); drawShape(ellipse); } ////////////////////////////////////////////////////////////// // ARC //public void arc(float a, float b, float c, float d, // float start, float stop) @Override protected void arcImpl(float x, float y, float w, float h, float start, float stop, int mode) { // 0 to 90 in java would be 0 to -90 for p5 renderer // but that won't work, so -90 to 0? start = -start * RAD_TO_DEG; stop = -stop * RAD_TO_DEG; // ok to do this because already checked for NaN // while (start < 0) { // start += 360; // stop += 360; // } // if (start > stop) { // float temp = start; // start = stop; // stop = temp; // } float sweep = stop - start; // The defaults, before 2.0b7, were to stroke as Arc2D.OPEN, and then fill // using Arc2D.PIE. That's a little wonky, but it's here for compatability. int fillMode = Arc2D.PIE; int strokeMode = Arc2D.OPEN; if (mode == OPEN) { fillMode = Arc2D.OPEN; //strokeMode = Arc2D.OPEN; } else if (mode == PIE) { //fillMode = Arc2D.PIE; strokeMode = Arc2D.PIE; } else if (mode == CHORD) { fillMode = Arc2D.CHORD; strokeMode = Arc2D.CHORD; } if (fill) { //System.out.println("filla"); arc.setArc(x, y, w, h, start, sweep, fillMode); fillShape(arc); } if (stroke) { //System.out.println("strokey"); arc.setArc(x, y, w, h, start, sweep, strokeMode); strokeShape(arc); } } ////////////////////////////////////////////////////////////// // JAVA2D SHAPE/PATH HANDLING protected void fillShape(Shape s) { if (fillGradient) { g2.setPaint(fillGradientObject); g2.fill(s); } else if (fill) { g2.setColor(fillColorObject); g2.fill(s); } } protected void strokeShape(Shape s) { if (strokeGradient) { g2.setPaint(strokeGradientObject); g2.draw(s); } else if (stroke) { g2.setColor(strokeColorObject); g2.draw(s); } } protected void drawShape(Shape s) { if (fillGradient) { g2.setPaint(fillGradientObject); g2.fill(s); } else if (fill) { g2.setColor(fillColorObject); g2.fill(s); } if (strokeGradient) { g2.setPaint(strokeGradientObject); g2.draw(s); } else if (stroke) { g2.setColor(strokeColorObject); g2.draw(s); } } ////////////////////////////////////////////////////////////// // BOX //public void box(float size) @Override public void box(float w, float h, float d) { showMethodWarning("box"); } ////////////////////////////////////////////////////////////// // SPHERE //public void sphereDetail(int res) //public void sphereDetail(int ures, int vres) @Override public void sphere(float r) { showMethodWarning("sphere"); } ////////////////////////////////////////////////////////////// // BEZIER //public float bezierPoint(float a, float b, float c, float d, float t) //public float bezierTangent(float a, float b, float c, float d, float t) //protected void bezierInitCheck() //protected void bezierInit() /** Ignored (not needed) in Java 2D. */ @Override public void bezierDetail(int detail) { } //public void bezier(float x1, float y1, // float x2, float y2, // float x3, float y3, // float x4, float y4) //public void bezier(float x1, float y1, float z1, // float x2, float y2, float z2, // float x3, float y3, float z3, // float x4, float y4, float z4) ////////////////////////////////////////////////////////////// // CURVE //public float curvePoint(float a, float b, float c, float d, float t) //public float curveTangent(float a, float b, float c, float d, float t) /** Ignored (not needed) in Java 2D. */ @Override public void curveDetail(int detail) { } //public void curveTightness(float tightness) //protected void curveInitCheck() //protected void curveInit() //public void curve(float x1, float y1, // float x2, float y2, // float x3, float y3, // float x4, float y4) //public void curve(float x1, float y1, float z1, // float x2, float y2, float z2, // float x3, float y3, float z3, // float x4, float y4, float z4) // ////////////////////////////////////////////////////////////// // // // SMOOTH // // // @Override // public void smooth() { // smooth = true; // // if (quality == 0) { // quality = 4; // change back to bicubic // } // // g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // RenderingHints.VALUE_ANTIALIAS_ON); // // g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, // quality == 4 ? // RenderingHints.VALUE_INTERPOLATION_BICUBIC : // RenderingHints.VALUE_INTERPOLATION_BILINEAR); // // // http://docs.oracle.com/javase/tutorial/2d/text/renderinghints.html // // Oracle Java text anti-aliasing on OS X looks like s*t compared to the // // text rendering with Apple's old Java 6. Below, several attempts to fix: // g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, // RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // // Turns out this is the one that actually makes things work. // // Kerning is still screwed up, however. // g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, // RenderingHints.VALUE_FRACTIONALMETRICS_ON); //// g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, //// RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); //// g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, //// RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); // //// g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, //// RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); // // } // // // @Override // public void smooth(int quality) { // this.quality = quality; // if (quality == 0) { // noSmooth(); // } else { // smooth(); // } // } // // // @Override // public void noSmooth() { // smooth = false; // quality = 0; // https://github.com/processing/processing/issues/3113 // g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // RenderingHints.VALUE_ANTIALIAS_OFF); // g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, // RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); // g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, // RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); // } ////////////////////////////////////////////////////////////// // IMAGE //public void imageMode(int mode) //public void image(PImage image, float x, float y) //public void image(PImage image, float x, float y, float c, float d) //public void image(PImage image, // float a, float b, float c, float d, // int u1, int v1, int u2, int v2) /** * Handle renderer-specific image drawing. */ @Override protected void imageImpl(PImage who, float x1, float y1, float x2, float y2, int u1, int v1, int u2, int v2) { // Image not ready yet, or an error if (who.width <= 0 || who.height <= 0) return; ImageCache cash = (ImageCache) getCache(who); // Nuke the cache if the image was resized if (cash != null) { if (who.pixelWidth != cash.image.getWidth() || who.pixelHeight != cash.image.getHeight()) { cash = null; } } if (cash == null) { //System.out.println("making new image cache"); cash = new ImageCache(); //who); setCache(who, cash); who.updatePixels(); // mark the whole thing for update who.setModified(); } // If image previously was tinted, or the color changed // or the image was tinted, and tint is now disabled if ((tint && !cash.tinted) || (tint && (cash.tintedColor != tintColor)) || (!tint && cash.tinted)) { // For tint change, mark all pixels as needing update. who.updatePixels(); } if (who.isModified()) { if (who.pixels == null) { // This might be a PGraphics that hasn't been drawn to yet. // Can't just bail because the cache has been created above. // https://github.com/processing/processing/issues/2208 who.pixels = new int[who.pixelWidth * who.pixelHeight]; } cash.update(who, tint, tintColor); who.setModified(false); } u1 *= who.pixelDensity; v1 *= who.pixelDensity; u2 *= who.pixelDensity; v2 *= who.pixelDensity; g2.drawImage(((ImageCache) getCache(who)).image, (int) x1, (int) y1, (int) x2, (int) y2, u1, v1, u2, v2, null); // Every few years I think "nah, Java2D couldn't possibly be that f*king // slow, why are we doing this by hand?" then comes the affirmation: // Composite oldComp = null; // if (false && tint) { // oldComp = g2.getComposite(); // int alpha = (tintColor >> 24) & 0xff; // System.out.println("using alpha composite"); // Composite alphaComp = // AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha / 255f); // g2.setComposite(alphaComp); // } // // long t = System.currentTimeMillis(); // g2.drawImage(who.getImage(), // (int) x1, (int) y1, (int) x2, (int) y2, // u1, v1, u2, v2, null); // System.out.println(System.currentTimeMillis() - t); // // if (oldComp != null) { // g2.setComposite(oldComp); // } } static class ImageCache { boolean tinted; int tintedColor; int[] tintedTemp; // one row of tinted pixels BufferedImage image; // BufferedImage compat; // public ImageCache(PImage source) { //// this.source = source; // // even if RGB, set the image type to ARGB, because the // // image may have an alpha value for its tint(). //// int type = BufferedImage.TYPE_INT_ARGB; // //System.out.println("making new buffered image"); //// image = new BufferedImage(source.width, source.height, type); // } /** * Update the pixels of the cache image. Already determined that the tint * has changed, or the pixels have changed, so should just go through * with the update without further checks. */ public void update(PImage source, boolean tint, int tintColor) { //int bufferType = BufferedImage.TYPE_INT_ARGB; int targetType = ARGB; boolean opaque = (tintColor & 0xFF000000) == 0xFF000000; if (source.format == RGB) { if (!tint || (tint && opaque)) { //bufferType = BufferedImage.TYPE_INT_RGB; targetType = RGB; } } // boolean wrongType = (image != null) && (image.getType() != bufferType); // if ((image == null) || wrongType) { // image = new BufferedImage(source.width, source.height, bufferType); // } // Must always use an ARGB image, otherwise will write zeros // in the alpha channel when drawn to the screen. // https://github.com/processing/processing/issues/2030 if (image == null) { image = new BufferedImage(source.pixelWidth, source.pixelHeight, BufferedImage.TYPE_INT_ARGB); } WritableRaster wr = image.getRaster(); if (tint) { if (tintedTemp == null || tintedTemp.length != source.pixelWidth) { tintedTemp = new int[source.pixelWidth]; } int a2 = (tintColor >> 24) & 0xff; // System.out.println("tint color is " + a2); // System.out.println("source.pixels[0] alpha is " + (source.pixels[0] >>> 24)); int r2 = (tintColor >> 16) & 0xff; int g2 = (tintColor >> 8) & 0xff; int b2 = (tintColor) & 0xff; //if (bufferType == BufferedImage.TYPE_INT_RGB) { if (targetType == RGB) { // The target image is opaque, meaning that the source image has no // alpha (is not ARGB), and the tint has no alpha. int index = 0; for (int y = 0; y < source.pixelHeight; y++) { for (int x = 0; x < source.pixelWidth; x++) { int argb1 = source.pixels[index++]; int r1 = (argb1 >> 16) & 0xff; int g1 = (argb1 >> 8) & 0xff; int b1 = (argb1) & 0xff; // Prior to 2.1, the alpha channel was commented out here, // but can't remember why (just thought unnecessary b/c of RGB?) // https://github.com/processing/processing/issues/2030 tintedTemp[x] = 0xFF000000 | (((r2 * r1) & 0xff00) << 8) | ((g2 * g1) & 0xff00) | (((b2 * b1) & 0xff00) >> 8); } wr.setDataElements(0, y, source.pixelWidth, 1, tintedTemp); } // could this be any slower? // float[] scales = { tintR, tintG, tintB }; // float[] offsets = new float[3]; // RescaleOp op = new RescaleOp(scales, offsets, null); // op.filter(image, image); //} else if (bufferType == BufferedImage.TYPE_INT_ARGB) { } else if (targetType == ARGB) { if (source.format == RGB && (tintColor & 0xffffff) == 0xffffff) { int hi = tintColor & 0xff000000; int index = 0; for (int y = 0; y < source.pixelHeight; y++) { for (int x = 0; x < source.pixelWidth; x++) { tintedTemp[x] = hi | (source.pixels[index++] & 0xFFFFFF); } wr.setDataElements(0, y, source.pixelWidth, 1, tintedTemp); } } else { int index = 0; for (int y = 0; y < source.pixelHeight; y++) { if (source.format == RGB) { int alpha = tintColor & 0xFF000000; for (int x = 0; x < source.pixelWidth; x++) { int argb1 = source.pixels[index++]; int r1 = (argb1 >> 16) & 0xff; int g1 = (argb1 >> 8) & 0xff; int b1 = (argb1) & 0xff; tintedTemp[x] = alpha | (((r2 * r1) & 0xff00) << 8) | ((g2 * g1) & 0xff00) | (((b2 * b1) & 0xff00) >> 8); } } else if (source.format == ARGB) { for (int x = 0; x < source.pixelWidth; x++) { int argb1 = source.pixels[index++]; int a1 = (argb1 >> 24) & 0xff; int r1 = (argb1 >> 16) & 0xff; int g1 = (argb1 >> 8) & 0xff; int b1 = (argb1) & 0xff; tintedTemp[x] = (((a2 * a1) & 0xff00) << 16) | (((r2 * r1) & 0xff00) << 8) | ((g2 * g1) & 0xff00) | (((b2 * b1) & 0xff00) >> 8); } } else if (source.format == ALPHA) { int lower = tintColor & 0xFFFFFF; for (int x = 0; x < source.pixelWidth; x++) { int a1 = source.pixels[index++]; tintedTemp[x] = (((a2 * a1) & 0xff00) << 16) | lower; } } wr.setDataElements(0, y, source.pixelWidth, 1, tintedTemp); } } // Not sure why ARGB images take the scales in this order... // float[] scales = { tintR, tintG, tintB, tintA }; // float[] offsets = new float[4]; // RescaleOp op = new RescaleOp(scales, offsets, null); // op.filter(image, image); } } else { // !tint if (targetType == RGB && (source.pixels[0] >> 24 == 0)) { // If it's an RGB image and the high bits aren't set, need to set // the high bits to opaque because we're drawing ARGB images. source.filter(OPAQUE); // Opting to just manipulate the image here, since it shouldn't // affect anything else (and alpha(get(x, y)) should return 0xff). // Wel also make no guarantees about the values of the pixels array // in a PImage and how the high bits will be set. } // If no tint, just shove the pixels on in there verbatim wr.setDataElements(0, 0, source.pixelWidth, source.pixelHeight, source.pixels); } this.tinted = tint; this.tintedColor = tintColor; // GraphicsConfiguration gc = parent.getGraphicsConfiguration(); // compat = gc.createCompatibleImage(image.getWidth(), // image.getHeight(), // Transparency.TRANSLUCENT); // // Graphics2D g = compat.createGraphics(); // g.drawImage(image, 0, 0, null); // g.dispose(); } } ////////////////////////////////////////////////////////////// // SHAPE //public void shapeMode(int mode) //public void shape(PShape shape) //public void shape(PShape shape, float x, float y) //public void shape(PShape shape, float x, float y, float c, float d) ////////////////////////////////////////////////////////////// // SHAPE I/O //public PShape loadShape(String filename) @Override public PShape loadShape(String filename, String options) { String extension = PApplet.getExtension(filename); if (extension.equals("svg") || extension.equals("svgz")) { return new PShapeJava2D(parent.loadXML(filename)); } PGraphics.showWarning("Unsupported format: " + filename); return null; } ////////////////////////////////////////////////////////////// // TEXT ATTRIBTUES //public void textAlign(int align) //public void textAlign(int alignX, int alignY) @Override public float textAscent() { if (textFont == null) { defaultFontOrDeath("textAscent"); } Font font = (Font) textFont.getNative(); if (font != null) { //return getFontMetrics(font).getAscent(); return g2.getFontMetrics(font).getAscent(); } return super.textAscent(); } @Override public float textDescent() { if (textFont == null) { defaultFontOrDeath("textDescent"); } Font font = (Font) textFont.getNative(); if (font != null) { //return getFontMetrics(font).getDescent(); return g2.getFontMetrics(font).getDescent(); } return super.textDescent(); } //public void textFont(PFont which) //public void textFont(PFont which, float size) //public void textLeading(float leading) //public void textMode(int mode) @Override protected boolean textModeCheck(int mode) { return mode == MODEL; } /** * Same as parent, but override for native version of the font. * <p/> * Called from textFontImpl and textSizeImpl, so the metrics * will get recorded properly. */ @Override protected void handleTextSize(float size) { // if a native version available, derive this font Font font = (Font) textFont.getNative(); // don't derive again if the font size has not changed if (font != null) { if (font.getSize2D() != size) { Map<TextAttribute, Object> map = new HashMap<>(); map.put(TextAttribute.SIZE, size); map.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); // map.put(TextAttribute.TRACKING, // TextAttribute.TRACKING_TIGHT); font = font.deriveFont(map); } g2.setFont(font); textFont.setNative(font); fontObject = font; /* Map<TextAttribute, ?> attrs = font.getAttributes(); for (TextAttribute ta : attrs.keySet()) { System.out.println(ta + " -> " + attrs.get(ta)); } */ } // take care of setting the textSize and textLeading vars // this has to happen second, because it calls textAscent() // (which requires the native font metrics to be set) super.handleTextSize(size); } //public float textWidth(char c) //public float textWidth(String str) @Override protected float textWidthImpl(char[] buffer, int start, int stop) { if (textFont == null) { defaultFontOrDeath("textWidth"); } // Avoid "Zero length string passed to TextLayout constructor" error if (start == stop) { return 0; } Font font = (Font) textFont.getNative(); // System.out.println(font); //if (font != null && (textFont.isStream() || hints[ENABLE_NATIVE_FONTS])) { if (font != null) { // System.out.println("using charswidth for " + new String(buffer, start, stop-start)); // maybe should use one of the newer/fancier functions for this? // int length = stop - start; // FontMetrics metrics = getFontMetrics(font); FontMetrics metrics = g2.getFontMetrics(font); // Using fractional metrics makes the measurement worse, not better, // at least on OS X 10.6 (November, 2010). // TextLayout returns the same value as charsWidth(). // System.err.println("using native"); // g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, // RenderingHints.VALUE_FRACTIONALMETRICS_ON); // float m1 = metrics.charsWidth(buffer, start, length); // float m2 = (float) metrics.getStringBounds(buffer, start, stop, g2).getWidth(); // TextLayout tl = new TextLayout(new String(buffer, start, length), font, g2.getFontRenderContext()); // float m3 = (float) tl.getBounds().getWidth(); // System.err.println(m1 + " " + m2 + " " + m3); ////// return m1; //// return m2; //// return metrics.charsWidth(buffer, start, length); // return m2; return (float) metrics.getStringBounds(buffer, start, stop, g2).getWidth(); } // System.err.println("not native"); return super.textWidthImpl(buffer, start, stop); } // protected void beginTextScreenMode() { // loadPixels(); // } // protected void endTextScreenMode() { // updatePixels(); // } ////////////////////////////////////////////////////////////// // TEXT // None of the variations of text() are overridden from PGraphics. ////////////////////////////////////////////////////////////// // TEXT IMPL //protected void textLineAlignImpl(char buffer[], int start, int stop, // float x, float y) @Override protected void textLineImpl(char[] buffer, int start, int stop, float x, float y) { Font font = (Font) textFont.getNative(); // if (font != null && (textFont.isStream() || hints[ENABLE_NATIVE_FONTS])) { if (font != null) { /* // save the current setting for text smoothing. note that this is // different from the smooth() function, because the font smoothing // is controlled when the font is created, not now as it's drawn. // fixed a bug in 0116 that handled this incorrectly. Object textAntialias = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); // override the current text smoothing setting based on the font // (don't change the global smoothing settings) g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textFont.smooth ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF); */ Object antialias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); if (antialias == null) { // if smooth() and noSmooth() not called, this will be null (0120) antialias = RenderingHints.VALUE_ANTIALIAS_DEFAULT; } // override the current smoothing setting based on the font // also changes global setting for antialiasing, but this is because it's // not possible to enable/disable them independently in some situations. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, textFont.isSmooth() ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF); g2.setColor(fillColorObject); int length = stop - start; if (length != 0) { g2.drawChars(buffer, start, length, (int) (x + 0.5f), (int) (y + 0.5f)); // better to use round here? also, drawChars now just calls drawString // g2.drawString(new String(buffer, start, stop - start), Math.round(x), Math.round(y)); // better to use drawString() with floats? (nope, draws the same) //g2.drawString(new String(buffer, start, length), x, y); // this didn't seem to help the scaling issue, and creates garbage // because of a fairly heavyweight new temporary object // java.awt.font.GlyphVector gv = // font.createGlyphVector(g2.getFontRenderContext(), new String(buffer, start, stop - start)); // g2.drawGlyphVector(gv, x, y); } // return to previous smoothing state if it was changed //g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textAntialias); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialias); } else { // otherwise just do the default super.textLineImpl(buffer, start, stop, x, y); } } // /** // * Convenience method to get a legit FontMetrics object. Where possible, // * override this any renderer subclass so that you're not using what's // * returned by getDefaultToolkit() to get your metrics. // */ // @SuppressWarnings("deprecation") // public FontMetrics getFontMetrics(Font font) { // ignore // Frame frame = parent.frame; // if (frame != null) { // return frame.getToolkit().getFontMetrics(font); // } // return Toolkit.getDefaultToolkit().getFontMetrics(font); // } // // // /** // * Convenience method to jump through some Java2D hoops and get an FRC. // */ // public FontRenderContext getFontRenderContext(Font font) { // ignore // return getFontMetrics(font).getFontRenderContext(); // } /* Toolkit toolkit; @SuppressWarnings("deprecation") protected FontMetrics getFontMetrics(Font font) { if (toolkit == null) { try { Canvas canvas = (Canvas) surface.getNative(); toolkit = canvas.getToolkit(); } catch (Exception e) { // May error out if it's a PSurfaceNone or similar toolkit = Toolkit.getDefaultToolkit(); } } return toolkit.getFontMetrics(font); //return (g2 != null) ? g2.getFontMetrics(font) : super.getFontMetrics(font); } */ ////////////////////////////////////////////////////////////// // MATRIX STACK @Override public void pushMatrix() { if (transformCount == transformStack.length) { throw new RuntimeException("pushMatrix() cannot use push more than " + transformStack.length + " times"); } transformStack[transformCount] = g2.getTransform(); transformCount++; } @Override public void popMatrix() { if (transformCount == 0) { throw new RuntimeException("missing a pushMatrix() " + "to go with that popMatrix()"); } transformCount--; g2.setTransform(transformStack[transformCount]); } ////////////////////////////////////////////////////////////// // MATRIX TRANSFORMS @Override public void translate(float tx, float ty) { g2.translate(tx, ty); } //public void translate(float tx, float ty, float tz) @Override public void rotate(float angle) { g2.rotate(angle); } @Override public void rotateX(float angle) { showDepthWarning("rotateX"); } @Override public void rotateY(float angle) { showDepthWarning("rotateY"); } @Override public void rotateZ(float angle) { showDepthWarning("rotateZ"); } @Override public void rotate(float angle, float vx, float vy, float vz) { showVariationWarning("rotate"); } @Override public void scale(float s) { g2.scale(s, s); } @Override public void scale(float sx, float sy) { g2.scale(sx, sy); } @Override public void scale(float sx, float sy, float sz) { showDepthWarningXYZ("scale"); } @Override public void shearX(float angle) { g2.shear(Math.tan(angle), 0); } @Override public void shearY(float angle) { g2.shear(0, Math.tan(angle)); } ////////////////////////////////////////////////////////////// // MATRIX MORE @Override public void resetMatrix() { g2.setTransform(new AffineTransform()); g2.scale(pixelDensity, pixelDensity); } //public void applyMatrix(PMatrix2D source) @Override public void applyMatrix(float n00, float n01, float n02, float n10, float n11, float n12) { //System.out.println("PGraphicsJava2D.applyMatrix()"); //System.out.println(new AffineTransform(n00, n10, n01, n11, n02, n12)); g2.transform(new AffineTransform(n00, n10, n01, n11, n02, n12)); //g2.transform(new AffineTransform(n00, n01, n02, n10, n11, n12)); } //public void applyMatrix(PMatrix3D source) @Override public void applyMatrix(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23, float n30, float n31, float n32, float n33) { showVariationWarning("applyMatrix"); } ////////////////////////////////////////////////////////////// // MATRIX GET/SET @Override public PMatrix getMatrix() { return getMatrix((PMatrix2D) null); } @Override public PMatrix2D getMatrix(PMatrix2D target) { if (target == null) { target = new PMatrix2D(); } g2.getTransform().getMatrix(transform); target.set((float) transform[0], (float) transform[2], (float) transform[4], (float) transform[1], (float) transform[3], (float) transform[5]); return target; } @Override public PMatrix3D getMatrix(PMatrix3D target) { showVariationWarning("getMatrix"); return target; } //public void setMatrix(PMatrix source) @Override public void setMatrix(PMatrix2D source) { g2.setTransform(new AffineTransform(source.m00, source.m10, source.m01, source.m11, source.m02, source.m12)); } @Override public void setMatrix(PMatrix3D source) { showVariationWarning("setMatrix"); } @Override public void printMatrix() { getMatrix((PMatrix2D) null).print(); } ////////////////////////////////////////////////////////////// // CAMERA and PROJECTION // Inherit the plaintive warnings from PGraphics //public void beginCamera() //public void endCamera() //public void camera() //public void camera(float eyeX, float eyeY, float eyeZ, // float centerX, float centerY, float centerZ, // float upX, float upY, float upZ) //public void printCamera() //public void ortho() //public void ortho(float left, float right, // float bottom, float top, // float near, float far) //public void perspective() //public void perspective(float fov, float aspect, float near, float far) //public void frustum(float left, float right, // float bottom, float top, // float near, float far) //public void printProjection() ////////////////////////////////////////////////////////////// // SCREEN and MODEL transforms @Override public float screenX(float x, float y) { g2.getTransform().getMatrix(transform); return (float)transform[0]*x + (float)transform[2]*y + (float)transform[4]; } @Override public float screenY(float x, float y) { g2.getTransform().getMatrix(transform); return (float)transform[1]*x + (float)transform[3]*y + (float)transform[5]; } @Override public float screenX(float x, float y, float z) { showDepthWarningXYZ("screenX"); return 0; } @Override public float screenY(float x, float y, float z) { showDepthWarningXYZ("screenY"); return 0; } @Override public float screenZ(float x, float y, float z) { showDepthWarningXYZ("screenZ"); return 0; } //public float modelX(float x, float y, float z) //public float modelY(float x, float y, float z) //public float modelZ(float x, float y, float z) ////////////////////////////////////////////////////////////// // STYLE // pushStyle(), popStyle(), style() and getStyle() inherited. ////////////////////////////////////////////////////////////// // STROKE CAP/JOIN/WEIGHT @Override public void strokeCap(int cap) { super.strokeCap(cap); strokeImpl(); } @Override public void strokeJoin(int join) { super.strokeJoin(join); strokeImpl(); } @Override public void strokeWeight(float weight) { super.strokeWeight(weight); strokeImpl(); } protected void strokeImpl() { int cap = BasicStroke.CAP_BUTT; if (strokeCap == ROUND) { cap = BasicStroke.CAP_ROUND; } else if (strokeCap == PROJECT) { cap = BasicStroke.CAP_SQUARE; } int join = BasicStroke.JOIN_BEVEL; if (strokeJoin == MITER) { join = BasicStroke.JOIN_MITER; } else if (strokeJoin == ROUND) { join = BasicStroke.JOIN_ROUND; } strokeObject = new BasicStroke(strokeWeight, cap, join); g2.setStroke(strokeObject); } ////////////////////////////////////////////////////////////// // STROKE // noStroke() and stroke() inherited from PGraphics. @Override protected void strokeFromCalc() { super.strokeFromCalc(); strokeColorObject = new Color(strokeColor, true); strokeGradient = false; } ////////////////////////////////////////////////////////////// // TINT // noTint() and tint() inherited from PGraphics. @Override protected void tintFromCalc() { super.tintFromCalc(); // TODO actually implement tinted images tintColorObject = new Color(tintColor, true); } ////////////////////////////////////////////////////////////// // FILL // noFill() and fill() inherited from PGraphics. @Override protected void fillFromCalc() { super.fillFromCalc(); fillColorObject = new Color(fillColor, true); fillGradient = false; } ////////////////////////////////////////////////////////////// // MATERIAL PROPERTIES //public void ambient(int rgb) //public void ambient(float gray) //public void ambient(float x, float y, float z) //protected void ambientFromCalc() //public void specular(int rgb) //public void specular(float gray) //public void specular(float x, float y, float z) //protected void specularFromCalc() //public void shininess(float shine) //public void emissive(int rgb) //public void emissive(float gray) //public void emissive(float x, float y, float z ) //protected void emissiveFromCalc() ////////////////////////////////////////////////////////////// // LIGHTS //public void lights() //public void noLights() //public void ambientLight(float red, float green, float blue) //public void ambientLight(float red, float green, float blue, // float x, float y, float z) //public void directionalLight(float red, float green, float blue, // float nx, float ny, float nz) //public void pointLight(float red, float green, float blue, // float x, float y, float z) //public void spotLight(float red, float green, float blue, // float x, float y, float z, // float nx, float ny, float nz, // float angle, float concentration) //public void lightFalloff(float constant, float linear, float quadratic) //public void lightSpecular(float x, float y, float z) //protected void lightPosition(int num, float x, float y, float z) //protected void lightDirection(int num, float x, float y, float z) ////////////////////////////////////////////////////////////// // BACKGROUND int[] clearPixels; protected void clearPixels(int color) { // On a hi-res display, image may be larger than width/height int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); // Create a small array that can be used to set the pixels several times. // Using a single-pixel line of length 'width' is a tradeoff between // speed (setting each pixel individually is too slow) and memory // (an array for width*height would waste lots of memory if it stayed // resident, and would terrify the gc if it were re-created on each trip // to background(). // WritableRaster raster = ((BufferedImage) image).getRaster(); // WritableRaster raster = image.getRaster(); WritableRaster raster = getRaster(); if ((clearPixels == null) || (clearPixels.length < imageWidth)) { clearPixels = new int[imageWidth]; } Arrays.fill(clearPixels, 0, imageWidth, backgroundColor); for (int i = 0; i < imageHeight; i++) { raster.setDataElements(0, i, imageWidth, 1, clearPixels); } } // background() methods inherited from PGraphics, along with the // PImage version of backgroundImpl(), since it just calls set(). //public void backgroundImpl(PImage image) @Override public void backgroundImpl() { if (backgroundAlpha) { clearPixels(backgroundColor); } else { Color bgColor = new Color(backgroundColor); // seems to fire an additional event that causes flickering, // like an extra background erase on OS X // if (canvas != null) { // canvas.setBackground(bgColor); // } //new Exception().printStackTrace(System.out); // in case people do transformations before background(), // need to handle this with a push/reset/pop Composite oldComposite = g2.getComposite(); g2.setComposite(defaultComposite); pushMatrix(); resetMatrix(); g2.setColor(bgColor); //, backgroundAlpha)); // g2.fillRect(0, 0, width, height); // On a hi-res display, image may be larger than width/height if (image != null) { // image will be null in subclasses (i.e. PDF) g2.fillRect(0, 0, image.getWidth(null), image.getHeight(null)); } else { // hope for the best if image is null g2.fillRect(0, 0, width, height); } popMatrix(); g2.setComposite(oldComposite); } } ////////////////////////////////////////////////////////////// // COLOR MODE // All colorMode() variations are inherited from PGraphics. ////////////////////////////////////////////////////////////// // COLOR CALC // colorCalc() and colorCalcARGB() inherited from PGraphics. ////////////////////////////////////////////////////////////// // COLOR DATATYPE STUFFING // final color() variations inherited. ////////////////////////////////////////////////////////////// // COLOR DATATYPE EXTRACTION // final methods alpha, red, green, blue, // hue, saturation, and brightness all inherited. ////////////////////////////////////////////////////////////// // COLOR DATATYPE INTERPOLATION // both lerpColor variants inherited. ////////////////////////////////////////////////////////////// // BEGIN/END RAW @Override public void beginRaw(PGraphics recorderRaw) { showMethodWarning("beginRaw"); } @Override public void endRaw() { showMethodWarning("endRaw"); } ////////////////////////////////////////////////////////////// // WARNINGS and EXCEPTIONS // showWarning and showException inherited. ////////////////////////////////////////////////////////////// // RENDERER SUPPORT QUERIES //public boolean displayable() // true //public boolean is2D() // true //public boolean is3D() // false ////////////////////////////////////////////////////////////// // PIMAGE METHODS // getImage, setCache, getCache, removeCache, isModified, setModified protected WritableRaster getRaster() { WritableRaster raster = null; if (primaryGraphics) { /* // 'offscreen' will probably be removed in the next release if (useOffscreen) { raster = offscreen.getRaster(); } else*/ if (image instanceof VolatileImage) { // when possible, we'll try VolatileImage raster = ((VolatileImage) image).getSnapshot().getRaster(); } } if (raster == null) { raster = ((BufferedImage) image).getRaster(); } // On Raspberry Pi (and perhaps other platforms, the color buffer won't // necessarily be the int array that we'd like. Need to convert it here. // Not that this would probably mean getRaster() would need to work more // like loadRaster/updateRaster because the pixels will need to be // temporarily moved to (and later from) a buffer that's understood by // the rest of the Processing source. // https://github.com/processing/processing/issues/2010 if (raster.getTransferType() != DataBuffer.TYPE_INT) { System.err.println("See https://github.com/processing/processing/issues/2010"); throw new RuntimeException("Pixel operations are not supported on this device."); } return raster; } @Override public void loadPixels() { if (pixels == null || (pixels.length != pixelWidth*pixelHeight)) { pixels = new int[pixelWidth * pixelHeight]; } WritableRaster raster = getRaster(); raster.getDataElements(0, 0, pixelWidth, pixelHeight, pixels); if (raster.getNumBands() == 3) { // Java won't set the high bits when RGB, returns 0 for alpha // https://github.com/processing/processing/issues/2030 for (int i = 0; i < pixels.length; i++) { pixels[i] = 0xff000000 | pixels[i]; } } //((BufferedImage) image).getRGB(0, 0, width, height, pixels, 0, width); // WritableRaster raster = ((BufferedImage) (useOffscreen && primarySurface ? offscreen : image)).getRaster(); // WritableRaster raster = image.getRaster(); } // /** // * Update the pixels[] buffer to the PGraphics image. // * <P> // * Unlike in PImage, where updatePixels() only requests that the // * update happens, in PGraphicsJava2D, this will happen immediately. // */ // @Override // public void updatePixels() { // //updatePixels(0, 0, width, height); //// WritableRaster raster = ((BufferedImage) (useOffscreen && primarySurface ? offscreen : image)).getRaster(); //// WritableRaster raster = image.getRaster(); // updatePixels(0, 0, width, height); // } /** * Update the pixels[] buffer to the PGraphics image. * <P> * Unlike in PImage, where updatePixels() only requests that the * update happens, in PGraphicsJava2D, this will happen immediately. */ @Override public void updatePixels(int x, int y, int c, int d) { //if ((x == 0) && (y == 0) && (c == width) && (d == height)) { // System.err.format("%d %d %d %d .. w/h = %d %d .. pw/ph = %d %d %n", x, y, c, d, width, height, pixelWidth, pixelHeight); if ((x != 0) || (y != 0) || (c != pixelWidth) || (d != pixelHeight)) { // Show a warning message, but continue anyway. showVariationWarning("updatePixels(x, y, w, h)"); // new Exception().printStackTrace(System.out); } // updatePixels(); if (pixels != null) { getRaster().setDataElements(0, 0, pixelWidth, pixelHeight, pixels); } modified = true; } // @Override // protected void updatePixelsImpl(int x, int y, int w, int h) { // super.updatePixelsImpl(x, y, w, h); // // if ((x != 0) || (y != 0) || (w != width) || (h != height)) { // // Show a warning message, but continue anyway. // showVariationWarning("updatePixels(x, y, w, h)"); // } // getRaster().setDataElements(0, 0, width, height, pixels); // } ////////////////////////////////////////////////////////////// // GET/SET static int[] getset = new int[1]; @Override public int get(int x, int y) { if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return 0; //return ((BufferedImage) image).getRGB(x, y); // WritableRaster raster = ((BufferedImage) (useOffscreen && primarySurface ? offscreen : image)).getRaster(); WritableRaster raster = getRaster(); raster.getDataElements(x, y, getset); if (raster.getNumBands() == 3) { // https://github.com/processing/processing/issues/2030 return getset[0] | 0xff000000; } return getset[0]; } //public PImage get(int x, int y, int w, int h) @Override protected void getImpl(int sourceX, int sourceY, int sourceWidth, int sourceHeight, PImage target, int targetX, int targetY) { // last parameter to getRGB() is the scan size of the *target* buffer //((BufferedImage) image).getRGB(x, y, w, h, output.pixels, 0, w); // WritableRaster raster = // ((BufferedImage) (useOffscreen && primarySurface ? offscreen : image)).getRaster(); WritableRaster raster = getRaster(); if (sourceWidth == target.pixelWidth && sourceHeight == target.pixelHeight) { raster.getDataElements(sourceX, sourceY, sourceWidth, sourceHeight, target.pixels); // https://github.com/processing/processing/issues/2030 if (raster.getNumBands() == 3) { target.filter(OPAQUE); } } else { // TODO optimize, incredibly inefficient to reallocate this much memory int[] temp = new int[sourceWidth * sourceHeight]; raster.getDataElements(sourceX, sourceY, sourceWidth, sourceHeight, temp); // Copy the temporary output pixels over to the outgoing image int sourceOffset = 0; int targetOffset = targetY*target.pixelWidth + targetX; for (int y = 0; y < sourceHeight; y++) { if (raster.getNumBands() == 3) { for (int i = 0; i < sourceWidth; i++) { // Need to set the high bits for this feller // https://github.com/processing/processing/issues/2030 target.pixels[targetOffset + i] = 0xFF000000 | temp[sourceOffset + i]; } } else { System.arraycopy(temp, sourceOffset, target.pixels, targetOffset, sourceWidth); } sourceOffset += sourceWidth; targetOffset += target.pixelWidth; } } } @Override public void set(int x, int y, int argb) { if ((x < 0) || (y < 0) || (x >= pixelWidth) || (y >= pixelHeight)) return; // ((BufferedImage) image).setRGB(x, y, argb); getset[0] = argb; // WritableRaster raster = ((BufferedImage) (useOffscreen && primarySurface ? offscreen : image)).getRaster(); // WritableRaster raster = image.getRaster(); getRaster().setDataElements(x, y, getset); } //public void set(int x, int y, PImage img) @Override protected void setImpl(PImage sourceImage, int sourceX, int sourceY, int sourceWidth, int sourceHeight, int targetX, int targetY) { WritableRaster raster = getRaster(); // ((BufferedImage) (useOffscreen && primarySurface ? offscreen : image)).getRaster(); if ((sourceX == 0) && (sourceY == 0) && (sourceWidth == sourceImage.pixelWidth) && (sourceHeight == sourceImage.pixelHeight)) { // System.out.format("%d %d %dx%d %d%n", targetX, targetY, // sourceImage.width, sourceImage.height, // sourceImage.pixels.length); raster.setDataElements(targetX, targetY, sourceImage.pixelWidth, sourceImage.pixelHeight, sourceImage.pixels); } else { // TODO optimize, incredibly inefficient to reallocate this much memory PImage temp = sourceImage.get(sourceX, sourceY, sourceWidth, sourceHeight); raster.setDataElements(targetX, targetY, temp.pixelWidth, temp.pixelHeight, temp.pixels); } } ////////////////////////////////////////////////////////////// // MASK static final String MASK_WARNING = "mask() cannot be used on the main drawing surface"; @Override public void mask(int[] alpha) { if (primaryGraphics) { showWarning(MASK_WARNING); } else { super.mask(alpha); } } @Override public void mask(PImage alpha) { if (primaryGraphics) { showWarning(MASK_WARNING); } else { super.mask(alpha); } } ////////////////////////////////////////////////////////////// // FILTER // Because the PImage versions call loadPixels() and // updatePixels(), no need to override anything here. //public void filter(int kind) //public void filter(int kind, float param) ////////////////////////////////////////////////////////////// // COPY @Override public void copy(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if ((sw != dw) || (sh != dh)) { g2.drawImage(image, dx, dy, dx + dw, dy + dh, sx, sy, sx + sw, sy + sh, null); } else { dx = dx - sx; // java2d's "dx" is the delta, not dest dy = dy - sy; g2.copyArea(sx, sy, sw, sh, dx, dy); } } @Override public void copy(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { g2.drawImage((Image) src.getNative(), dx, dy, dx + dw, dy + dh, sx, sy, sx + sw, sy + sh, null); } ////////////////////////////////////////////////////////////// // BLEND // static public int blendColor(int c1, int c2, int mode) // public void blend(int sx, int sy, int sw, int sh, // int dx, int dy, int dw, int dh, int mode) // public void blend(PImage src, // int sx, int sy, int sw, int sh, // int dx, int dy, int dw, int dh, int mode) ////////////////////////////////////////////////////////////// // SAVE // public void save(String filename) { // loadPixels(); // super.save(filename); // } }
processing/processing
core/src/processing/awt/PGraphicsJava2D.java
2,183
/* * 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
2,184
package org.telegram.ui; import static org.telegram.messenger.AndroidUtilities.dp; import static org.telegram.messenger.AndroidUtilities.translitSafe; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.app.Activity; import android.app.Dialog; import android.app.Notification; import android.content.Context; import android.content.ContextWrapper; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.LinearGradient; 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.Shader; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcelable; import android.os.SystemClock; import android.text.Editable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; import android.text.style.ForegroundColorSpan; import android.util.LongSparseArray; import android.util.SparseArray; import android.util.SparseIntArray; import android.util.TypedValue; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import android.view.ViewTreeObserver; import android.view.Window; import android.view.WindowInsets; import android.view.WindowManager; import android.view.animation.LinearInterpolator; import android.view.animation.OvershootInterpolator; import android.view.inputmethod.EditorInfo; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.core.graphics.ColorUtils; import androidx.core.math.MathUtils; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearSmoothScrollerCustom; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AnimationNotificationsLocker; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.DocumentObject; import org.telegram.messenger.Emoji; import org.telegram.messenger.EmojiData; 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.LiteMode; import org.telegram.messenger.LocaleController; 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.SharedConfig; import org.telegram.messenger.SvgHelper; 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.ActionBarMenuItem; import org.telegram.ui.ActionBar.ActionBarPopupWindow; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BottomSheet; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Cells.FixedHeightEmptyCell; import org.telegram.ui.Components.AlertsCreator; import org.telegram.ui.Components.AnimatedEmojiDrawable; import org.telegram.ui.Components.AnimatedEmojiSpan; import org.telegram.ui.Components.AnimatedTextView; import org.telegram.ui.Components.BackupImageView; import org.telegram.ui.Components.CloseProgressDrawable2; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.DrawingInBackgroundThreadDrawable; import org.telegram.ui.Components.EditTextCaption; import org.telegram.ui.Components.EmojiPacksAlert; import org.telegram.ui.Components.EmojiTabsStrip; import org.telegram.ui.Components.EmojiView; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.Premium.PremiumButtonView; import org.telegram.ui.Components.Premium.PremiumFeatureBottomSheet; import org.telegram.ui.Components.Premium.PremiumLockIconView; import org.telegram.ui.Components.RLottieImageView; import org.telegram.ui.Components.Reactions.HwEmojis; import org.telegram.ui.Components.Reactions.ReactionsEffectOverlay; import org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble; import org.telegram.ui.Components.Reactions.ReactionsUtils; import org.telegram.ui.Components.RecyclerAnimationScrollHelper; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.SearchStateDrawable; import org.telegram.ui.Components.StickerCategoriesListView; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; public class SelectAnimatedEmojiDialog extends FrameLayout implements NotificationCenter.NotificationCenterDelegate { public final static int TYPE_EMOJI_STATUS = 0; public final static int TYPE_REACTIONS = 1; public final static int TYPE_SET_DEFAULT_REACTION = 2; public static final int TYPE_TOPIC_ICON = 3; public static final int TYPE_AVATAR_CONSTRUCTOR = 4; public final static int TYPE_SET_REPLY_ICON = 5; public static final int TYPE_CHAT_REACTIONS = 6; public final static int TYPE_SET_REPLY_ICON_BOTTOM = 7; public final static int TYPE_EXPANDABLE_REACTIONS = 8; public final static int TYPE_EMOJI_STATUS_CHANNEL = 9; public final static int TYPE_EMOJI_STATUS_CHANNEL_TOP = 10; public final static int TYPE_TAGS = 11; public final static int TYPE_EMOJI_STATUS_TOP = 12; public final static int TYPE_STICKER_SET_EMOJI = 13; public boolean isBottom() { return type == TYPE_SET_REPLY_ICON || type == TYPE_EMOJI_STATUS_CHANNEL_TOP || type == TYPE_EMOJI_STATUS_TOP; } private final int SPAN_COUNT_FOR_EMOJI = 8; private final int SPAN_COUNT_FOR_STICKER = 5; private final int SPAN_COUNT = 40; private final int RECENT_MAX_LINES = 5; private final int EXPAND_MAX_LINES = 3; private int searchRow; private int recentReactionsStartRow; private int recentReactionsEndRow; private int topReactionsStartRow; private int topReactionsEndRow; private int recentReactionsSectionRow; private int popularSectionRow; private int longtapHintRow; private int defaultTopicIconRow; private int topicEmojiHeaderRow; private EmojiPackExpand recentExpandButton; public onLongPressedListener bigReactionListener; public SelectAnimatedEmojiDialog.onRecentClearedListener onRecentClearedListener; private boolean isAttached; HashSet<ReactionsLayoutInBubble.VisibleReaction> selectedReactions = new HashSet<>(); HashSet<Long> selectedDocumentIds = new HashSet(); public Paint selectorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); public Paint selectorAccentPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Drawable forumIconDrawable; private ImageViewEmoji forumIconImage; private boolean animationsEnabled; private boolean showStickers; public boolean forUser; private ArrayList<TLRPC.TL_messages_stickerSet> stickerSets = new ArrayList<>(); private boolean enterAnimationInProgress; private BackgroundDelegate backgroundDelegate; public void putAnimatedEmojiToCache(AnimatedEmojiDrawable animatedEmojiDrawable) { emojiGridView.animatedEmojiDrawables.put(animatedEmojiDrawable.getDocumentId(), animatedEmojiDrawable); } public void setSelectedReactions(HashSet<ReactionsLayoutInBubble.VisibleReaction> selectedReactions) { this.selectedReactions = selectedReactions; selectedDocumentIds.clear(); ArrayList<ReactionsLayoutInBubble.VisibleReaction> arrayList = new ArrayList<>(selectedReactions); for (int i = 0; i < arrayList.size(); i++) { if (arrayList.get(i).documentId != 0) { selectedDocumentIds.add(arrayList.get(i).documentId); } } } public void setSelectedReaction(ReactionsLayoutInBubble.VisibleReaction reaction) { selectedReactions.clear(); selectedReactions.add(reaction); if (emojiGridView != null) { for (int i = 0; i < emojiGridView.getChildCount(); i++) { if (emojiGridView.getChildAt(i) instanceof ImageViewEmoji) { ImageViewEmoji imageViewEmoji = (ImageViewEmoji) emojiGridView.getChildAt(i); imageViewEmoji.setViewSelected(selectedReactions.contains(imageViewEmoji.reaction), true); } } emojiGridView.invalidate(); } } public void setSelectedReactions(ArrayList<String> emojis) { selectedReactions.clear(); for (String emoji : emojis) { selectedReactions.add(ReactionsLayoutInBubble.VisibleReaction.fromEmojicon(emoji)); } if (emojiGridView != null) { for (int i = 0; i < emojiGridView.getChildCount(); i++) { if (emojiGridView.getChildAt(i) instanceof ImageViewEmoji) { ImageViewEmoji imageViewEmoji = (ImageViewEmoji) emojiGridView.getChildAt(i); imageViewEmoji.setViewSelected(selectedReactions.contains(imageViewEmoji.reaction), true); } } emojiGridView.invalidate(); } } public void setForUser(boolean forUser) { this.forUser = forUser; updateRows(false, false); } public void invalidateSearchBox() { searchBox.invalidate(); } public static class SelectAnimatedEmojiDialogWindow extends PopupWindow { private static final Field superListenerField; private ViewTreeObserver.OnScrollChangedListener mSuperScrollListener; private ViewTreeObserver mViewTreeObserver; private static final ViewTreeObserver.OnScrollChangedListener NOP = () -> { /* do nothing */ }; static { Field f = null; try { f = PopupWindow.class.getDeclaredField("mOnScrollChangedListener"); f.setAccessible(true); } catch (NoSuchFieldException e) { /* ignored */ } superListenerField = f; } public SelectAnimatedEmojiDialogWindow(View anchor) { super(anchor); init(); } public SelectAnimatedEmojiDialogWindow(View anchor, int width, int height) { super(anchor, width, height); init(); } private void init() { setFocusable(true); setAnimationStyle(0); setOutsideTouchable(true); setClippingEnabled(true); setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_FROM_FOCUSABLE); setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); if (superListenerField != null) { try { mSuperScrollListener = (ViewTreeObserver.OnScrollChangedListener) superListenerField.get(this); superListenerField.set(this, NOP); } catch (Exception e) { mSuperScrollListener = null; } } } private void unregisterListener() { if (mSuperScrollListener != null && mViewTreeObserver != null) { if (mViewTreeObserver.isAlive()) { mViewTreeObserver.removeOnScrollChangedListener(mSuperScrollListener); } mViewTreeObserver = null; } } private void registerListener(View anchor) { if (getContentView() instanceof SelectAnimatedEmojiDialog) { ((SelectAnimatedEmojiDialog) getContentView()).onShow(this::dismiss); } if (mSuperScrollListener != null) { ViewTreeObserver vto = (anchor.getWindowToken() != null) ? anchor.getViewTreeObserver() : null; if (vto != mViewTreeObserver) { if (mViewTreeObserver != null && mViewTreeObserver.isAlive()) { mViewTreeObserver.removeOnScrollChangedListener(mSuperScrollListener); } if ((mViewTreeObserver = vto) != null) { vto.addOnScrollChangedListener(mSuperScrollListener); } } } } public void dimBehind() { View container = getContentView().getRootView(); Context context = getContentView().getContext(); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams(); p.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND; p.dimAmount = 0.2f; wm.updateViewLayout(container, p); } private void dismissDim() { View container = getContentView().getRootView(); Context context = getContentView().getContext(); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (container.getLayoutParams() == null || !(container.getLayoutParams() instanceof WindowManager.LayoutParams)) { return; } WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams(); try { if ((p.flags & WindowManager.LayoutParams.FLAG_DIM_BEHIND) != 0) { p.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND; p.dimAmount = 0.0f; wm.updateViewLayout(container, p); } } catch (Exception ignore) { } } @Override public void showAsDropDown(View anchor) { super.showAsDropDown(anchor); registerListener(anchor); } @Override public void showAsDropDown(View anchor, int xoff, int yoff) { super.showAsDropDown(anchor, xoff, yoff); registerListener(anchor); } @Override public void showAsDropDown(View anchor, int xoff, int yoff, int gravity) { super.showAsDropDown(anchor, xoff, yoff, gravity); registerListener(anchor); } @Override public void showAtLocation(View parent, int gravity, int x, int y) { super.showAtLocation(parent, gravity, x, y); unregisterListener(); } @Override public void dismiss() { if (getContentView() instanceof SelectAnimatedEmojiDialog) { ((SelectAnimatedEmojiDialog) getContentView()).onDismiss(super::dismiss); dismissDim(); } else { super.dismiss(); } } } private final int currentAccount = UserConfig.selectedAccount; private int type; public FrameLayout contentView; private View backgroundView; private EmojiTabsStrip[] cachedEmojiTabs = new EmojiTabsStrip[2]; public EmojiTabsStrip emojiTabs; public View emojiTabsShadow; public SearchBox searchBox; public FrameLayout gridViewContainer; public EmojiListView emojiGridView; public EmojiListView emojiSearchGridView; public FrameLayout emojiSearchEmptyView; public FrameLayout emojiGridViewContainer; private BackupImageView emojiSearchEmptyViewImageView; private View bubble1View; private View bubble2View; private View topGradientView; private View bottomGradientView; private Adapter adapter; private SearchAdapter searchAdapter; private GridLayoutManager layoutManager; private GridLayoutManager searchLayoutManager; private RecyclerAnimationScrollHelper scrollHelper; private View contentViewForeground; private int totalCount; private ArrayList<Long> rowHashCodes = new ArrayList<>(); private SparseIntArray positionToSection = new SparseIntArray(); private SparseIntArray sectionToPosition = new SparseIntArray(); private SparseIntArray positionToExpand = new SparseIntArray(); private SparseIntArray positionToButton = new SparseIntArray(); private ArrayList<Long> expandedEmojiSets = new ArrayList<>(); private ArrayList<Long> installedEmojiSets = new ArrayList<>(); private boolean recentExpanded = false; private ArrayList<AnimatedEmojiSpan> recent = new ArrayList<>(); private ArrayList<TLRPC.Document> recentStickers = new ArrayList<>(); private ArrayList<String> standardEmojis = new ArrayList<>(); private ArrayList<ReactionsLayoutInBubble.VisibleReaction> topReactions = new ArrayList<>(); private ArrayList<ReactionsLayoutInBubble.VisibleReaction> recentReactions = new ArrayList<>(); private ArrayList<AnimatedEmojiSpan> defaultStatuses = new ArrayList<>(); private ArrayList<TLRPC.TL_messages_stickerSet> frozenEmojiPacks = new ArrayList<>(); private ArrayList<EmojiView.EmojiPack> packs = new ArrayList<>(); private boolean includeEmpty = false; public boolean includeHint = false; private Integer hintExpireDate; private boolean drawBackground = true; private List<ReactionsLayoutInBubble.VisibleReaction> recentReactionsToSet; ImageViewEmoji selectedReactionView; public boolean cancelPressed; float pressedProgress; ImageReceiver bigReactionImageReceiver = new ImageReceiver(); AnimatedEmojiDrawable bigReactionAnimatedEmoji; private SelectStatusDurationDialog selectStatusDateDialog; private Integer emojiX; private Theme.ResourcesProvider resourcesProvider; private float scaleX, scaleY; private BaseFragment baseFragment; private int topMarginDp; DefaultItemAnimator emojiItemAnimator; private int accentColor; public boolean useAccentForPlus; protected void invalidateParent() { } public SelectAnimatedEmojiDialog(BaseFragment baseFragment, Context context, boolean includeEmpty, Theme.ResourcesProvider resourcesProvider) { this(baseFragment, context, includeEmpty, null, TYPE_EMOJI_STATUS, resourcesProvider); } public SelectAnimatedEmojiDialog(BaseFragment baseFragment, Context context, boolean includeEmpty, Integer emojiX, int type, Theme.ResourcesProvider resourcesProvider) { this(baseFragment, context, includeEmpty, emojiX, type, true, resourcesProvider, 16); } public SelectAnimatedEmojiDialog(BaseFragment baseFragment, Context context, boolean includeEmpty, Integer emojiX, int type, boolean shouldDrawBackground, Theme.ResourcesProvider resourcesProvider, int topPaddingDp) { this(baseFragment, context, includeEmpty, emojiX, type, shouldDrawBackground, resourcesProvider, topPaddingDp, Theme.getColor(Theme.key_windowBackgroundWhiteBlueIcon, resourcesProvider)); } public SelectAnimatedEmojiDialog(BaseFragment baseFragment, Context context, boolean includeEmpty, Integer emojiX, int type, boolean shouldDrawBackground, Theme.ResourcesProvider resourcesProvider, int topPaddingDp, int accentColor) { super(context); this.resourcesProvider = resourcesProvider; this.type = type; this.includeEmpty = includeEmpty; this.baseFragment = baseFragment; this.includeHint = MessagesController.getGlobalMainSettings().getInt("emoji" + (type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP ? "status" : "reaction") + "usehint", 0) < 3; this.accentColor = accentColor; selectorPaint.setColor(Theme.getColor(Theme.key_listSelector, resourcesProvider)); selectorAccentPaint.setColor(ColorUtils.setAlphaComponent(accentColor, 30)); premiumStarColorFilter = new PorterDuffColorFilter(accentColor, PorterDuff.Mode.SRC_IN); this.emojiX = emojiX; final Integer bubbleX = emojiX == null ? null : MathUtils.clamp(emojiX, AndroidUtilities.dp(26), AndroidUtilities.dp(340 - 48)); boolean bubbleRight = bubbleX != null && bubbleX > AndroidUtilities.dp(170); setFocusableInTouchMode(true); if (type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP || type == TYPE_SET_DEFAULT_REACTION || type == TYPE_SET_REPLY_ICON || type == TYPE_SET_REPLY_ICON_BOTTOM) { topMarginDp = topPaddingDp; setPadding(AndroidUtilities.dp(4), AndroidUtilities.dp(4), AndroidUtilities.dp(4), AndroidUtilities.dp(4)); setOnTouchListener((v, e) -> { if (e.getAction() == MotionEvent.ACTION_DOWN && dismiss != null) { dismiss.run(); return true; } return false; }); } if (bubbleX != null) { bubble1View = new View(context); Drawable bubble1Drawable = getResources().getDrawable(R.drawable.shadowed_bubble1).mutate(); bubble1Drawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground, resourcesProvider), PorterDuff.Mode.MULTIPLY)); bubble1View.setBackground(bubble1Drawable); addView(bubble1View, LayoutHelper.createFrame(10, 10, (isBottom() ? Gravity.BOTTOM : Gravity.TOP) | Gravity.LEFT, bubbleX / AndroidUtilities.density + (bubbleRight ? -12 : 4), (isBottom() ? 0 : topMarginDp), 0, (isBottom() ? topMarginDp : 0))); } backgroundView = new View(context) { @Override protected void onDraw(Canvas canvas) { if (!drawBackground) { super.dispatchDraw(canvas); return; } canvas.drawColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground, resourcesProvider)); } }; boolean needBackgroundShadow = type == TYPE_TOPIC_ICON || type == TYPE_AVATAR_CONSTRUCTOR; contentView = new FrameLayout(context) { private final Path pathApi20 = new Path(); private final Paint paintApi20 = new Paint(Paint.ANTI_ALIAS_FLAG); private final boolean beforeLollipop = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP; @Override protected void dispatchDraw(Canvas canvas) { if (!drawBackground) { super.dispatchDraw(canvas); return; } if (beforeLollipop) { canvas.save(); if (needBackgroundShadow) { Theme.applyDefaultShadow(paintApi20); } paintApi20.setColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground, resourcesProvider)); paintApi20.setAlpha((int) (255 * getAlpha())); float px = (bubbleX == null ? getWidth() / 2f : bubbleX) + AndroidUtilities.dp(20); float w = getWidth() - getPaddingLeft() - getPaddingRight(); float h = getHeight() - getPaddingBottom() - getPaddingTop(); if (isBottom()) { AndroidUtilities.rectTmp.set( (getPaddingLeft() + (px - px * scaleX)), (getPaddingTop() + h * (1f - scaleY)), (getPaddingLeft() + px + (w - px) * scaleX), (getPaddingTop() + h) ); } else { AndroidUtilities.rectTmp.set( (getPaddingLeft() + (px - px * scaleX)), getPaddingTop(), (getPaddingLeft() + px + (w - px) * scaleX), (getPaddingTop() + h * scaleY) ); } pathApi20.rewind(); pathApi20.addRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(12), AndroidUtilities.dp(12), Path.Direction.CW); canvas.drawPath(pathApi20, paintApi20); canvas.clipPath(pathApi20); super.dispatchDraw(canvas); canvas.restore(); } else { super.dispatchDraw(canvas); } } }; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && type != TYPE_AVATAR_CONSTRUCTOR) { contentView.setOutlineProvider(new ViewOutlineProvider() { private final Rect rect = new Rect(); @Override public void getOutline(View view, Outline outline) { float px = (bubbleX == null ? view.getWidth() / 2f : bubbleX) + AndroidUtilities.dp(20); float w = view.getWidth() - view.getPaddingLeft() - view.getPaddingRight(); float h = view.getHeight() - view.getPaddingBottom() - view.getPaddingTop(); if (isBottom()) { rect.set( (int) (view.getPaddingLeft() + (px - px * scaleX)), (int) (view.getPaddingTop() + h * (1f - scaleY) + dp(topMarginDp) * (1f - scaleY)), (int) (view.getPaddingLeft() + px + (w - px) * scaleX), (int) (view.getPaddingTop() + h + dp(topMarginDp) * (1f - scaleY)) ); } else { rect.set( (int) (view.getPaddingLeft() + (px - px * scaleX)), view.getPaddingTop(), (int) (view.getPaddingLeft() + px + (w - px) * scaleX), (int) (view.getPaddingTop() + h * scaleY) ); } outline.setRoundRect(rect, dp(12)); } }); contentView.setClipToOutline(true); if (needBackgroundShadow) { contentView.setElevation(2f); } } if (type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP || type == TYPE_SET_DEFAULT_REACTION || type == TYPE_SET_REPLY_ICON) { contentView.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8)); } contentView.addView(backgroundView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); addView(contentView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.FILL, 0, type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_SET_DEFAULT_REACTION || type == TYPE_SET_REPLY_ICON_BOTTOM ? 6 + topMarginDp : 0, 0, isBottom() ? 6 + topMarginDp : 0)); if (bubbleX != null) { bubble2View = new View(context) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setPivotX(getMeasuredWidth() / 2); setPivotY(getMeasuredHeight()); } }; Drawable bubble2Drawable = getResources().getDrawable(R.drawable.shadowed_bubble2_half); bubble2Drawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground, resourcesProvider), PorterDuff.Mode.MULTIPLY)); bubble2View.setBackground(bubble2Drawable); addView(bubble2View, LayoutHelper.createFrame(17, 9, (isBottom() ? Gravity.BOTTOM : Gravity.TOP) | Gravity.LEFT, bubbleX / AndroidUtilities.density + (bubbleRight ? -25 : 10), isBottom() ? 0 : 5 + topMarginDp, 0, isBottom() ? 5 + topMarginDp + 9 : 0)); } boolean showSettings = baseFragment != null && type != TYPE_TOPIC_ICON && type != TYPE_CHAT_REACTIONS && type != TYPE_SET_REPLY_ICON && type != TYPE_SET_REPLY_ICON_BOTTOM && type != TYPE_AVATAR_CONSTRUCTOR && type != TYPE_EMOJI_STATUS_CHANNEL && type != TYPE_EMOJI_STATUS_CHANNEL_TOP && shouldDrawBackground; for (int i = 0; i < 2; i++) { EmojiTabsStrip emojiTabs = new EmojiTabsStrip(context, resourcesProvider, true, false, true, type, showSettings ? () -> { search(null, false, false); onSettings(); baseFragment.presentFragment(new StickersActivity(MediaDataController.TYPE_EMOJIPACKS, frozenEmojiPacks)); if (dismiss != null) { dismiss.run(); } } : null, accentColor) { @Override protected ColorFilter getEmojiColorFilter() { return premiumStarColorFilter; } @Override protected boolean onTabClick(int index) { if (smoothScrolling) { return false; } if (type == TYPE_AVATAR_CONSTRUCTOR) { if (index == 0) { showStickers = !showStickers; SelectAnimatedEmojiDialog.this.emojiTabs.setVisibility(View.GONE); SelectAnimatedEmojiDialog.this.emojiTabs = cachedEmojiTabs[showStickers ? 1 : 0]; SelectAnimatedEmojiDialog.this.emojiTabs.setVisibility(View.VISIBLE); SelectAnimatedEmojiDialog.this.emojiTabs.toggleEmojiStickersTab.setDrawable(ContextCompat.getDrawable(getContext(), showStickers ? R.drawable.msg_emoji_stickers : R.drawable.msg_emoji_smiles)); updateRows(true, false, false); layoutManager.scrollToPositionWithOffset(0, 0); return true; } index--; } int position = 0; if (index > 0 && sectionToPosition.indexOfKey(index - 1) >= 0) { position = sectionToPosition.get(index - 1); } scrollToPosition(position, AndroidUtilities.dp(-2)); SelectAnimatedEmojiDialog.this.emojiTabs.select(index); emojiGridView.scrolledByUserOnce = true; search(null); if (searchBox != null && searchBox.categoriesListView != null) { searchBox.categoriesListView.selectCategory(null); } return true; } @Override protected void onTabCreate(EmojiTabsStrip.EmojiTabButton button) { if (showAnimator == null || showAnimator.isRunning()) { button.setScaleX(0); button.setScaleY(0); } } }; emojiTabs.recentTab.setOnLongClickListener(e -> { onRecentLongClick(); try { performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); } catch (Exception ignore) { } return true; }); emojiTabs.updateButtonDrawables = false; if (type == TYPE_AVATAR_CONSTRUCTOR) { emojiTabs.setAnimatedEmojiCacheType(AnimatedEmojiDrawable.CACHE_TYPE_ALERT_PREVIEW_STATIC); } else { emojiTabs.setAnimatedEmojiCacheType(type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_SET_DEFAULT_REACTION ? AnimatedEmojiDrawable.CACHE_TYPE_TAB_STRIP : AnimatedEmojiDrawable.CACHE_TYPE_ALERT_PREVIEW_TAB_STRIP); } emojiTabs.animateAppear = bubbleX == null; emojiTabs.setPaddingLeft(type == TYPE_CHAT_REACTIONS ? 10 : 5); if (type != TYPE_EXPANDABLE_REACTIONS && type != TYPE_STICKER_SET_EMOJI) { contentView.addView(emojiTabs, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36)); } cachedEmojiTabs[i] = emojiTabs; } emojiTabs = cachedEmojiTabs[0]; cachedEmojiTabs[1].setVisibility(View.GONE); emojiTabsShadow = new View(context) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (bubbleX != null) { setPivotX(bubbleX); } } }; emojiTabsShadow.setBackgroundColor(Theme.getColor(Theme.key_divider, resourcesProvider)); if (type != TYPE_EXPANDABLE_REACTIONS && type != TYPE_STICKER_SET_EMOJI) { contentView.addView(emojiTabsShadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 1f / AndroidUtilities.density, Gravity.TOP, 0, 36, 0, 0)); } AndroidUtilities.updateViewVisibilityAnimated(emojiTabsShadow, true, 1f, false); emojiGridView = new EmojiListView(context) { @Override public void onScrolled(int dx, int dy) { super.onScrolled(dx, dy); checkScroll(); if (!smoothScrolling) { updateTabsPosition(layoutManager.findFirstCompletelyVisibleItemPosition()); } updateSearchBox(); AndroidUtilities.updateViewVisibilityAnimated(emojiTabsShadow, emojiGridView.computeVerticalScrollOffset() != 0 || type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL_TOP || type == TYPE_REACTIONS || type == TYPE_TAGS || type == TYPE_CHAT_REACTIONS, 1f, true); invalidateParent(); } @Override public void onScrollStateChanged(int state) { if (state == RecyclerView.SCROLL_STATE_IDLE) { smoothScrolling = false; if (searchRow != -1 && searchBox.getVisibility() == View.VISIBLE && searchBox.getTranslationY() > -AndroidUtilities.dp(51)) { SelectAnimatedEmojiDialog.this.scrollToPosition(searchBox.getTranslationY() > -AndroidUtilities.dp(16) ? 0 : 1, 0); } } super.onScrollStateChanged(state); } }; emojiItemAnimator = new DefaultItemAnimator() { @Override protected float animateByScale(View view) { return (view instanceof EmojiPackExpand ? .6f : 0f); } }; emojiItemAnimator.setAddDuration(220); emojiItemAnimator.setMoveDuration(260); emojiItemAnimator.setChangeDuration(160); emojiItemAnimator.setSupportsChangeAnimations(false); emojiItemAnimator.setMoveInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); emojiItemAnimator.setDelayAnimations(false); emojiGridView.setItemAnimator(emojiItemAnimator); emojiGridView.setPadding(dp(5), dp(type == TYPE_CHAT_REACTIONS ? 8 : 2), dp(5), dp(2 + 36)); adapter = new Adapter(); emojiGridView.setAdapter(adapter); emojiGridView.setLayoutManager(layoutManager = new GridLayoutManager(context, SPAN_COUNT) { @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { try { LinearSmoothScrollerCustom linearSmoothScroller = new LinearSmoothScrollerCustom(recyclerView.getContext(), LinearSmoothScrollerCustom.POSITION_TOP) { @Override public void onEnd() { smoothScrolling = false; } }; linearSmoothScroller.setTargetPosition(position); startSmoothScroll(linearSmoothScroller); } catch (Exception e) { FileLog.e(e); } } }); layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { if (positionToSection.indexOfKey(position) >= 0 || positionToButton.indexOfKey(position) >= 0 || position == recentReactionsSectionRow || position == popularSectionRow || position == longtapHintRow || position == searchRow || position == topicEmojiHeaderRow) { return layoutManager.getSpanCount(); } else { return showStickers ? 8 : 5; } } }); gridViewContainer = new FrameLayout(context) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) + AndroidUtilities.dp(36), MeasureSpec.EXACTLY)); } }; emojiGridViewContainer = new FrameLayout(context) { private final Rect rect = new Rect(); /** * The child does not redraw and uses hardware acceleration during animation. * We simply display the pieces we need from a large image for cascade animation. */ @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { if (child == emojiGridView && HwEmojis.isHwEnabled() && HwEmojis.isCascade()) { for (int i = 0; i < emojiGridView.getChildCount(); i++) { View view = emojiGridView.getChildAt(i); if (view instanceof ImageViewEmoji) { ImageViewEmoji viewEmoji = (ImageViewEmoji) view; if (viewEmoji.getAnimatedScale() == 1f) { rect.set(view.getLeft(), view.getTop(), view.getRight(), view.getBottom()); canvas.save(); canvas.clipRect(rect); super.drawChild(canvas, child, drawingTime); canvas.restore(); } else if (viewEmoji.getAnimatedScale() > 0f) { rect.set(view.getLeft(), view.getTop(), view.getRight(), view.getBottom()); rect.set( (int) (rect.centerX() - rect.width() / 2f * viewEmoji.getAnimatedScale()), (int) (rect.centerY() - rect.height() / 2f * viewEmoji.getAnimatedScale()), (int) (rect.centerX() + rect.width() / 2f * viewEmoji.getAnimatedScale()), (int) (rect.centerY() + rect.height() / 2f * viewEmoji.getAnimatedScale()) ); canvas.save(); canvas.clipRect(rect); canvas.scale(viewEmoji.getAnimatedScale(), viewEmoji.getAnimatedScale(), rect.centerX(), rect.centerY()); super.drawChild(canvas, child, drawingTime); canvas.restore(); } } else if (view instanceof TextView || view instanceof EmojiPackExpand || view instanceof EmojiPackButton || view instanceof HeaderView) { rect.set(view.getLeft(), view.getTop(), view.getRight(), view.getBottom()); canvas.save(); canvas.clipRect(rect); super.drawChild(canvas, child, drawingTime); canvas.restore(); } } return false; } return super.drawChild(canvas, child, drawingTime); } }; emojiGridViewContainer.addView(emojiGridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.FILL, 0, 0, 0, 0)); gridViewContainer.addView(emojiGridViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.FILL, 0, 0, 0, 0)); emojiSearchGridView = new EmojiListView(context) { @Override public void onScrolled(int dx, int dy) { super.onScrolled(dx, dy); checkScroll(); } }; if (emojiSearchGridView.getItemAnimator() != null) { emojiSearchGridView.getItemAnimator().setDurations(180); emojiSearchGridView.getItemAnimator().setMoveInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); } TextView emptyViewText = new TextView(context); if (type == TYPE_AVATAR_CONSTRUCTOR) { emptyViewText.setText(LocaleController.getString("NoEmojiOrStickersFound", R.string.NoEmojiOrStickersFound)); } else if (type == TYPE_EMOJI_STATUS || type == TYPE_STICKER_SET_EMOJI || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_TAGS || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP) { emptyViewText.setText(LocaleController.getString("NoEmojiFound", R.string.NoEmojiFound)); } else if (type == TYPE_REACTIONS || type == TYPE_SET_DEFAULT_REACTION) { emptyViewText.setText(LocaleController.getString("NoReactionsFound", R.string.NoReactionsFound)); } else { emptyViewText.setText(LocaleController.getString("NoIconsFound", R.string.NoIconsFound)); } emptyViewText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); emptyViewText.setTextColor(Theme.getColor(Theme.key_chat_emojiPanelEmptyText, resourcesProvider)); emojiSearchEmptyViewImageView = new BackupImageView(context); emojiSearchEmptyView = new FrameLayout(context); emojiSearchEmptyView.addView(emojiSearchEmptyViewImageView, LayoutHelper.createFrame(36, 36, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16, 0, 0)); emojiSearchEmptyView.addView(emptyViewText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16 + 36 + 8, 0, 0)); emojiSearchEmptyView.setVisibility(View.GONE); emojiSearchEmptyView.setAlpha(0); gridViewContainer.addView(emojiSearchEmptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 0, 0, 0, 0)); emojiSearchGridView.setPadding(dp(5), dp(52 + 2), dp(5), dp(36 + 2)); emojiSearchGridView.setAdapter(searchAdapter = new SearchAdapter()); emojiSearchGridView.setLayoutManager(searchLayoutManager = new GridLayoutManager(context, SPAN_COUNT) { @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { try { LinearSmoothScrollerCustom linearSmoothScroller = new LinearSmoothScrollerCustom(recyclerView.getContext(), LinearSmoothScrollerCustom.POSITION_TOP) { @Override public void onEnd() { smoothScrolling = false; } }; linearSmoothScroller.setTargetPosition(position); startSmoothScroll(linearSmoothScroller); } catch (Exception e) { FileLog.e(e); } } }); searchLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { int viewType = searchAdapter.getItemViewType(position); if (viewType == SearchAdapter.VIEW_TYPE_HEADER) { return layoutManager.getSpanCount(); } if (viewType == SearchAdapter.VIEW_TYPE_STICKER) { return 8; } return 5; } }); emojiSearchGridView.setVisibility(View.GONE); gridViewContainer.addView(emojiSearchGridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.FILL, 0, 0, 0, 0)); contentView.addView(gridViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP, 0, type == TYPE_EXPANDABLE_REACTIONS || type == TYPE_STICKER_SET_EMOJI ? 0 : 36 + (1 / AndroidUtilities.density), 0, 0)); scrollHelper = new RecyclerAnimationScrollHelper(emojiGridView, layoutManager); scrollHelper.setAnimationCallback(new RecyclerAnimationScrollHelper.AnimationCallback() { @Override public void onPreAnimation() { smoothScrolling = true; } @Override public void onEndAnimation() { smoothScrolling = false; } }); scrollHelper.setScrollListener(() -> { invalidateParent(); }); RecyclerListView.OnItemLongClickListenerExtended onItemLongClick = new RecyclerListView.OnItemLongClickListenerExtended() { @Override public boolean onItemClick(View view, int position, float x, float y) { if (type == TYPE_TAGS || type == TYPE_STICKER_SET_EMOJI) return false; if (view instanceof ImageViewEmoji && (type == TYPE_REACTIONS || type == TYPE_EXPANDABLE_REACTIONS)) { incrementHintUse(); performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); ImageViewEmoji imageViewEmoji = (ImageViewEmoji) view; if (!imageViewEmoji.isDefaultReaction && !UserConfig.getInstance(currentAccount).isPremium()) { TLRPC.Document document = imageViewEmoji.span.document; if (document == null) { document = AnimatedEmojiDrawable.findDocument(currentAccount, imageViewEmoji.span.documentId); } onEmojiSelected(imageViewEmoji, imageViewEmoji.span.documentId, document, null); return true; } selectedReactionView = imageViewEmoji; pressedProgress = 0f; cancelPressed = false; if (selectedReactionView.isDefaultReaction) { setBigReactionAnimatedEmoji(null); TLRPC.TL_availableReaction reaction = MediaDataController.getInstance(currentAccount).getReactionsMap().get(selectedReactionView.reaction.emojicon); if (reaction != null) { bigReactionImageReceiver.setImage(ImageLocation.getForDocument(reaction.select_animation), ReactionsUtils.SELECT_ANIMATION_FILTER, null, null, null, 0, "tgs", selectedReactionView.reaction, 0); } } else { setBigReactionAnimatedEmoji(new AnimatedEmojiDrawable(AnimatedEmojiDrawable.CACHE_TYPE_ALERT_PREVIEW_LARGE, currentAccount, selectedReactionView.span.documentId)); } emojiGridView.invalidate(); invalidateParent(); return true; } if (view instanceof ImageViewEmoji && ((ImageViewEmoji) view).span != null && (type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP)) { SelectStatusDurationDialog dialog = selectStatusDateDialog = new SelectStatusDurationDialog(context, dismiss, SelectAnimatedEmojiDialog.this, (ImageViewEmoji) view, resourcesProvider) { @Override protected boolean getOutBounds(Rect rect) { if (scrimDrawable != null && emojiX != null) { rect.set(drawableToBounds); return true; } return false; } @Override protected void onEndPartly(Integer date) { incrementHintUse(); TLRPC.TL_emojiStatus status = new TLRPC.TL_emojiStatus(); status.document_id = ((ImageViewEmoji) view).span.documentId; onEmojiSelected(view, status.document_id, ((ImageViewEmoji) view).span.document, date); MediaDataController.getInstance(currentAccount).pushRecentEmojiStatus(status); } @Override protected void onEnd(Integer date) { if (date != null) { if (SelectAnimatedEmojiDialog.this.dismiss != null) { SelectAnimatedEmojiDialog.this.dismiss.run(); } } } @Override public void dismiss() { super.dismiss(); selectStatusDateDialog = null; } }; dialog.show(); try { view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); } catch (Exception ignore) {} return true; } return false; } @Override public void onLongClickRelease() { if (selectedReactionView != null) { cancelPressed = true; ValueAnimator cancelProgressAnimator = ValueAnimator.ofFloat(pressedProgress, 0); cancelProgressAnimator.addUpdateListener(animation -> pressedProgress = (float) animation.getAnimatedValue()); cancelProgressAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { selectedReactionView.bigReactionSelectedProgress = 0f; selectedReactionView = null; emojiGridView.invalidate(); } }); cancelProgressAnimator.setDuration(150); cancelProgressAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); cancelProgressAnimator.start(); } } }; emojiGridView.setOnItemLongClickListener(onItemLongClick, (long) (ViewConfiguration.getLongPressTimeout() * 0.25f)); emojiSearchGridView.setOnItemLongClickListener(onItemLongClick, (long) (ViewConfiguration.getLongPressTimeout() * 0.25f)); RecyclerListView.OnItemClickListener onItemClick = (view, position) -> { if (view instanceof ImageViewEmoji) { ImageViewEmoji viewEmoji = (ImageViewEmoji) view; if (viewEmoji.isDefaultReaction || type == TYPE_STICKER_SET_EMOJI) { incrementHintUse(); onReactionClick(viewEmoji, viewEmoji.reaction); } else if (viewEmoji.isStaticIcon && viewEmoji.document != null) { onStickerClick(viewEmoji, viewEmoji.document); } else { onEmojiClick(viewEmoji, viewEmoji.span); } if (type != TYPE_REACTIONS && type != TYPE_TAGS) { try { performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); } catch (Exception ignore) {} } } else if (view instanceof ImageView) { onEmojiClick(view, null); if (type != TYPE_REACTIONS && type != TYPE_TAGS) { try { performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); } catch (Exception ignore) {} } } else if (view instanceof EmojiPackExpand) { EmojiPackExpand button = (EmojiPackExpand) view; expand(position, button); if (type != TYPE_REACTIONS && type != TYPE_TAGS) { try { performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); } catch (Exception ignore) {} } } else if (view != null) { view.callOnClick(); } }; emojiGridView.setOnItemClickListener(onItemClick); emojiSearchGridView.setOnItemClickListener(onItemClick); searchBox = new SearchBox(context, shouldDrawBackground) { @Override protected void dispatchDraw(Canvas canvas) { if (backgroundDelegate != null) { backgroundDelegate.drawRect(canvas, 0, 0, getMeasuredWidth(), getMeasuredHeight(), searchBox.getX() + gridViewContainer.getX(), searchBox.getY() + gridViewContainer.getY()); } super.dispatchDraw(canvas); } @Override public void setTranslationY(float translationY) { if (translationY != getTranslationY()) { super.setTranslationY(translationY); if (backgroundDelegate != null) { invalidate(); } } } }; searchBox.setTranslationY(-AndroidUtilities.dp(52)); searchBox.setVisibility(View.INVISIBLE); gridViewContainer.addView(searchBox, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 52, Gravity.TOP, 0, -4, 0, 0)); topGradientView = new View(context) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (bubbleX != null) { setPivotX(bubbleX); } } }; Drawable topGradient = getResources().getDrawable(R.drawable.gradient_top); topGradient.setColorFilter(new PorterDuffColorFilter(AndroidUtilities.multiplyAlphaComponent(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground, resourcesProvider), .8f), PorterDuff.Mode.SRC_IN)); topGradientView.setBackground(topGradient); topGradientView.setAlpha(0); contentView.addView(topGradientView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 20, Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 36 + 1f / AndroidUtilities.density, 0, 0)); bottomGradientView = new View(context); Drawable bottomGradient = getResources().getDrawable(R.drawable.gradient_bottom); bottomGradient.setColorFilter(new PorterDuffColorFilter(AndroidUtilities.multiplyAlphaComponent(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground, resourcesProvider), .8f), PorterDuff.Mode.SRC_IN)); // bottomGradientView.setBackground(bottomGradient); bottomGradientView.setAlpha(0); contentView.addView(bottomGradientView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 20, Gravity.BOTTOM | Gravity.FILL_HORIZONTAL)); contentViewForeground = new View(context); contentViewForeground.setAlpha(0); contentViewForeground.setBackgroundColor(0xff000000); contentView.addView(contentViewForeground, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); preload(type, currentAccount); bigReactionImageReceiver.setLayerNum(7); if (isAnimatedShow()) { HwEmojis.beforePreparing(); } updateRows(true, false); } private void onStickerClick(ImageViewEmoji viewEmoji, TLRPC.Document document) { if (type == TYPE_CHAT_REACTIONS) { onEmojiSelected(viewEmoji, document.id, document, null); } else { onEmojiSelected(viewEmoji, null, document, null); } } protected void onSettings() { } public void setExpireDateHint(int date) { if (date <= 0) return; includeHint = true; hintExpireDate = date; updateRows(true, false); } private void setBigReactionAnimatedEmoji(AnimatedEmojiDrawable animatedEmojiDrawable) { if (!isAttached) { return; } if (bigReactionAnimatedEmoji == animatedEmojiDrawable) { return; } if (bigReactionAnimatedEmoji != null) { bigReactionAnimatedEmoji.removeView(this); } this.bigReactionAnimatedEmoji = animatedEmojiDrawable; if (bigReactionAnimatedEmoji != null) { bigReactionAnimatedEmoji.setColorFilter(premiumStarColorFilter); bigReactionAnimatedEmoji.addView(this); } } private void onRecentLongClick() { AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), null); builder.setTitle(LocaleController.getString("ClearRecentEmojiStatusesTitle", R.string.ClearRecentEmojiStatusesTitle)); builder.setMessage(LocaleController.getString("ClearRecentEmojiStatusesText", R.string.ClearRecentEmojiStatusesText)); builder.setPositiveButton(LocaleController.getString("Clear", R.string.Clear), (dialogInterface, i) -> { ConnectionsManager.getInstance(currentAccount).sendRequest(new TLRPC.TL_account_clearRecentEmojiStatuses(), null); MediaDataController.getInstance(currentAccount).clearRecentEmojiStatuses(); updateRows(false, true); }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setDimEnabled(false); builder.setOnDismissListener(di -> { setDim(0, true); }); builder.show(); setDim(1f, true); } private ValueAnimator dimAnimator; private final float maxDim = .25f; private void setDim(float dim, boolean animated) { if (dimAnimator != null) { dimAnimator.cancel(); dimAnimator = null; } if (animated) { dimAnimator = ValueAnimator.ofFloat(contentViewForeground.getAlpha(), dim * maxDim); dimAnimator.addUpdateListener(anm -> { if (contentViewForeground != null) { contentViewForeground.setAlpha((float) anm.getAnimatedValue()); } final int bubbleColor = Theme.blendOver(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground, resourcesProvider), ColorUtils.setAlphaComponent(0xff000000, (int) (255 * (float) anm.getAnimatedValue()))); if (bubble1View != null) { bubble1View.getBackground().setColorFilter(new PorterDuffColorFilter(bubbleColor, PorterDuff.Mode.MULTIPLY)); } if (bubble2View != null) { bubble2View.getBackground().setColorFilter(new PorterDuffColorFilter(bubbleColor, PorterDuff.Mode.MULTIPLY)); } }); dimAnimator.setDuration(200); dimAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); dimAnimator.start(); } else { contentViewForeground.setAlpha(dim * maxDim); final int bubbleColor = Theme.blendOver(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground, resourcesProvider), ColorUtils.setAlphaComponent(0xff000000, (int) (255 * dim * maxDim))); if (bubble1View != null) { bubble1View.getBackground().setColorFilter(new PorterDuffColorFilter(bubbleColor, PorterDuff.Mode.MULTIPLY)); } if (bubble2View != null) { bubble2View.getBackground().setColorFilter(new PorterDuffColorFilter(bubbleColor, PorterDuff.Mode.MULTIPLY)); } } } private void updateTabsPosition(int position) { if (position != RecyclerView.NO_POSITION) { final int recentmaxlen = SPAN_COUNT_FOR_EMOJI * RECENT_MAX_LINES; int recentSize = recent.size() > recentmaxlen && !recentExpanded ? recentmaxlen : recent.size() + (includeEmpty ? 1 : 0); if (position <= recentSize || position <= recentReactions.size()) { emojiTabs.select(0); // recent } else { final int maxlen = SPAN_COUNT_FOR_EMOJI * EXPAND_MAX_LINES; for (int i = 0; i < positionToSection.size(); ++i) { int startPosition = positionToSection.keyAt(i); int index = i - (defaultStatuses.isEmpty() ? 0 : 1); EmojiView.EmojiPack pack = index >= 0 ? packs.get(index) : null; if (pack == null) { continue; } int count = pack.expanded ? pack.documents.size() : Math.min(maxlen, pack.documents.size()); if (position > startPosition && position <= startPosition + 1 + count) { emojiTabs.select(1 + i); return; } } } } } private void updateSearchBox() { if (searchBox == null) { return; } if (searched) { searchBox.clearAnimation(); searchBox.setVisibility(View.VISIBLE); searchBox.animate().translationY(0).start(); } else { if (emojiGridView.getChildCount() > 0) { View first = emojiGridView.getChildAt(0); if (emojiGridView.getChildAdapterPosition(first) == searchRow && "searchbox".equals(first.getTag())) { searchBox.setVisibility(View.VISIBLE); searchBox.setTranslationY(first.getY()); } else { searchBox.setTranslationY(-AndroidUtilities.dp(52)); } } else { searchBox.setTranslationY(-AndroidUtilities.dp(52)); } } } private Drawable premiumStar; private ColorFilter premiumStarColorFilter; private Drawable getPremiumStar() { if (premiumStar == null) { if (type == TYPE_SET_REPLY_ICON || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP || type == TYPE_SET_REPLY_ICON_BOTTOM) { premiumStar = ApplicationLoader.applicationContext.getResources().getDrawable(R.drawable.msg_filled_blocked).mutate(); } else { premiumStar = ApplicationLoader.applicationContext.getResources().getDrawable(R.drawable.msg_settings_premium).mutate(); } premiumStar.setColorFilter(premiumStarColorFilter); } return premiumStar; } private float scrimAlpha = 1f; private int scrimColor; private AnimatedEmojiDrawable.SwapAnimatedEmojiDrawable scrimDrawable; private Rect drawableToBounds; private View scrimDrawableParent; private float emojiSelectAlpha = 1f; private ImageViewEmoji emojiSelectView; private Rect emojiSelectRect; private OvershootInterpolator overshootInterpolator = new OvershootInterpolator(2f); protected float getScrimDrawableTranslationY() { return 0; } @Override protected void dispatchDraw(Canvas canvas) { if (scrimDrawable != null && emojiX != null) { Rect bounds = scrimDrawable.getBounds(); float scale = scrimDrawableParent == null ? 1f : scrimDrawableParent.getScaleY(); int wasAlpha = 255; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { wasAlpha = scrimDrawable.getAlpha(); } int h = (scrimDrawableParent == null ? bounds.height() : scrimDrawableParent.getHeight()); canvas.save(); canvas.translate(0, -getTranslationY()); scrimDrawable.setAlpha((int) (wasAlpha * Math.pow(contentView.getAlpha(), .25f) * scrimAlpha)); if (drawableToBounds == null) { drawableToBounds = new Rect(); } final float xmagic = (scale > 1f && scale < 1.5f ? 2 : 0); final float ymagic = -(scale > 1.5f ? (bounds.height() * .81f + 1) : 0); final float cx = emojiX + xmagic; final float cy = bounds.centerY() * (scale - 1) + ymagic + (!isBottom() ? dp(topMarginDp) : getMeasuredHeight() - dp(topMarginDp) / 2f) + getScrimDrawableTranslationY(); final float sw = bounds.width() * scale / 2f; final float sh = bounds.height() * scale / 2f; drawableToBounds.set((int) (cx - sw), (int) (cy - sh), (int) (cx + sw), (int) (cy + sh)); scrimDrawable.setBounds( drawableToBounds.left, drawableToBounds.top, (int) (drawableToBounds.left + drawableToBounds.width() / scale), (int) (drawableToBounds.top + drawableToBounds.height() / scale) ); canvas.scale(scale, scale, drawableToBounds.left, drawableToBounds.top); scrimDrawable.draw(canvas); scrimDrawable.setAlpha(wasAlpha); scrimDrawable.setBounds(bounds); canvas.restore(); } super.dispatchDraw(canvas); if (emojiSelectView != null && emojiSelectRect != null && emojiSelectView.drawable != null) { canvas.save(); canvas.translate(0, -getTranslationY()); emojiSelectView.drawable.setAlpha((int) (255 * emojiSelectAlpha)); emojiSelectView.drawable.setBounds(emojiSelectRect); emojiSelectView.drawable.setColorFilter(new PorterDuffColorFilter(ColorUtils.blendARGB(accentColor, scrimColor, 1f - scrimAlpha), PorterDuff.Mode.SRC_IN)); emojiSelectView.drawable.draw(canvas); canvas.restore(); } } private ValueAnimator emojiSelectAnimator; public void animateEmojiSelect(ImageViewEmoji view, Runnable onDone) { if (emojiSelectAnimator != null || scrimDrawable == null) { onDone.run(); return; } view.notDraw = true; final Rect from = new Rect(); from.set( contentView.getLeft() + emojiGridView.getLeft() + view.getLeft(), contentView.getTop() + emojiGridView.getTop() + view.getTop(), contentView.getLeft() + emojiGridView.getLeft() + view.getRight(), contentView.getTop() + emojiGridView.getTop() + view.getBottom() ); final AnimatedEmojiDrawable statusDrawable; if (view.drawable instanceof AnimatedEmojiDrawable) { statusDrawable = AnimatedEmojiDrawable.make(currentAccount, AnimatedEmojiDrawable.CACHE_TYPE_EMOJI_STATUS, ((AnimatedEmojiDrawable) view.drawable).getDocumentId()); } else { statusDrawable = null; } emojiSelectView = view; emojiSelectRect = new Rect(); emojiSelectRect.set(from); boolean[] done = new boolean[1]; emojiSelectAnimator = ValueAnimator.ofFloat(0, 1); emojiSelectAnimator.addUpdateListener(anm -> { float t = (float) anm.getAnimatedValue(); scrimAlpha = 1f - t * t * t; emojiSelectAlpha = 1f - (float) Math.pow(t, 10); AndroidUtilities.lerp(from, drawableToBounds, t, emojiSelectRect); float scale = Math.max(1, overshootInterpolator.getInterpolation(MathUtils.clamp(3 * t - (3 - 1), 0, 1f))) * view.getScaleX(); emojiSelectRect.set( (int) (emojiSelectRect.centerX() - emojiSelectRect.width() / 2f * scale), (int) (emojiSelectRect.centerY() - emojiSelectRect.height() / 2f * scale), (int) (emojiSelectRect.centerX() + emojiSelectRect.width() / 2f * scale), (int) (emojiSelectRect.centerY() + emojiSelectRect.height() / 2f * scale) ); invalidate(); if (t > .85f && !done[0]) { done[0] = true; onDone.run(); if (statusDrawable != null && scrimDrawable != null) { scrimDrawable.play(); } } }); emojiSelectAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { emojiSelectView = null; invalidate(); if (!done[0]) { done[0] = true; onDone.run(); } } }); emojiSelectAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); emojiSelectAnimator.setDuration(260); emojiSelectAnimator.start(); } private boolean topGradientShown = false; private boolean bottomGradientShown = false; private void checkScroll() { final boolean bottom = (gridSearch ? emojiSearchGridView : emojiGridView).canScrollVertically(1); if (bottom != bottomGradientShown) { bottomGradientShown = bottom; bottomGradientView.animate().alpha(bottom ? 1f : 0f).setDuration(200).start(); } } private boolean smoothScrolling = false; private void scrollToPosition(int p, int offset) { View view = layoutManager.findViewByPosition(p); int firstPosition = layoutManager.findFirstVisibleItemPosition(); if ((view == null && Math.abs(p - firstPosition) > SPAN_COUNT_FOR_EMOJI * 9f) || !SharedConfig.animationsEnabled()) { scrollHelper.setScrollDirection(layoutManager.findFirstVisibleItemPosition() < p ? RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN : RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP); scrollHelper.scrollToPosition(p, offset, false, true); } else { LinearSmoothScrollerCustom linearSmoothScroller = new LinearSmoothScrollerCustom(emojiGridView.getContext(), LinearSmoothScrollerCustom.POSITION_TOP) { @Override public void onEnd() { smoothScrolling = false; } @Override protected void onStart() { smoothScrolling = true; } }; linearSmoothScroller.setTargetPosition(p); linearSmoothScroller.setOffset(offset); layoutManager.startSmoothScroll(linearSmoothScroller); } } public boolean searching = false; public boolean searched = false; public boolean searchedLiftUp = false; private String lastQuery; private ArrayList<ReactionsLayoutInBubble.VisibleReaction> searchResult; private ArrayList<TLRPC.Document> stickersSearchResult; private ArrayList<TLRPC.Document> searchSets; private ValueAnimator gridSwitchAnimator; public void switchGrids(boolean search) { switchGrids(search, true); } private boolean gridSearch = false; public void switchGrids(boolean search, boolean liftUp) { if (gridSearch == search) { return; } gridSearch = search; emojiGridView.setVisibility(View.VISIBLE); emojiSearchGridView.setVisibility(View.VISIBLE); if (gridSwitchAnimator != null) { gridSwitchAnimator.cancel(); } if (searchEmptyViewAnimator != null) { searchEmptyViewAnimator.cancel(); searchEmptyViewAnimator = null; } gridSwitchAnimator = ValueAnimator.ofFloat(0, 1); gridSwitchAnimator.addUpdateListener(anm -> { float t = (float) anm.getAnimatedValue(); if (!search) { t = 1f - t; } emojiGridView.setAlpha(1f - t); emojiGridView.setTranslationY(AndroidUtilities.dp(8) * t); emojiSearchGridView.setAlpha(t); emojiSearchGridView.setTranslationY(AndroidUtilities.dp(8) * (1f - t)); emojiSearchEmptyView.setAlpha(emojiSearchGridView.getAlpha() * t); }); gridSwitchAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { emojiSearchGridView.setVisibility(search ? View.VISIBLE : View.GONE); emojiGridView.setVisibility(search ? View.GONE : View.VISIBLE); gridSwitchAnimator = null; if (!search && searchResult != null) { searchResult.clear(); if (searchSets != null) { searchSets.clear(); } searchAdapter.updateRows(false); } } }); gridSwitchAnimator.setDuration(320); gridSwitchAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); gridSwitchAnimator.start(); ((View) emojiGridView.getParent()).animate() .translationY(gridSearch && liftUp ? -AndroidUtilities.dp(36) : 0) .setUpdateListener(anm -> invalidateParent()) .setInterpolator(CubicBezierInterpolator.DEFAULT) .setDuration(160) .start(); if (gridSearch && liftUp) { emojiSearchGridView.setPadding(dp(5), dp(54), dp(5), dp(36 + 2)); } else { emojiSearchGridView.setPadding(dp(5), dp(54), dp(5), dp(36 + 2)); } checkScroll(); } public static void updateSearchEmptyViewImage(int currentAccount, BackupImageView imageView) { if (imageView == null) { return; } TLRPC.Document emoji = null; ArrayList<TLRPC.StickerSetCovered> featuredSets = MediaDataController.getInstance(currentAccount).getFeaturedEmojiSets(); List<TLRPC.StickerSetCovered> shuffledFeaturedSets = new ArrayList<>(featuredSets); Collections.shuffle(shuffledFeaturedSets); int skip = (int) Math.round(Math.random() * 10); for (int i = 0; i < shuffledFeaturedSets.size(); ++i) { if (shuffledFeaturedSets.get(i) instanceof TLRPC.TL_stickerSetFullCovered && ((TLRPC.TL_stickerSetFullCovered) shuffledFeaturedSets.get(i)).documents != null) { List<TLRPC.Document> documents = new ArrayList<>(((TLRPC.TL_stickerSetFullCovered) shuffledFeaturedSets.get(i)).documents); Collections.shuffle(documents); for (int j = 0; j < documents.size(); ++j) { TLRPC.Document document = documents.get(j); if (document != null && emptyViewEmojis.contains(MessageObject.findAnimatedEmojiEmoticon(document, null))) { emoji = document; if (skip-- <= 0) break; } } } if (emoji != null && skip <= 0) { break; } } if (emoji == null || skip > 0) { ArrayList<TLRPC.TL_messages_stickerSet> sets = MediaDataController.getInstance(currentAccount).getStickerSets(MediaDataController.TYPE_EMOJIPACKS); List<TLRPC.TL_messages_stickerSet> shuffledSets = new ArrayList<>(sets); Collections.shuffle(shuffledSets); for (int i = 0; i < shuffledSets.size(); ++i) { if (shuffledSets.get(i) != null && shuffledSets.get(i).documents != null) { List<TLRPC.Document> documents = new ArrayList<>(shuffledSets.get(i).documents); Collections.shuffle(documents); for (int j = 0; j < documents.size(); ++j) { TLRPC.Document document = documents.get(j); if (document != null && emptyViewEmojis.contains(MessageObject.findAnimatedEmojiEmoticon(document, null))) { emoji = document; if (skip-- <= 0) break; } } } if (emoji != null && skip <= 0) { break; } } } if (emoji != null) { TLRPC.Document document = emoji; String filter = "36_36"; ImageLocation mediaLocation; String mediaFilter; SvgHelper.SvgDrawable thumbDrawable = DocumentObject.getSvgThumb(document.thumbs, Theme.key_windowBackgroundWhiteGrayIcon, 0.2f); TLRPC.PhotoSize thumb = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 90); if ("video/webm".equals(document.mime_type)) { mediaLocation = ImageLocation.getForDocument(document); mediaFilter = filter + "_" + ImageLoader.AUTOPLAY_FILTER; if (thumbDrawable != null) { thumbDrawable.overrideWidthAndHeight(512, 512); } } else { if (thumbDrawable != null && MessageObject.isAnimatedStickerDocument(document, false)) { thumbDrawable.overrideWidthAndHeight(512, 512); } mediaLocation = ImageLocation.getForDocument(document); mediaFilter = filter; } imageView.setLayerNum(7); imageView.setRoundRadius(AndroidUtilities.dp(4)); imageView.setImage(mediaLocation, mediaFilter, ImageLocation.getForDocument(thumb, document), "36_36", thumbDrawable, document); } } private static final List<String> emptyViewEmojis = Arrays.asList("😖", "😫", "🫠", "😨", "❓"); private boolean searchEmptyViewVisible = false; private ValueAnimator searchEmptyViewAnimator; public void switchSearchEmptyView(boolean empty) { if (searchEmptyViewVisible == empty) { return; } searchEmptyViewVisible = empty; if (searchEmptyViewAnimator != null) { searchEmptyViewAnimator.cancel(); } searchEmptyViewAnimator = ValueAnimator.ofFloat(0, 1); searchEmptyViewAnimator.addUpdateListener(anm -> { float t = (float) anm.getAnimatedValue(); if (!empty) { t = 1f - t; } emojiSearchEmptyView.setAlpha(emojiSearchGridView.getAlpha() * t); }); searchEmptyViewAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { emojiSearchEmptyView.setVisibility(empty && emojiSearchGridView.getVisibility() == View.VISIBLE ? View.VISIBLE : View.GONE); searchEmptyViewAnimator = null; } }); searchEmptyViewAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); searchEmptyViewAnimator.setDuration(100); searchEmptyViewAnimator.start(); if (empty) { updateSearchEmptyViewImage(currentAccount, emojiSearchEmptyViewImageView); } } private static String[] lastSearchKeyboardLanguage; private Runnable clearSearchRunnable; private Runnable searchRunnable; public void search(String query) { search(query, true, true); } public void search(String query, boolean liftUp, boolean delay) { if (clearSearchRunnable != null) { AndroidUtilities.cancelRunOnUIThread(clearSearchRunnable); clearSearchRunnable = null; } if (searchRunnable != null) { AndroidUtilities.cancelRunOnUIThread(searchRunnable); searchRunnable = null; } if (TextUtils.isEmpty(query)) { searching = false; searched = false; switchGrids(false, liftUp); if (searchBox != null) { searchBox.showProgress(false); searchBox.toggleClear(false); } searchAdapter.updateRows(true); lastQuery = null; } else { boolean firstSearch = !searching; searching = true; searched = false; searchedLiftUp = liftUp; if (searchBox != null) { searchBox.showProgress(true); } if (firstSearch) { if (searchResult != null) { searchResult.clear(); } if (searchSets != null) { searchSets.clear(); } searchAdapter.updateRows(false); } else if (!query.equals(lastQuery)) { AndroidUtilities.runOnUIThread(clearSearchRunnable = () -> { if (searchResult != null) { searchResult.clear(); } if (searchSets != null) { searchSets.clear(); } searchAdapter.updateRows(true); }, 120); } lastQuery = query; String[] newLanguage = AndroidUtilities.getCurrentKeyboardLanguage(); if (!Arrays.equals(newLanguage, lastSearchKeyboardLanguage)) { MediaDataController.getInstance(currentAccount).fetchNewEmojiKeywords(newLanguage); } lastSearchKeyboardLanguage = newLanguage; AndroidUtilities.runOnUIThread(searchRunnable = () -> { final LinkedHashSet<Long> documentIds = new LinkedHashSet<>(); final LinkedHashSet<String> emojis = new LinkedHashSet<>(); final HashMap<String, TLRPC.TL_availableReaction> availableReactions = MediaDataController.getInstance(currentAccount).getReactionsMap(); final ArrayList<ReactionsLayoutInBubble.VisibleReaction> reactions = new ArrayList<>(); final boolean queryFullyConsistsOfEmojis = Emoji.fullyConsistsOfEmojis(query); final ArrayList<ArrayList<TLRPC.Document>> emojiArrays = new ArrayList<>(); final HashMap<ArrayList<TLRPC.Document>, String> emojiStickers = new HashMap<>(); final ArrayList<TLRPC.Document> sets = new ArrayList<>(); final Utilities.Callback<Runnable> applySearch = next -> AndroidUtilities.runOnUIThread(() -> { if (clearSearchRunnable != null) { AndroidUtilities.cancelRunOnUIThread(clearSearchRunnable); clearSearchRunnable = null; } if (query != lastQuery) { return; } searched = true; switchGrids(true, liftUp); if (searchBox != null) { searchBox.showProgress(false); } if (searchResult == null) { searchResult = new ArrayList<>(); } else { searchResult.clear(); } if (searchSets == null) { searchSets = new ArrayList<>(); } else { searchSets.clear(); } if (stickersSearchResult == null) { stickersSearchResult = new ArrayList<>(); } else { stickersSearchResult.clear(); } emojiSearchGridView.scrollToPosition(0); if (type == TYPE_REACTIONS || type == TYPE_TAGS || type == TYPE_SET_DEFAULT_REACTION) { if (!reactions.isEmpty()) { searchResult.addAll(reactions); } else { TLRPC.TL_availableReaction reaction = availableReactions.get(query); if (reaction != null) { searchResult.add(ReactionsLayoutInBubble.VisibleReaction.fromEmojicon(reaction)); } } } for (long documentId : documentIds) { searchResult.add(ReactionsLayoutInBubble.VisibleReaction.fromCustomEmoji(documentId)); } for (String emoji : emojis) { searchResult.add(ReactionsLayoutInBubble.VisibleReaction.fromEmojicon(emoji)); } searchSets.addAll(sets); for (ArrayList<TLRPC.Document> array : emojiArrays) { stickersSearchResult.addAll(array); } searchAdapter.updateRows(!firstSearch); }); if (type == TYPE_STICKER_SET_EMOJI) { final Utilities.Callback<Runnable> search = next -> { MediaDataController.getInstance(currentAccount).getEmojiSuggestions( lastSearchKeyboardLanguage, query, false, (result, alias) -> { try { for (int i = 0; i < result.size(); ++i) { if (result.get(i).emoji.startsWith("animated_")) { continue; } String emoji = Emoji.fixEmoji(result.get(i).emoji); if (Emoji.getEmojiDrawable(emoji) == null) { continue; } emojis.add(emoji); } } catch (Exception ignore) {} next.run(); }, null, false, false, false, 0 ); }; Utilities.doCallbacks(search, applySearch); } else { final Utilities.Callback<Runnable> searchCategories = next -> { if (queryFullyConsistsOfEmojis) { StickerCategoriesListView.search.fetch(UserConfig.selectedAccount, query, list -> { if (list != null) { documentIds.addAll(list.document_id); } next.run(); }); } else { next.run(); } }; final Utilities.Callback<Runnable> searchByKeywords = next -> { MediaDataController.getInstance(currentAccount).getAnimatedEmojiByKeywords(query, _documentIds -> { if (_documentIds != null) { documentIds.addAll(_documentIds); } next.run(); }); }; final Utilities.Callback<Runnable> searchEmojiSuggestions = next -> { if (queryFullyConsistsOfEmojis) { ArrayList<TLRPC.TL_messages_stickerSet> stickerSets = MediaDataController.getInstance(currentAccount).getStickerSets(MediaDataController.TYPE_EMOJIPACKS); String emoticon; for (int i = 0; i < stickerSets.size(); ++i) { if (stickerSets.get(i).documents == null) { continue; } ArrayList<TLRPC.Document> documents = stickerSets.get(i).documents; if (documents == null) { continue; } for (int j = 0; j < documents.size(); ++j) { emoticon = MessageObject.findAnimatedEmojiEmoticon(documents.get(j), null); long id = documents.get(j).id; if (emoticon != null && !documentIds.contains(id) && query.contains(emoticon.toLowerCase())) { documentIds.add(id); } } } ArrayList<TLRPC.StickerSetCovered> featuredStickerSets = MediaDataController.getInstance(currentAccount).getFeaturedEmojiSets(); for (int i = 0; i < featuredStickerSets.size(); ++i) { if (featuredStickerSets.get(i) instanceof TLRPC.TL_stickerSetFullCovered && ((TLRPC.TL_stickerSetFullCovered) featuredStickerSets.get(i)).keywords != null) { ArrayList<TLRPC.Document> documents = ((TLRPC.TL_stickerSetFullCovered) featuredStickerSets.get(i)).documents; if (documents == null) { continue; } for (int j = 0; j < documents.size(); ++j) { emoticon = MessageObject.findAnimatedEmojiEmoticon(documents.get(j), null); final long id = documents.get(j).id; if (emoticon != null && !documentIds.contains(id) && query.contains(emoticon)) { documentIds.add(id); } } } } next.run(); } else { MediaDataController.getInstance(currentAccount).getEmojiSuggestions( lastSearchKeyboardLanguage, query, false, (result, alias) -> { try { for (int i = 0; i < result.size(); ++i) { if (result.get(i).emoji.startsWith("animated_")) { documentIds.add(Long.parseLong(result.get(i).emoji.substring(9))); } else { if (type == TYPE_REACTIONS || type == TYPE_TAGS || type == TYPE_SET_DEFAULT_REACTION) { TLRPC.TL_availableReaction reaction = availableReactions.get(result.get(i).emoji); if (reaction != null) { reactions.add(ReactionsLayoutInBubble.VisibleReaction.fromEmojicon(reaction)); } } } } } catch (Exception ignore) { } next.run(); }, null, true, type == TYPE_TOPIC_ICON, false, 30 ); } }; final Utilities.Callback<Runnable> searchAvatarConstructor = next -> { if (type != TYPE_AVATAR_CONSTRUCTOR) { next.run(); return; } final ArrayList<TLRPC.Document> emojiStickersArray = new ArrayList<>(0); final LongSparseArray<TLRPC.Document> emojiStickersMap = new LongSparseArray<>(0); HashMap<String, ArrayList<TLRPC.Document>> allStickers = MediaDataController.getInstance(currentAccount).getAllStickers(); if (query.length() <= 14) { CharSequence emoji = query; int length = emoji.length(); for (int a = 0; a < length; a++) { if (a < length - 1 && (emoji.charAt(a) == 0xD83C && emoji.charAt(a + 1) >= 0xDFFB && emoji.charAt(a + 1) <= 0xDFFF || emoji.charAt(a) == 0x200D && (emoji.charAt(a + 1) == 0x2640 || emoji.charAt(a + 1) == 0x2642))) { emoji = TextUtils.concat(emoji.subSequence(0, a), emoji.subSequence(a + 2, emoji.length())); length -= 2; a--; } else if (emoji.charAt(a) == 0xfe0f) { emoji = TextUtils.concat(emoji.subSequence(0, a), emoji.subSequence(a + 1, emoji.length())); length--; a--; } } ArrayList<TLRPC.Document> newStickers = allStickers != null ? allStickers.get(emoji.toString()) : null; if (newStickers != null && !newStickers.isEmpty()) { emojiStickersArray.addAll(newStickers); for (int a = 0, size = newStickers.size(); a < size; a++) { TLRPC.Document document = newStickers.get(a); emojiStickersMap.put(document.id, document); } emojiArrays.add(emojiStickersArray); } } if (allStickers != null && !allStickers.isEmpty() && query.length() > 1) { MediaDataController.getInstance(currentAccount).getEmojiSuggestions(lastSearchKeyboardLanguage, query, false, (param, alias) -> { boolean added = false; for (int a = 0, size = param.size(); a < size; a++) { String emoji = param.get(a).emoji; ArrayList<TLRPC.Document> newStickers = allStickers != null ? allStickers.get(emoji) : null; if (newStickers != null && !newStickers.isEmpty()) { if (!emojiStickers.containsKey(newStickers)) { emojiStickers.put(newStickers, emoji); emojiArrays.add(newStickers); } } } next.run(); }, false); } }; final Utilities.Callback<Runnable> searchFromSets = next -> { ArrayList<TLRPC.TL_messages_stickerSet> stickerSets = MediaDataController.getInstance(currentAccount).getStickerSets(MediaDataController.TYPE_EMOJIPACKS); final HashSet<Long> addedSets = new HashSet<>(); final String q = translitSafe(query), sq = " " + q; if (stickerSets != null) { for (int i = 0; i < stickerSets.size(); ++i) { TLRPC.TL_messages_stickerSet set = stickerSets.get(i); if (set == null || set.set == null || set.set.title == null || set.documents == null || addedSets.contains(set.set.id)) continue; final String title = translitSafe(set.set.title); if (title.startsWith(q) || title.contains(sq)) { sets.add(new SetTitleDocument(title)); sets.addAll(set.documents); addedSets.add(set.set.id); } } } ArrayList<TLRPC.StickerSetCovered> featuredSets = MediaDataController.getInstance(currentAccount).getFeaturedEmojiSets(); if (featuredSets != null) { for (int i = 0; i < featuredSets.size(); ++i) { TLRPC.StickerSetCovered set = featuredSets.get(i); if (set == null || set.set == null || set.set.title == null || addedSets.contains(set.set.id)) continue; final String title = translitSafe(set.set.title); if (title.startsWith(q) || title.contains(sq)) { ArrayList<TLRPC.Document> documents = null; if (set instanceof TLRPC.TL_stickerSetNoCovered) { TLRPC.TL_messages_stickerSet fullSet = MediaDataController.getInstance(currentAccount).getStickerSet(MediaDataController.getInputStickerSet(set.set), set.set.hash, true); if (fullSet != null) { documents = fullSet.documents; } } else if (set instanceof TLRPC.TL_stickerSetFullCovered) { documents = ((TLRPC.TL_stickerSetFullCovered) set).documents; } else { documents = set.covers; } if (documents == null || documents.size() == 0) continue; sets.add(new SetTitleDocument(set.set.title)); sets.addAll(documents); addedSets.add(set.set.id); } } } next.run(); }; Utilities.doCallbacks(searchCategories, searchByKeywords, searchEmojiSuggestions, searchAvatarConstructor, searchFromSets, applySearch); } }, delay ? 425 : 0); if (searchBox != null) { searchBox.showProgress(true); searchBox.toggleClear(liftUp); } } updateSearchBox(); } public static TLRPC.Document findSticker(TLRPC.TL_messages_stickerSet set, String emoji) { if (set == null) return null; final String q = Emoji.fixEmoji(emoji); long documentId = 0; for (int i = 0; i < set.packs.size(); ++i) { if (!set.packs.get(i).documents.isEmpty() && TextUtils.equals(Emoji.fixEmoji(set.packs.get(i).emoticon), q)) { documentId = set.packs.get(i).documents.get(0); break; } } if (documentId == 0) return null; for (int i = 0; i < set.documents.size(); ++i) { TLRPC.Document d = set.documents.get(i); if (d.id == documentId) { return d; } } return null; } private class SearchAdapter extends RecyclerListView.SelectionAdapter { public final static int VIEW_TYPE_SEARCH = 7; public final static int VIEW_TYPE_EMOJI = 3; public final static int VIEW_TYPE_REACTION = 4; public final static int VIEW_TYPE_STICKER = 5; public final static int VIEW_TYPE_HEADER = 6; int stickersStartRow; int emojiStartRow; int emojiHeaderRow = -1; int stickersHeaderRow = -1; int setsStartRow; @Override public boolean isEnabled(RecyclerView.ViewHolder holder) { return holder.getItemViewType() == VIEW_TYPE_EMOJI || holder.getItemViewType() == VIEW_TYPE_REACTION; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view; if (viewType == VIEW_TYPE_HEADER) { view = new HeaderView(getContext(), type == TYPE_CHAT_REACTIONS); } else if (viewType == VIEW_TYPE_SEARCH) { view = new View(getContext()) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(52), MeasureSpec.EXACTLY)); } }; view.setTag("searchbox"); } else { view = new ImageViewEmoji(getContext()); } if (enterAnimationInProgress()) { view.setScaleX(0); view.setScaleY(0); } return new RecyclerListView.Holder(view); } @Override public int getItemViewType(int position) { if (position == emojiHeaderRow || position == stickersHeaderRow) { return VIEW_TYPE_HEADER; } if (position > stickersStartRow && position - stickersStartRow - 1 < stickersSearchResult.size()) { return VIEW_TYPE_STICKER; } if (searchResult == null) { return VIEW_TYPE_EMOJI; } if (position > emojiStartRow && position - emojiStartRow - 1 < searchResult.size()) { if (type == TYPE_STICKER_SET_EMOJI || searchResult.get(position - emojiStartRow - 1).documentId != 0) { return VIEW_TYPE_EMOJI; } } if (position - setsStartRow >= 0 && position - setsStartRow < searchSets.size()) { if (searchSets.get(position - setsStartRow) instanceof SetTitleDocument) { return VIEW_TYPE_HEADER; } return VIEW_TYPE_EMOJI; } return VIEW_TYPE_REACTION; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { if (holder.getItemViewType() == VIEW_TYPE_HEADER) { HeaderView header = (HeaderView) holder.itemView; if (searchSets != null && (position - setsStartRow) >= 0 && (position - setsStartRow) < searchSets.size()) { TLRPC.Document d = searchSets.get(position - setsStartRow); if (d instanceof SetTitleDocument) { header.setText(((SetTitleDocument) d).title, lastQuery, false); } } else if (position == emojiHeaderRow) { header.setText(LocaleController.getString("Emoji", R.string.Emoji), false); } else { header.setText(LocaleController.getString("AccDescrStickers", R.string.AccDescrStickers), false); } header.closeIcon.setVisibility(View.GONE); } else if (holder.getItemViewType() == VIEW_TYPE_STICKER) { int p = position - stickersStartRow - 1; TLRPC.Document document = stickersSearchResult.get(p); ImageViewEmoji imageView = (ImageViewEmoji) holder.itemView; imageView.createImageReceiver(emojiSearchGridView); SvgHelper.SvgDrawable svgThumb = DocumentObject.getSvgThumb(document, Theme.key_windowBackgroundWhiteGrayIcon, 0.2f); imageView.imageReceiver.setImage(ImageLocation.getForDocument(document), "100_100_firstframe", null, null, svgThumb, 0, "tgs", document, 0); imageView.isStaticIcon = true; imageView.document = document; imageView.span = null; } else if (holder.getItemViewType() == VIEW_TYPE_REACTION) { ImageViewEmoji imageView = (ImageViewEmoji) holder.itemView; imageView.position = position; if (searchResult == null || position < 0 || position >= searchResult.size()) { return; } ReactionsLayoutInBubble.VisibleReaction currentReaction = searchResult.get(position); if (imageView.imageReceiver == null) { imageView.imageReceiver = new ImageReceiver(imageView); imageView.imageReceiver.setLayerNum(7); imageView.imageReceiver.onAttachedToWindow(); } imageView.imageReceiver.setParentView(emojiSearchGridView); imageView.reaction = currentReaction; imageView.isFirstReactions = false; imageView.setViewSelected(selectedReactions.contains(currentReaction), false); imageView.notDraw = false; imageView.invalidate(); if (type == TYPE_STICKER_SET_EMOJI) { imageView.setDrawable(Emoji.getEmojiDrawable(currentReaction.emojicon)); } else if (currentReaction.emojicon != null) { imageView.isDefaultReaction = true; TLRPC.TL_availableReaction reaction = MediaDataController.getInstance(currentAccount).getReactionsMap().get(currentReaction.emojicon); if (reaction != null) { SvgHelper.SvgDrawable svgThumb = DocumentObject.getSvgThumb(reaction.activate_animation, Theme.key_windowBackgroundWhiteGrayIcon, 0.2f); if (!LiteMode.isEnabled(LiteMode.FLAG_ANIMATED_EMOJI_REACTIONS)) { imageView.imageReceiver.setImage(ImageLocation.getForDocument(reaction.select_animation), "60_60_firstframe", null, null, svgThumb, 0, "tgs", currentReaction, 0); } else { imageView.imageReceiver.setImage(ImageLocation.getForDocument(reaction.select_animation), ReactionsUtils.SELECT_ANIMATION_FILTER, ImageLocation.getForDocument(reaction.select_animation), "30_30_firstframe", null, null, svgThumb, 0, "tgs", currentReaction, 0); } MediaDataController.getInstance(currentAccount).preloadImage(imageView.preloadEffectImageReceiver, ImageLocation.getForDocument(reaction.around_animation), ReactionsEffectOverlay.getFilterForAroundAnimation()); } else { imageView.imageReceiver.clearImage(); imageView.preloadEffectImageReceiver.clearImage(); } imageView.span = null; imageView.document = null; imageView.setDrawable(null); if (imageView.premiumLockIconView != null) { imageView.premiumLockIconView.setVisibility(View.GONE); imageView.premiumLockIconView.setImageReceiver(null); } } else { imageView.isDefaultReaction = false; imageView.span = new AnimatedEmojiSpan(currentReaction.documentId, null); imageView.document = null; imageView.imageReceiver.clearImage(); imageView.preloadEffectImageReceiver.clearImage(); AnimatedEmojiDrawable drawable = emojiSearchGridView.animatedEmojiDrawables.get(imageView.span.getDocumentId()); // if (drawable == null) { drawable = AnimatedEmojiDrawable.make(currentAccount, getCacheType(), imageView.span.getDocumentId()); emojiSearchGridView.animatedEmojiDrawables.put(imageView.span.getDocumentId(), drawable); } imageView.setDrawable(drawable); // if (!UserConfig.getInstance(currentAccount).isPremium() && type != TYPE_AVATAR_CONSTRUCTOR && type != TYPE_TOPIC_ICON) { // imageView.createPremiumLockView(); // imageView.premiumLockIconView.setVisibility(View.VISIBLE); // } } } else if (holder.getItemViewType() == VIEW_TYPE_EMOJI) { ImageViewEmoji imageView = (ImageViewEmoji) holder.itemView; imageView.empty = false; imageView.position = position; imageView.setPadding(AndroidUtilities.dp(1), AndroidUtilities.dp(1), AndroidUtilities.dp(1), AndroidUtilities.dp(1)); boolean selected = false; imageView.setDrawable(null); Long documentId = null; TLRPC.Document document = null; if (searchResult != null && position >= 0 && position < searchResult.size()) { ReactionsLayoutInBubble.VisibleReaction visibleReaction = searchResult.get(position); if (visibleReaction.documentId == 0) { selected = selectedReactions.contains(visibleReaction); imageView.reaction = visibleReaction; imageView.isFirstReactions = true; imageView.setDrawable(Emoji.getEmojiDrawable(visibleReaction.emojicon)); imageView.setViewSelected(selected, false); return; } else { documentId = visibleReaction.documentId; } } else if (searchSets != null && (position - setsStartRow) >= 0 && (position - setsStartRow) < searchSets.size()) { document = searchSets.get(position - setsStartRow); if (document instanceof SetTitleDocument) { document = null; } } if (documentId != null || document != null) { if (document != null) { imageView.span = new AnimatedEmojiSpan(document, null); imageView.document = document; selected = selectedDocumentIds.contains(document.id); } else { imageView.span = new AnimatedEmojiSpan(documentId, null); imageView.document = imageView.span.document; selected = selectedDocumentIds.contains(documentId); } AnimatedEmojiDrawable drawable = emojiSearchGridView.animatedEmojiDrawables.get(imageView.span.getDocumentId()); if (drawable == null) { drawable = AnimatedEmojiDrawable.make(currentAccount, getCacheType(), imageView.span.getDocumentId()); emojiSearchGridView.animatedEmojiDrawables.put(imageView.span.getDocumentId(), drawable); } imageView.setDrawable(drawable); } imageView.setViewSelected(selected, false); } } private int count = 1; private ArrayList<Integer> rowHashCodes = new ArrayList<>(); @Override public int getItemCount() { return count; } public void updateRows(boolean diff) { if (!isAttached || type == TYPE_AVATAR_CONSTRUCTOR) { diff = false; } ArrayList<Integer> prevRowHashCodes = new ArrayList<>(rowHashCodes); setsStartRow = -1; count = 0; rowHashCodes.clear(); if (searchResult != null) { if (type == TYPE_AVATAR_CONSTRUCTOR && !searchResult.isEmpty()) { emojiHeaderRow = count++; rowHashCodes.add(1); } emojiStartRow = count; for (int i = 0; i < searchResult.size(); ++i) { count++; rowHashCodes.add(Objects.hash(-4342, searchResult.get(i))); } } if (stickersSearchResult != null) { if (type == TYPE_AVATAR_CONSTRUCTOR && !stickersSearchResult.isEmpty()) { stickersHeaderRow = count++; rowHashCodes.add(2); } stickersStartRow = count; for (int i = 0; i < stickersSearchResult.size(); ++i) { count++; rowHashCodes.add(Objects.hash(-7453, stickersSearchResult.get(i))); } } if (searchSets != null) { setsStartRow = count; count += searchSets.size(); } // if (diff) { // DiffUtil.calculateDiff(new DiffUtil.Callback() { // @Override // public int getOldListSize() { // return prevRowHashCodes.size(); // } // // @Override // public int getNewListSize() { // return rowHashCodes.size(); // } // // @Override // public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { // return prevRowHashCodes.get(oldItemPosition).equals(rowHashCodes.get(newItemPosition)); // } // // @Override // public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { // return true; // } // }, false).dispatchUpdatesTo(SearchAdapter.this); // } else { this.notifyDataSetChanged(); // } switchSearchEmptyView(searched && count == 0); } } private class Adapter extends RecyclerListView.SelectionAdapter { public static final int VIEW_TYPE_HEADER = 0; public static final int VIEW_TYPE_REACTION = 1; public static final int VIEW_TYPE_IMAGE = 2; public static final int VIEW_TYPE_EMOJI = 3; public static final int VIEW_TYPE_EXPAND = 4; public static final int VIEW_TYPE_BUTTON = 5; public static final int VIEW_TYPE_HINT = 6; public static final int VIEW_TYPE_SEARCH = 7; public static final int VIEW_TYPE_TOPIC_ICON = 8; public static final int VIEW_TYPE_STICKER = 9; @Override public boolean isEnabled(RecyclerView.ViewHolder holder) { int viewType = holder.getItemViewType(); return ( viewType == VIEW_TYPE_IMAGE || viewType == VIEW_TYPE_REACTION || viewType == VIEW_TYPE_EMOJI || viewType == VIEW_TYPE_TOPIC_ICON ); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view; if (viewType == VIEW_TYPE_HEADER) { view = new HeaderView(getContext(), type == TYPE_CHAT_REACTIONS); } else if (viewType == VIEW_TYPE_IMAGE) { view = new ImageView(getContext()); } else if (viewType == VIEW_TYPE_EMOJI || viewType == VIEW_TYPE_REACTION || viewType == VIEW_TYPE_TOPIC_ICON) { ImageViewEmoji imageView = new ImageViewEmoji(getContext()); if (viewType == VIEW_TYPE_TOPIC_ICON) { imageView.isStaticIcon = true; imageView.imageReceiverToDraw = imageView.imageReceiver = new ImageReceiver(imageView); imageView.imageReceiver.setImageBitmap(forumIconDrawable); forumIconImage = imageView; imageView.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8)); } view = imageView; } else if (viewType == VIEW_TYPE_EXPAND) { view = new EmojiPackExpand(getContext(), null); } else if (viewType == VIEW_TYPE_BUTTON) { view = new EmojiPackButton(getContext()); } else if (viewType == VIEW_TYPE_HINT) { TextView textView = new TextView(getContext()) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(AndroidUtilities.dp(26)), MeasureSpec.EXACTLY)); } }; textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); if (type == TYPE_TOPIC_ICON) { textView.setText(LocaleController.getString("SelectTopicIconHint", R.string.SelectTopicIconHint)); } else if (type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP) { textView.setText(LocaleController.getString("EmojiLongtapHint", R.string.EmojiLongtapHint)); } else { textView.setText(LocaleController.getString("ReactionsLongtapHint", R.string.ReactionsLongtapHint)); } textView.setGravity(Gravity.CENTER); textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText, resourcesProvider)); view = textView; } else if (viewType == VIEW_TYPE_SEARCH) { view = new FixedHeightEmptyCell(getContext(), 52); view.setTag("searchbox"); } else { view = new ImageViewEmoji(getContext()); } if (enterAnimationInProgress()) { view.setScaleX(0); view.setScaleY(0); } return new RecyclerListView.Holder(view); } @Override public int getItemViewType(int position) { if (position == searchRow) { return VIEW_TYPE_SEARCH; } else if ((position >= recentReactionsStartRow && position < recentReactionsEndRow) || (position >= topReactionsStartRow && position < topReactionsEndRow)) { return VIEW_TYPE_REACTION; } else if (positionToExpand.indexOfKey(position) >= 0) { return VIEW_TYPE_EXPAND; } else if (positionToButton.indexOfKey(position) >= 0) { return VIEW_TYPE_BUTTON; } else if (position == longtapHintRow) { return VIEW_TYPE_HINT; } else if (positionToSection.indexOfKey(position) >= 0 || position == recentReactionsSectionRow || position == popularSectionRow || position == topicEmojiHeaderRow) { return VIEW_TYPE_HEADER; } if (position == defaultTopicIconRow) { return VIEW_TYPE_TOPIC_ICON; } else { if (showStickers) { return VIEW_TYPE_EMOJI; } else { return VIEW_TYPE_EMOJI; } } } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { int viewType = holder.getItemViewType(); if (viewType == VIEW_TYPE_TOPIC_ICON) { ImageViewEmoji imageView = (ImageViewEmoji) holder.itemView; imageView.position = position; imageView.selected = selectedDocumentIds.contains(0L); return; } if (showAnimator == null || !showAnimator.isRunning()) { holder.itemView.setScaleX(1); holder.itemView.setScaleY(1); } if (viewType == VIEW_TYPE_HINT) { TextView textView = (TextView) holder.itemView; if (hintExpireDate != null) { textView.setText(LocaleController.formatString("EmojiStatusExpireHint", R.string.EmojiStatusExpireHint, LocaleController.formatStatusExpireDateTime(hintExpireDate))); } } else if (viewType == VIEW_TYPE_HEADER) { HeaderView header = (HeaderView) holder.itemView; if (position == topicEmojiHeaderRow) { header.setText(LocaleController.getString("SelectTopicIconHint", R.string.SelectTopicIconHint), false); header.closeIcon.setVisibility(View.GONE); return; } if (position == recentReactionsSectionRow) { header.setText(LocaleController.getString("RecentlyUsed", R.string.RecentlyUsed), false); // if (type == TYPE_AVATAR_CONSTRUCTOR) { header.closeIcon.setVisibility(View.GONE); // } else { // header.closeIcon.setVisibility(View.VISIBLE); // header.closeIcon.setOnClickListener((view) -> { // clearRecent(); // }); // } return; } header.closeIcon.setVisibility(View.GONE); if (position == popularSectionRow) { header.setText(LocaleController.getString("PopularReactions", R.string.PopularReactions), false); return; } int index = positionToSection.get(position); if (index >= 0) { EmojiView.EmojiPack pack = packs.get(index); header.setText(pack.set.title, !pack.free && !UserConfig.getInstance(currentAccount).isPremium() && type != TYPE_AVATAR_CONSTRUCTOR && type != TYPE_SET_REPLY_ICON && type != TYPE_SET_REPLY_ICON_BOTTOM && type != TYPE_CHAT_REACTIONS); } else { header.setText(null, false); } } else if (viewType == VIEW_TYPE_REACTION) { ImageViewEmoji imageView = (ImageViewEmoji) holder.itemView; imageView.position = position; ReactionsLayoutInBubble.VisibleReaction currentReaction; if ((position >= recentReactionsStartRow && position < recentReactionsEndRow)) { int index = position - recentReactionsStartRow; currentReaction = recentReactions.get(index); } else { int index = position - topReactionsStartRow; currentReaction = topReactions.get(index); } if (type == TYPE_STICKER_SET_EMOJI) { imageView.notDraw = false; imageView.isFirstReactions = true; imageView.reaction = currentReaction; imageView.setDrawable(Emoji.getEmojiDrawable(currentReaction.emojicon)); imageView.setViewSelected(selectedReactions.contains(currentReaction), false); return; } imageView.createImageReceiver(emojiGridView); imageView.isFirstReactions = true; imageView.reaction = currentReaction; imageView.setViewSelected(selectedReactions.contains(currentReaction), false); imageView.notDraw = false; if (currentReaction.emojicon != null) { imageView.isDefaultReaction = true; TLRPC.TL_availableReaction reaction = MediaDataController.getInstance(currentAccount).getReactionsMap().get(currentReaction.emojicon); if (reaction != null) { SvgHelper.SvgDrawable svgThumb = DocumentObject.getSvgThumb(reaction.activate_animation, Theme.key_windowBackgroundWhiteGrayIcon, 0.2f); if (!LiteMode.isEnabled(LiteMode.FLAG_ANIMATED_EMOJI_REACTIONS)) { imageView.imageReceiver.setImage(ImageLocation.getForDocument(reaction.select_animation), "60_60_firstframe", null, null, svgThumb, 0, "tgs", currentReaction, 0); } else { imageView.imageReceiver.setImage(ImageLocation.getForDocument(reaction.select_animation), ReactionsUtils.SELECT_ANIMATION_FILTER, ImageLocation.getForDocument(reaction.select_animation), "30_30_firstframe", null, null, svgThumb, 0, "tgs", currentReaction, 0); } MediaDataController.getInstance(currentAccount).preloadImage(imageView.preloadEffectImageReceiver, ImageLocation.getForDocument(reaction.around_animation), ReactionsEffectOverlay.getFilterForAroundAnimation()); } else { imageView.imageReceiver.clearImage(); imageView.preloadEffectImageReceiver.clearImage(); } imageView.span = null; imageView.document = null; imageView.setDrawable(null); if (imageView.premiumLockIconView != null) { imageView.premiumLockIconView.setVisibility(View.GONE); imageView.premiumLockIconView.setImageReceiver(null); } } else { imageView.isDefaultReaction = false; imageView.span = new AnimatedEmojiSpan(currentReaction.documentId, null); imageView.document = null; imageView.imageReceiver.clearImage(); imageView.preloadEffectImageReceiver.clearImage(); Drawable drawable = emojiGridView.animatedEmojiDrawables.get(imageView.span.getDocumentId()); if (drawable == null) { drawable = AnimatedEmojiDrawable.make(currentAccount, getCacheType(), imageView.span.getDocumentId()); emojiGridView.animatedEmojiDrawables.put(imageView.span.getDocumentId(), (AnimatedEmojiDrawable) drawable); } imageView.setDrawable(drawable); } } else if (viewType == VIEW_TYPE_EXPAND) { EmojiPackExpand button = (EmojiPackExpand) holder.itemView; final int i = positionToExpand.get(position); EmojiView.EmojiPack pack = i >= 0 && i < packs.size() ? packs.get(i) : null; if (i == -1) { recentExpandButton = button; final int maxlen = SPAN_COUNT_FOR_EMOJI * RECENT_MAX_LINES; button.textView.setText("+" + (recent.size() - maxlen + (includeEmpty ? 1 : 0) + 1)); } else if (pack != null) { if (recentExpandButton == button) { recentExpandButton = null; } final int maxlen = SPAN_COUNT_FOR_EMOJI * EXPAND_MAX_LINES; button.textView.setText("+" + (pack.documents.size() - maxlen + 1)); } else { if (recentExpandButton == button) { recentExpandButton = null; } } } else if (viewType == VIEW_TYPE_BUTTON) { EmojiPackButton button = (EmojiPackButton) holder.itemView; final int packIndex = positionToButton.get(position); if (packIndex >= 0 && packIndex < packs.size()) { EmojiView.EmojiPack pack = packs.get(packIndex); if (pack != null) { button.set(pack.set.title, !pack.free && !UserConfig.getInstance(currentAccount).isPremium(), pack.installed, e -> { if (!pack.free && !UserConfig.getInstance(currentAccount).isPremium()) { BaseFragment fragment = LaunchActivity.getLastFragment(); if (fragment != null) { fragment.showDialog(new PremiumFeatureBottomSheet(baseFragment, getContext(), currentAccount, PremiumPreviewFragment.PREMIUM_FEATURE_ANIMATED_EMOJI, false)); } return; } Integer p = null; View expandButton = null; for (int i = 0; i < emojiGridView.getChildCount(); ++i) { if (emojiGridView.getChildAt(i) instanceof EmojiPackExpand) { View child = emojiGridView.getChildAt(i); int j = emojiGridView.getChildAdapterPosition(child); if (j >= 0 && positionToExpand.get(j) == packIndex) { p = j; expandButton = child; break; } } } if (p != null) { expand(p, expandButton); } EmojiPacksAlert.installSet(null, pack.set, false); installedEmojiSets.add(pack.set.id); updateRows(true, true); }); } } } else if (viewType == VIEW_TYPE_SEARCH) { } else if (viewType == VIEW_TYPE_STICKER) { } else { ImageViewEmoji imageView = (ImageViewEmoji) holder.itemView; imageView.empty = false; imageView.position = position; imageView.setPadding(AndroidUtilities.dp(1), AndroidUtilities.dp(1), AndroidUtilities.dp(1), AndroidUtilities.dp(1)); final int recentmaxlen = SPAN_COUNT_FOR_EMOJI * RECENT_MAX_LINES; final int maxlen = SPAN_COUNT_FOR_EMOJI * EXPAND_MAX_LINES; int recentSize; if (type == TYPE_AVATAR_CONSTRUCTOR && showStickers || type == TYPE_CHAT_REACTIONS) { recentSize = recentStickers.size(); } else if (type == TYPE_AVATAR_CONSTRUCTOR || type == TYPE_TOPIC_ICON) { recentSize = recent.size(); } else { recentSize = recent.size() > recentmaxlen && !recentExpanded ? recentmaxlen : recent.size() + (includeEmpty ? 1 : 0); } boolean selected = false; if (includeEmpty && position == (searchRow != -1 ? 1 : 0) + (longtapHintRow != -1 ? 1 : 0)) { selected = selectedDocumentIds.contains(null); imageView.empty = true; imageView.setPadding(AndroidUtilities.dp(5), AndroidUtilities.dp(5), AndroidUtilities.dp(5), AndroidUtilities.dp(5)); imageView.span = null; imageView.document = null; imageView.isStaticIcon = false; if (imageView.imageReceiver != null) { imageView.imageReceiver.clearImage(); } } else if (type == TYPE_STICKER_SET_EMOJI && position - (searchRow != -1 ? 1 : 0) - (longtapHintRow != -1 ? 1 : 0) < standardEmojis.size()) { int pos = position - (searchRow != -1 ? 1 : 0) - (longtapHintRow != -1 ? 1 : 0) - (includeEmpty ? 1 : 0); String emoji = standardEmojis.get(pos); imageView.notDraw = false; imageView.isFirstReactions = false; imageView.reaction = ReactionsLayoutInBubble.VisibleReaction.fromEmojicon(emoji); imageView.setDrawable(Emoji.getEmojiDrawable(emoji)); selected = selectedReactions.contains(imageView.reaction); imageView.setViewSelected(selected, false); return; } else if (position - (searchRow != -1 ? 1 : 0) - (longtapHintRow != -1 ? 1 : 0) < recentSize) { int resentPosition = position - (searchRow != -1 ? 1 : 0) - (longtapHintRow != -1 ? 1 : 0) - (includeEmpty ? 1 : 0); if (type == TYPE_AVATAR_CONSTRUCTOR && showStickers) { TLRPC.Document document = recentStickers.get(resentPosition); imageView.setSticker(document, emojiGridView); } else if (type == TYPE_CHAT_REACTIONS) { TLRPC.Document document = recentStickers.get(resentPosition); imageView.setSticker(document, emojiGridView); selected = document != null && selectedDocumentIds.contains(document.id); } else { imageView.span = recent.get(resentPosition); imageView.document = imageView.span == null ? null : imageView.span.document; selected = imageView.span != null && selectedDocumentIds.contains(imageView.span.getDocumentId()); imageView.isStaticIcon = false; if (imageView.imageReceiver != null) { imageView.imageReceiver.clearImage(); } } } else if (!defaultStatuses.isEmpty() && position - (searchRow != -1 ? 1 : 0) - (longtapHintRow != -1 ? 1 : 0) - recentSize - 1 >= 0 && position - (searchRow != -1 ? 1 : 0) - (longtapHintRow != -1 ? 1 : 0) - recentSize - 1 < defaultStatuses.size()) { int index = position - (searchRow != -1 ? 1 : 0) - (longtapHintRow != -1 ? 1 : 0) - recentSize - 1; imageView.span = defaultStatuses.get(index); imageView.document = imageView.span == null ? null : imageView.span.document; selected = imageView.span != null && selectedDocumentIds.contains(imageView.span.getDocumentId()); imageView.isStaticIcon = false; if (imageView.imageReceiver != null) { imageView.imageReceiver.clearImage(); } } else { for (int i = 0; i < positionToSection.size(); ++i) { int startPosition = positionToSection.keyAt(i); int index = i - (defaultStatuses.isEmpty() ? 0 : 1); EmojiView.EmojiPack pack = index >= 0 ? packs.get(index) : null; if (pack == null) { continue; } int count = pack.expanded ? pack.documents.size() : Math.min(pack.documents.size(), maxlen); if (position > startPosition && position <= startPosition + 1 + count) { TLRPC.Document document = pack.documents.get(position - startPosition - 1); if (document != null) { if (showStickers) { imageView.setSticker(document, emojiSearchGridView); } else { imageView.isStaticIcon = false; if (imageView.imageReceiver != null) { imageView.imageReceiver.clearImage(); } imageView.span = new AnimatedEmojiSpan(document, null); } imageView.document = document; } } } selected = imageView.span != null && selectedDocumentIds.contains(imageView.span.getDocumentId()); } if (imageView.span != null) { AnimatedEmojiDrawable drawable = emojiGridView.animatedEmojiDrawables.get(imageView.span.getDocumentId()); if (drawable == null) { drawable = AnimatedEmojiDrawable.make(currentAccount, getCacheType(), imageView.span.getDocumentId()); emojiGridView.animatedEmojiDrawables.put(imageView.span.getDocumentId(), drawable); } imageView.setDrawable(drawable); } else { imageView.setDrawable(null); } imageView.setViewSelected(selected, false); } } @Override public int getItemCount() { return totalCount; } @Override public long getItemId(int position) { return Math.abs(rowHashCodes.get(position)); } } private boolean enterAnimationInProgress() { return enterAnimationInProgress || (showAnimator != null && showAnimator.isRunning()); } private void clearRecent() { if ((type == TYPE_REACTIONS || type == TYPE_TAGS) && onRecentClearedListener != null) { onRecentClearedListener.onRecentCleared(); } } private class HeaderView extends FrameLayout { private LinearLayout layoutView; private TextView textView; private RLottieImageView lockView; ImageView closeIcon; public HeaderView(Context context, boolean leftGravity) { super(context); layoutView = new LinearLayout(context); layoutView.setOrientation(LinearLayout.HORIZONTAL); addView(layoutView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, leftGravity ? Gravity.LEFT : Gravity.CENTER)); lockView = new RLottieImageView(context); lockView.setAnimation(R.raw.unlock_icon, 20, 20); lockView.setColorFilter(Theme.getColor(Theme.key_chat_emojiPanelStickerSetName, resourcesProvider)); layoutView.addView(lockView, LayoutHelper.createLinear(20, 20)); textView = new TextView(context); textView.setTextColor(Theme.getColor(Theme.key_chat_emojiPanelStickerSetName, resourcesProvider)); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setLines(1); textView.setMaxLines(1); textView.setSingleLine(true); layoutView.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); closeIcon = new ImageView(context); closeIcon.setImageResource(R.drawable.msg_close); closeIcon.setScaleType(ImageView.ScaleType.CENTER); closeIcon.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelStickerSetNameIcon, resourcesProvider), PorterDuff.Mode.MULTIPLY)); addView(closeIcon, LayoutHelper.createFrame(24, 24, Gravity.RIGHT | Gravity.CENTER_VERTICAL)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(30), MeasureSpec.EXACTLY)); } public void setText(String text, boolean lock) { this.textView.setText(text); updateLock(lock, false); } public void setText(String text, String query, boolean lock) { CharSequence finalText = text; if (text != null && query != null) { final int index = text.toLowerCase().indexOf(query.toLowerCase()); if (index >= 0) { SpannableString spannableString = new SpannableString(text); spannableString.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_chat_emojiPanelStickerSetNameHighlight, resourcesProvider)), index, index + query.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); finalText = spannableString; } } this.textView.setText(finalText); updateLock(lock, false); } private float lockT; private ValueAnimator lockAnimator; public void updateLock(boolean lock, boolean animated) { if (lockAnimator != null) { lockAnimator.cancel(); lockAnimator = null; } if (animated) { lockAnimator = ValueAnimator.ofFloat(lockT, lock ? 1f : 0f); lockAnimator.addUpdateListener(anm -> { lockT = (float) anm.getAnimatedValue(); lockView.setTranslationX(AndroidUtilities.dp(-8) * (1f - lockT)); textView.setTranslationX(AndroidUtilities.dp(-8) * (1f - lockT)); lockView.setAlpha(lockT); }); lockAnimator.setDuration(200); lockAnimator.setInterpolator(CubicBezierInterpolator.EASE_BOTH); lockAnimator.start(); } else { lockT = lock ? 1f : 0f; lockView.setTranslationX(AndroidUtilities.dp(-8) * (1f - lockT)); textView.setTranslationX(AndroidUtilities.dp(-8) * (1f - lockT)); lockView.setAlpha(lockT); } } } private class EmojiPackButton extends FrameLayout { FrameLayout addButtonView; AnimatedTextView addButtonTextView; PremiumButtonView premiumButtonView; public EmojiPackButton(Context context) { super(context); addButtonTextView = new AnimatedTextView(getContext()) { @Override public void invalidate() { if (HwEmojis.grab(this)) { return; } super.invalidate(); } @Override public void invalidate(int l, int t, int r, int b) { if (HwEmojis.grab(this)) { return; } super.invalidate(l, t, r, b); } }; addButtonTextView.setAnimationProperties(.3f, 0, 250, CubicBezierInterpolator.EASE_OUT_QUINT); addButtonTextView.setTextSize(AndroidUtilities.dp(14)); addButtonTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); addButtonTextView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText, resourcesProvider)); addButtonTextView.setGravity(Gravity.CENTER); addButtonView = new FrameLayout(getContext()); addButtonView.setBackground(Theme.AdaptiveRipple.filledRect(Theme.getColor(Theme.key_featuredStickers_addButton, resourcesProvider), 8)); addButtonView.addView(addButtonTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); addView(addButtonView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); premiumButtonView = new PremiumButtonView(getContext(), false, resourcesProvider); premiumButtonView.setIcon(R.raw.unlock_icon); addView(premiumButtonView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); } private String lastTitle; public void set(String title, boolean unlock, boolean installed, OnClickListener onClickListener) { lastTitle = title; if (unlock) { addButtonView.setVisibility(View.GONE); premiumButtonView.setVisibility(View.VISIBLE); premiumButtonView.setButton(LocaleController.formatString("UnlockPremiumEmojiPack", R.string.UnlockPremiumEmojiPack, title), onClickListener); } else { premiumButtonView.setVisibility(View.GONE); addButtonView.setVisibility(View.VISIBLE); addButtonView.setOnClickListener(onClickListener); } updateInstall(installed, false); updateLock(unlock, false); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setPadding(AndroidUtilities.dp(5), AndroidUtilities.dp(8), AndroidUtilities.dp(5), AndroidUtilities.dp(8)); super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(44) + getPaddingTop() + getPaddingBottom(), MeasureSpec.EXACTLY)); } private ValueAnimator installFadeAway; public void updateInstall(boolean installed, boolean animated) { CharSequence text = installed ? LocaleController.getString("Added", R.string.Added) : LocaleController.formatString("AddStickersCount", R.string.AddStickersCount, lastTitle); addButtonTextView.setText(text, animated); if (installFadeAway != null) { installFadeAway.cancel(); installFadeAway = null; } addButtonView.setEnabled(!installed); if (animated) { installFadeAway = ValueAnimator.ofFloat(addButtonView.getAlpha(), installed ? .6f : 1f); addButtonView.setAlpha(addButtonView.getAlpha()); installFadeAway.addUpdateListener(anm -> { if (addButtonView != null) { addButtonView.setAlpha((float) anm.getAnimatedValue()); } }); installFadeAway.setDuration(450); installFadeAway.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); installFadeAway.start(); } else { addButtonView.setAlpha(installed ? .6f : 1f); } } private float lockT; private Boolean lockShow; private ValueAnimator lockAnimator; private void updateLock(boolean show, boolean animated) { if (lockAnimator != null) { lockAnimator.cancel(); lockAnimator = null; } if (lockShow != null && lockShow == show) { return; } lockShow = show; if (animated) { premiumButtonView.setVisibility(View.VISIBLE); lockAnimator = ValueAnimator.ofFloat(lockT, show ? 1f : 0f); lockAnimator.addUpdateListener(anm -> { lockT = (float) anm.getAnimatedValue(); if (addButtonView != null) { addButtonView.setAlpha(1f - lockT); } if (premiumButtonView != null) { premiumButtonView.setAlpha(lockT); } }); lockAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (!show) { premiumButtonView.setVisibility(View.GONE); } } }); lockAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); lockAnimator.setDuration(350); lockAnimator.start(); } else { lockT = lockShow ? 1 : 0; addButtonView.setAlpha(1f - lockT); premiumButtonView.setAlpha(lockT); premiumButtonView.setScaleX(lockT); premiumButtonView.setScaleY(lockT); premiumButtonView.setVisibility(lockShow ? View.VISIBLE : View.GONE); } } } public class EmojiPackExpand extends FrameLayout { public TextView textView; public EmojiPackExpand(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); textView.setTextColor(0xffffffff);// Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider)); final int backgroundColor = useAccentForPlus ? Theme.blendOver(accentColor, Theme.multAlpha(Theme.getColor(Theme.key_windowBackgroundWhite), .4f)) : ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_chat_emojiPanelStickerSetName, resourcesProvider), 99); textView.setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(11), backgroundColor)); textView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); textView.setPadding(AndroidUtilities.dp(4), AndroidUtilities.dp(1.66f), AndroidUtilities.dp(4), AndroidUtilities.dp(2f)); addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); } } private View animateExpandFromButton; private float animateExpandFromButtonTranslate; private int animateExpandFromPosition = -1, animateExpandToPosition = -1; private long animateExpandStartTime = -1; public long animateExpandDuration() { return animateExpandAppearDuration() + animateExpandCrossfadeDuration() + 16; } public long animateExpandAppearDuration() { int count = animateExpandToPosition - animateExpandFromPosition; return Math.max(450, Math.min(55, count) * 30L); } public long animateExpandCrossfadeDuration() { int count = animateExpandToPosition - animateExpandFromPosition; return Math.max(300, Math.min(45, count) * 25L); } public class ImageViewEmoji extends View { public boolean empty = false; public boolean notDraw = false; public int position; public TLRPC.Document document; public AnimatedEmojiSpan span; public ImageReceiver.BackgroundThreadDrawHolder[] backgroundThreadDrawHolder = new ImageReceiver.BackgroundThreadDrawHolder[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; public ImageReceiver imageReceiver; public ImageReceiver preloadEffectImageReceiver = new ImageReceiver(); public ImageReceiver imageReceiverToDraw; public boolean isDefaultReaction; public ReactionsLayoutInBubble.VisibleReaction reaction; public boolean isFirstReactions; public Drawable drawable; public Rect drawableBounds; public float bigReactionSelectedProgress; public boolean attached; ValueAnimator backAnimator; PremiumLockIconView premiumLockIconView; public boolean selected; private boolean shouldSelected; private float pressedProgress; public float skewAlpha; public int skewIndex; public boolean isStaticIcon; private float selectedProgress; private float animatedScale = 1f; final AnimatedEmojiSpan.InvalidateHolder invalidateHolder = () -> { if (HwEmojis.isHwEnabled()) { return; } if (getParent() != null) { ((View) getParent()).invalidate(); } }; public ImageViewEmoji(Context context) { super(context); preloadEffectImageReceiver.ignoreNotifications = true; } /** * {@link View#setScaleX} causes an implicit redraw of the parent. Therefore, we use a custom method. */ public void setAnimatedScale(float scale) { animatedScale = scale; } public float getAnimatedScale() { return animatedScale; } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY)); } @Override public void setPressed(boolean pressed) { if (isPressed() != pressed) { super.setPressed(pressed); invalidate(); if (pressed) { if (backAnimator != null) { backAnimator.removeAllListeners(); backAnimator.cancel(); } } if (!pressed && pressedProgress != 0) { backAnimator = ValueAnimator.ofFloat(pressedProgress, 0); backAnimator.addUpdateListener(animation -> { pressedProgress = (float) animation.getAnimatedValue(); emojiGridView.invalidate(); }); backAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); backAnimator = null; } }); backAnimator.setInterpolator(new OvershootInterpolator(5.0f)); backAnimator.setDuration(350); backAnimator.start(); } } } public void updatePressedProgress() { if (isPressed() && pressedProgress != 1f) { pressedProgress = Utilities.clamp(pressedProgress + 16f / 100f, 1f, 0); invalidate(); } } public void update(long time) { if (imageReceiverToDraw != null) { if (imageReceiverToDraw.getLottieAnimation() != null) { imageReceiverToDraw.getLottieAnimation().updateCurrentFrame(time, true); } if (imageReceiverToDraw.getAnimation() != null) { imageReceiverToDraw.getAnimation().updateCurrentFrame(time, true); } } } private void cancelBackAnimator() { if (backAnimator != null) { backAnimator.removeAllListeners(); backAnimator.cancel(); } } public void unselectWithScale() { if (selected) { cancelBackAnimator(); pressedProgress = 1f; backAnimator = ValueAnimator.ofFloat(pressedProgress, 0); backAnimator.addUpdateListener(animation -> { pressedProgress = (float) animation.getAnimatedValue(); emojiGridView.invalidate(); }); backAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); backAnimator = null; } }); backAnimator.setInterpolator(new OvershootInterpolator(5.0f)); backAnimator.setDuration(350); backAnimator.start(); setViewSelected(false, true); } } public void setViewSelectedWithScale(boolean selected, boolean animated) { boolean wasSelected = this.selected; if (!wasSelected && selected && animated) { shouldSelected = true; selectedProgress = 1f; cancelBackAnimator(); backAnimator = ValueAnimator.ofFloat(pressedProgress, 1.6f, 0.7f); backAnimator.addUpdateListener(animation -> { pressedProgress = (float) animation.getAnimatedValue(); emojiGridView.invalidate(); }); backAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); pressedProgress = 0; backAnimator = null; shouldSelected = false; setViewSelected(true, false); } }); backAnimator.setInterpolator(new LinearInterpolator()); backAnimator.setDuration(200); backAnimator.start(); } else { shouldSelected = false; setViewSelected(selected, animated); } } public void setViewSelected(boolean selected, boolean animated) { if (this.selected != selected) { this.selected = selected; if (!animated) { selectedProgress = selected ? 1f : 0f; } } } public void drawSelected(Canvas canvas, View view) { if ((selected || shouldSelected || selectedProgress > 0) && !notDraw) { if (((selected || shouldSelected) && selectedProgress < 1f)) { selectedProgress += 16 / 300f; view.invalidate(); } if ((!selected && !shouldSelected && selectedProgress > 0)) { selectedProgress -= 16 / 300f; view.invalidate(); } selectedProgress = Utilities.clamp(selectedProgress, 1f, 0f); int inset = AndroidUtilities.dp(type == TYPE_CHAT_REACTIONS ? 1.5f : 1f); int round = AndroidUtilities.dp(type == TYPE_CHAT_REACTIONS ? 6f : 4f); AndroidUtilities.rectTmp.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); AndroidUtilities.rectTmp.inset(inset, inset); Paint paint = empty || drawable instanceof AnimatedEmojiDrawable && ((AnimatedEmojiDrawable) drawable).canOverrideColor() ? selectorAccentPaint : selectorPaint; int wasAlpha = paint.getAlpha(); paint.setAlpha((int) (wasAlpha * getAlpha() * selectedProgress)); canvas.drawRoundRect(AndroidUtilities.rectTmp, round, round, paint); paint.setAlpha(wasAlpha); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (attached) { return; } attached = true; if (drawable instanceof AnimatedEmojiDrawable) { ((AnimatedEmojiDrawable) drawable).addView(invalidateHolder); } if (imageReceiver != null) { imageReceiver.setParentView((View) getParent()); imageReceiver.onAttachedToWindow(); } preloadEffectImageReceiver.onAttachedToWindow(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (!attached) { return; } attached = false; if (this.drawable instanceof AnimatedEmojiDrawable) { ((AnimatedEmojiDrawable) this.drawable).removeView(invalidateHolder); } if (imageReceiver != null) { imageReceiver.onDetachedFromWindow(); } preloadEffectImageReceiver.onDetachedFromWindow(); } public void setDrawable(Drawable drawable) { if (this.drawable != drawable) { if (attached && this.drawable != null && this.drawable instanceof AnimatedEmojiDrawable) { ((AnimatedEmojiDrawable) this.drawable).removeView(invalidateHolder); } this.drawable = drawable; if (attached && drawable instanceof AnimatedEmojiDrawable) { ((AnimatedEmojiDrawable) drawable).addView(invalidateHolder); } } } public void setSticker(TLRPC.Document document, View parent) { this.document = document; createImageReceiver(parent); Drawable thumb = null; // if (type == TYPE_STICKER_SET_EMOJI) { // thumb = Emoji.getEmojiDrawable(MessageObject.findAnimatedEmojiEmoticon(document, null)); // } if (thumb == null) { thumb = DocumentObject.getSvgThumb(document, Theme.key_windowBackgroundWhiteGrayIcon, 0.2f); } if (type == TYPE_CHAT_REACTIONS) { imageReceiver.setImage(ImageLocation.getForDocument(document), !LiteMode.isEnabled(LiteMode.FLAG_ANIMATED_EMOJI_KEYBOARD) ? "34_34_firstframe" : "34_34", null, null, thumb, document.size, null, document, 0); } else { imageReceiver.setImage(ImageLocation.getForDocument(document), "100_100_firstframe", null, null, thumb, 0, "tgs", document, 0); } isStaticIcon = true; span = null; } public void createImageReceiver(View parent) { if (imageReceiver == null) { imageReceiver = new ImageReceiver(parent); imageReceiver.setLayerNum(7); if (attached) { imageReceiver.onAttachedToWindow(); } imageReceiver.setAspectFit(true); } } @Override public void invalidate() { if (HwEmojis.isHwEnabled()) { return; } if (getParent() != null) { ((View) getParent()).invalidate(); } } @Override public void invalidate(int l, int t, int r, int b) { if (HwEmojis.isHwEnabled()) { return; } super.invalidate(l, t, r, b); } public void createPremiumLockView() { if (premiumLockIconView == null) { premiumLockIconView = new PremiumLockIconView(getContext(), PremiumLockIconView.TYPE_STICKERS_PREMIUM_LOCKED); int measureSpec = MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(12), MeasureSpec.EXACTLY); premiumLockIconView.measure(measureSpec, measureSpec); premiumLockIconView.layout(0, 0, premiumLockIconView.getMeasuredWidth(), premiumLockIconView.getMeasuredHeight()); } } } public void onEmojiClick(View view, AnimatedEmojiSpan span) { incrementHintUse(); if (span == null || (type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP) && selectedDocumentIds.contains(span.documentId)) { onEmojiSelected(view, null, null, null); } else { TLRPC.TL_emojiStatus status = new TLRPC.TL_emojiStatus(); status.document_id = span.getDocumentId(); TLRPC.Document document = span.document == null ? AnimatedEmojiDrawable.findDocument(currentAccount, span.documentId) : span.document; if (view instanceof ImageViewEmoji) { if (type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP) { MediaDataController.getInstance(currentAccount).pushRecentEmojiStatus(status); } if (type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP || type == TYPE_SET_DEFAULT_REACTION) { animateEmojiSelect((ImageViewEmoji) view, () -> { onEmojiSelected(view, span.documentId, document, null); }); } else { onEmojiSelected(view, span.documentId, document, null); } } else { onEmojiSelected(view, span.documentId, document, null); } } } private void incrementHintUse() { if (type == TYPE_SET_DEFAULT_REACTION) { return; } final String key = "emoji" + (type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP ? "status" : "reaction") + "usehint"; final int value = MessagesController.getGlobalMainSettings().getInt(key, 0); if (value <= 3) { MessagesController.getGlobalMainSettings().edit().putInt(key, value + 1).apply(); } } protected void onReactionClick(ImageViewEmoji emoji, ReactionsLayoutInBubble.VisibleReaction reaction) { } protected void onEmojiSelected(View view, Long documentId, TLRPC.Document document, Integer until) { } public void preload(int type, int account) { if (MediaDataController.getInstance(account) == null) { return; } MediaDataController.getInstance(account).checkStickers(MediaDataController.TYPE_EMOJIPACKS); if (type == TYPE_REACTIONS || type == TYPE_TAGS || type == TYPE_SET_DEFAULT_REACTION || type == TYPE_CHAT_REACTIONS || type == TYPE_STICKER_SET_EMOJI) { MediaDataController.getInstance(account).checkReactions(); } else if (type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP) { if (MessagesController.getInstance(account).getMainSettings().getBoolean("resetemojipacks", true)) { MediaDataController.getInstance(account).loadStickers(MediaDataController.TYPE_EMOJIPACKS, false, false); MessagesController.getInstance(account).getMainSettings().edit().putBoolean("resetemojipacks", false).commit(); } MediaDataController.getInstance(account).fetchEmojiStatuses(2, false); MediaDataController.getInstance(account).loadRestrictedStatusEmojis(); MediaDataController.getInstance(account).getStickerSet(new TLRPC.TL_inputStickerSetEmojiChannelDefaultStatuses(), false); } else if (type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP) { MediaDataController.getInstance(account).fetchEmojiStatuses(0, true); MediaDataController.getInstance(account).getStickerSet(new TLRPC.TL_inputStickerSetEmojiDefaultStatuses(), false); } else if (type == TYPE_TOPIC_ICON) { MediaDataController.getInstance(account).checkDefaultTopicIcons(); } else if (type == TYPE_AVATAR_CONSTRUCTOR) { MediaDataController.getInstance(account).loadRecents(MediaDataController.TYPE_IMAGE, false, true, false); MediaDataController.getInstance(account).checkStickers(MediaDataController.TYPE_IMAGE); } } private static boolean[] preloaded = new boolean[UserConfig.MAX_ACCOUNT_COUNT]; public static void preload(int account) { if (preloaded[account] || MediaDataController.getInstance(account) == null) { return; } preloaded[account] = true; MediaDataController.getInstance(account).checkStickers(MediaDataController.TYPE_EMOJIPACKS); MediaDataController.getInstance(account).fetchEmojiStatuses(0, true); MediaDataController.getInstance(account).checkReactions(); MediaDataController.getInstance(account).getStickerSet(new TLRPC.TL_inputStickerSetEmojiDefaultStatuses(), false); MediaDataController.getInstance(account).getDefaultEmojiStatuses(); MediaDataController.getInstance(account).checkDefaultTopicIcons(); StickerCategoriesListView.preload(account, StickerCategoriesListView.CategoriesType.STATUS); } private boolean defaultSetLoading = false; private void updateRows(boolean updateEmojipacks, boolean animated) { updateRows(updateEmojipacks, animated, true); } private void updateRows(boolean updateEmojipacks, boolean animated, boolean diff) { if (!animationsEnabled) { animated = false; } MediaDataController mediaDataController = MediaDataController.getInstance(currentAccount); if (mediaDataController == null) { return; } if (updateEmojipacks || frozenEmojiPacks == null) { frozenEmojiPacks = new ArrayList<>(mediaDataController.getStickerSets(showStickers ? MediaDataController.TYPE_IMAGE : MediaDataController.TYPE_EMOJIPACKS)); } ArrayList<TLRPC.TL_messages_stickerSet> installedEmojipacks = frozenEmojiPacks; ArrayList<TLRPC.StickerSetCovered> featuredEmojiPacks = new ArrayList<>(mediaDataController.getFeaturedEmojiSets()); ArrayList<Long> prevRowHashCodes = new ArrayList<>(rowHashCodes); totalCount = 0; recentReactionsSectionRow = -1; recentReactionsStartRow = -1; recentReactionsEndRow = -1; popularSectionRow = -1; longtapHintRow = -1; defaultTopicIconRow = -1; topicEmojiHeaderRow = -1; recent.clear(); defaultStatuses.clear(); topReactions.clear(); recentReactions.clear(); packs.clear(); positionToSection.clear(); sectionToPosition.clear(); positionToExpand.clear(); rowHashCodes.clear(); positionToButton.clear(); stickerSets.clear(); recentStickers.clear(); standardEmojis.clear(); if ((!installedEmojipacks.isEmpty() || type == TYPE_AVATAR_CONSTRUCTOR) && type != TYPE_SET_REPLY_ICON && type != TYPE_SET_REPLY_ICON_BOTTOM && type != TYPE_CHAT_REACTIONS && type != TYPE_EXPANDABLE_REACTIONS) { searchRow = totalCount++; rowHashCodes.add(9L); } else { searchRow = -1; } if (type == TYPE_SET_REPLY_ICON || type == TYPE_SET_REPLY_ICON_BOTTOM) { if (includeEmpty) { totalCount++; rowHashCodes.add(2L); } TLRPC.TL_emojiList emojiList = MediaDataController.getInstance(currentAccount).replyIconsDefault; if (emojiList != null && emojiList.document_id != null && !emojiList.document_id.isEmpty()) { for (int i = 0; i < emojiList.document_id.size(); ++i) { recent.add(new AnimatedEmojiSpan(emojiList.document_id.get(i), null)); } for (int i = 0; i < recent.size(); ++i) { rowHashCodes.add(43223L + 13L * recent.get(i).getDocumentId()); totalCount++; } } } else if (type == TYPE_AVATAR_CONSTRUCTOR) { if (showStickers) { recentStickers.addAll(MediaDataController.getInstance(currentAccount).getRecentStickersNoCopy(MediaDataController.TYPE_IMAGE)); for (int i = 0; i < recentStickers.size(); ++i) { rowHashCodes.add(62425L + 13L * recentStickers.get(i).id); totalCount++; } } else { TLRPC.TL_emojiList emojiList = forUser ? MediaDataController.getInstance(currentAccount).profileAvatarConstructorDefault : MediaDataController.getInstance(currentAccount).groupAvatarConstructorDefault; if (emojiList != null && emojiList.document_id != null && !emojiList.document_id.isEmpty()) { for (int i = 0; i < emojiList.document_id.size(); ++i) { recent.add(new AnimatedEmojiSpan(emojiList.document_id.get(i), null)); } for (int i = 0; i < recent.size(); ++i) { rowHashCodes.add(43223L + 13L * recent.get(i).getDocumentId()); totalCount++; } } } } else if (type == TYPE_CHAT_REACTIONS) { if (includeEmpty) { totalCount++; rowHashCodes.add(2L); } List<TLRPC.TL_availableReaction> enabledReactions = MediaDataController.getInstance(currentAccount).getEnabledReactionsList(); for (int i = 0; i < enabledReactions.size(); ++i) { TLRPC.TL_availableReaction reaction = enabledReactions.get(i); recentStickers.add(reaction.activate_animation); } for (int i = 0; i < recentStickers.size(); ++i) { rowHashCodes.add(62425L + 13L * recentStickers.get(i).id); totalCount++; } } else if (type == TYPE_TOPIC_ICON) { topicEmojiHeaderRow = totalCount++; rowHashCodes.add(12L); defaultTopicIconRow = totalCount++; rowHashCodes.add(7L); String packName = UserConfig.getInstance(currentAccount).defaultTopicIcons; TLRPC.TL_messages_stickerSet defaultSet = null; if (packName != null) { defaultSet = MediaDataController.getInstance(currentAccount).getStickerSetByName(packName); if (defaultSet == null) { defaultSet = MediaDataController.getInstance(currentAccount).getStickerSetByEmojiOrName(packName); } } if (defaultSet == null) { defaultSetLoading = true; } else { if (includeEmpty) { totalCount++; rowHashCodes.add(2L); } if (defaultSet.documents != null && !defaultSet.documents.isEmpty()) { for (int i = 0; i < defaultSet.documents.size(); ++i) { recent.add(new AnimatedEmojiSpan(defaultSet.documents.get(i), null)); } } for (int i = 0; i < recent.size(); ++i) { rowHashCodes.add(43223L + 13L * recent.get(i).getDocumentId()); totalCount++; } } } if (includeHint && type != TYPE_STICKER_SET_EMOJI && type != TYPE_SET_DEFAULT_REACTION && type != TYPE_TAGS && type != TYPE_TOPIC_ICON && type != TYPE_CHAT_REACTIONS && type != TYPE_EXPANDABLE_REACTIONS && type != TYPE_AVATAR_CONSTRUCTOR && type != TYPE_SET_REPLY_ICON && type != TYPE_SET_REPLY_ICON_BOTTOM) { longtapHintRow = totalCount++; rowHashCodes.add(6L); } HashSet<Long> restricted = null; if (type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP) { TLRPC.TL_emojiList emojiList = MediaDataController.getInstance(currentAccount).restrictedStatusEmojis; if (emojiList != null) { restricted = new HashSet<>(); restricted.addAll(emojiList.document_id); } } if (recentReactionsToSet != null) { topReactionsStartRow = totalCount; ArrayList<ReactionsLayoutInBubble.VisibleReaction> tmp = new ArrayList<>(recentReactionsToSet); if (type == TYPE_STICKER_SET_EMOJI && tmp.size() > 8) { tmp.removeAll(tmp.subList(8, tmp.size())); } if (type == TYPE_EXPANDABLE_REACTIONS || type == TYPE_TAGS || type == TYPE_STICKER_SET_EMOJI) { topReactions.addAll(tmp); } else { for (int i = 0; i < 16; i++) { if (!tmp.isEmpty()) { topReactions.add(tmp.remove(0)); } } } for (int i = 0; i < topReactions.size(); ++i) { rowHashCodes.add(-5632L + 13L * topReactions.get(i).hashCode()); } totalCount += topReactions.size(); topReactionsEndRow = totalCount; if (!tmp.isEmpty() && type != TYPE_EXPANDABLE_REACTIONS && type != TYPE_TAGS && type != TYPE_STICKER_SET_EMOJI) { boolean allRecentReactionsIsDefault = true; for (int i = 0; i < tmp.size(); i++) { if (tmp.get(i).documentId != 0) { allRecentReactionsIsDefault = false; break; } } if (allRecentReactionsIsDefault) { if (UserConfig.getInstance(currentAccount).isPremium()) { popularSectionRow = totalCount++; rowHashCodes.add(5L); } } else { recentReactionsSectionRow = totalCount++; rowHashCodes.add(4L); } recentReactionsStartRow = totalCount; recentReactions.addAll(tmp); for (int i = 0; i < recentReactions.size(); ++i) { rowHashCodes.add((allRecentReactionsIsDefault ? 4235 : -3142) + 13L * recentReactions.get(i).hash); } totalCount += recentReactions.size(); recentReactionsEndRow = totalCount; } } else if (type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP) { ArrayList<TLRPC.EmojiStatus> recentEmojiStatuses = MediaDataController.getInstance(currentAccount).getRecentEmojiStatuses(); TLRPC.TL_messages_stickerSet defaultSet = MediaDataController.getInstance(currentAccount).getStickerSet(type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP ? new TLRPC.TL_inputStickerSetEmojiDefaultStatuses() : new TLRPC.TL_inputStickerSetEmojiChannelDefaultStatuses(), true); if (defaultSet == null) { defaultSetLoading = true; } else { if (includeEmpty) { totalCount++; rowHashCodes.add(2L); } ArrayList<TLRPC.EmojiStatus> defaultEmojiStatuses; if (type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP) { defaultEmojiStatuses = MediaDataController.getInstance(currentAccount).getDefaultEmojiStatuses(); } else { defaultEmojiStatuses = MediaDataController.getInstance(currentAccount).getDefaultChannelEmojiStatuses(); } final int maxrecentlen = SPAN_COUNT_FOR_EMOJI * (RECENT_MAX_LINES + 8); if (defaultSet.documents != null && !defaultSet.documents.isEmpty()) { for (int i = 0; i < Math.min(SPAN_COUNT_FOR_EMOJI - 1, defaultSet.documents.size()); ++i) { recent.add(new AnimatedEmojiSpan(defaultSet.documents.get(i), null)); if (recent.size() + (includeEmpty ? 1 : 0) >= maxrecentlen) { break; } } } if ((type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP) && recentEmojiStatuses != null && !recentEmojiStatuses.isEmpty()) { for (TLRPC.EmojiStatus emojiStatus : recentEmojiStatuses) { Long did = UserObject.getEmojiStatusDocumentId(emojiStatus); if (did == null) { continue; } boolean foundDuplicate = false; for (int i = 0; i < recent.size(); ++i) { if (recent.get(i).getDocumentId() == did) { foundDuplicate = true; break; } } if (foundDuplicate) continue; recent.add(new AnimatedEmojiSpan(did, null)); if (recent.size() + (includeEmpty ? 1 : 0) >= maxrecentlen) { break; } } } if (defaultEmojiStatuses != null && !defaultEmojiStatuses.isEmpty()) { for (TLRPC.EmojiStatus emojiStatus : defaultEmojiStatuses) { Long did = UserObject.getEmojiStatusDocumentId(emojiStatus); if (did == null) { continue; } boolean foundDuplicate = false; for (int i = 0; i < recent.size(); ++i) { if (recent.get(i).getDocumentId() == did) { foundDuplicate = true; break; } } if (!foundDuplicate) { recent.add(new AnimatedEmojiSpan(did, null)); if (recent.size() + (includeEmpty ? 1 : 0) >= maxrecentlen) { break; } } } } final int maxlen = SPAN_COUNT_FOR_EMOJI * RECENT_MAX_LINES; int len = maxlen - (includeEmpty ? 1 : 0); if (recent.size() > len && !recentExpanded) { for (int i = 0; i < len - 1; ++i) { rowHashCodes.add(43223 + 13L * recent.get(i).getDocumentId()); totalCount++; } rowHashCodes.add(-5531 + 13L * (recent.size() - maxlen + (includeEmpty ? 1 : 0) + 1)); if (recentExpandButton != null) { recentExpandButton.textView.setText("+" + (recent.size() - maxlen + (includeEmpty ? 1 : 0) + 1)); } positionToExpand.put(totalCount, -1); totalCount++; } else { for (int i = 0; i < recent.size(); ++i) { rowHashCodes.add(43223 + 13L * recent.get(i).getDocumentId()); totalCount++; } } } } if (type == TYPE_STICKER_SET_EMOJI) { for (String[] section : EmojiData.dataColored) { for (String emoji : section) { standardEmojis.add(emoji); rowHashCodes.add(13334 + 322L * emoji.hashCode()); totalCount++; } } } if (installedEmojipacks != null && type != TYPE_EXPANDABLE_REACTIONS && type != TYPE_STICKER_SET_EMOJI) { for (int i = 0, j = 0; i < installedEmojipacks.size(); ++i) { TLRPC.TL_messages_stickerSet set = installedEmojipacks.get(i); if (set == null || set.set == null) { continue; } if ((type == TYPE_SET_REPLY_ICON || type == TYPE_SET_REPLY_ICON_BOTTOM) && !MessageObject.isTextColorSet(set)) { continue; } if ((type == TYPE_EMOJI_STATUS_CHANNEL_TOP || type == TYPE_EMOJI_STATUS_CHANNEL) && !set.set.channel_emoji_status) { continue; } if ((set.set.emojis || showStickers) && !installedEmojiSets.contains(set.set.id)) { positionToSection.put(totalCount, packs.size()); sectionToPosition.put(packs.size(), totalCount); totalCount++; rowHashCodes.add(9211 + 13L * set.set.id); EmojiView.EmojiPack pack = new EmojiView.EmojiPack(); pack.installed = true; pack.featured = false; pack.expanded = true; pack.free = !MessageObject.isPremiumEmojiPack(set); pack.set = set.set; pack.documents = filter(set.documents, restricted); pack.index = packs.size(); packs.add(pack); totalCount += pack.documents.size(); for (int k = 0; k < pack.documents.size(); ++k) { rowHashCodes.add(3212 + 13L * pack.documents.get(k).id); } j++; } } } if (featuredEmojiPacks != null && !showStickers && type != TYPE_EXPANDABLE_REACTIONS && type != TYPE_STICKER_SET_EMOJI) { final int maxlen = SPAN_COUNT_FOR_EMOJI * EXPAND_MAX_LINES; for (int i = 0; i < featuredEmojiPacks.size(); ++i) { TLRPC.StickerSetCovered set1 = featuredEmojiPacks.get(i); TLRPC.StickerSet set = set1.set; boolean isPremiumPack = false; boolean foundDuplicate = false; for (int j = 0; j < packs.size(); ++j) { if (packs.get(j).set.id == set.id) { foundDuplicate = true; break; } } if (foundDuplicate) { continue; } ArrayList<TLRPC.Document> documents = null; if (set1 instanceof TLRPC.TL_stickerSetNoCovered) { TLRPC.TL_messages_stickerSet fullSet = mediaDataController.getStickerSet(MediaDataController.getInputStickerSet(set1.set), set1.set.hash, true); if (fullSet != null) { documents = fullSet.documents; isPremiumPack = MessageObject.isPremiumEmojiPack(fullSet); } } else if (set1 instanceof TLRPC.TL_stickerSetFullCovered) { documents = ((TLRPC.TL_stickerSetFullCovered) set1).documents; isPremiumPack = MessageObject.isPremiumEmojiPack(set1); } if (documents == null) { continue; } if ((type == TYPE_SET_REPLY_ICON || type == TYPE_SET_REPLY_ICON_BOTTOM) && (documents.isEmpty() || !MessageObject.isTextColorEmoji(documents.get(0)))) { continue; } if ((type == TYPE_EMOJI_STATUS_CHANNEL_TOP || type == TYPE_EMOJI_STATUS_CHANNEL) && !set.channel_emoji_status) { continue; } positionToSection.put(totalCount, packs.size()); sectionToPosition.put(packs.size(), totalCount); totalCount++; rowHashCodes.add(9211 + 13L * set.id); EmojiView.EmojiPack pack = new EmojiView.EmojiPack(); pack.installed = installedEmojiSets.contains(set.id); pack.featured = true; pack.free = !isPremiumPack; pack.set = set; pack.documents = filter(documents, restricted); pack.index = packs.size(); pack.expanded = expandedEmojiSets.contains(pack.set.id); if (pack.documents.size() > maxlen && !pack.expanded) { totalCount += maxlen; for (int k = 0; k < maxlen - 1; ++k) { rowHashCodes.add(3212 + 13L * pack.documents.get(k).id); } rowHashCodes.add(-5531 + 13L * set.id + 169L * (pack.documents.size() - maxlen + 1)); positionToExpand.put(totalCount - 1, packs.size()); } else { totalCount += pack.documents.size(); for (int k = 0; k < pack.documents.size(); ++k) { rowHashCodes.add(3212 + 13L * pack.documents.get(k).id); } } if (!pack.installed && type != TYPE_AVATAR_CONSTRUCTOR && type != TYPE_SET_REPLY_ICON && type != TYPE_SET_REPLY_ICON_BOTTOM && type != TYPE_CHAT_REACTIONS) { positionToButton.put(totalCount, packs.size()); totalCount++; rowHashCodes.add(3321 + 13L * set.id); } packs.add(pack); } } if (type != TYPE_EXPANDABLE_REACTIONS && type != TYPE_STICKER_SET_EMOJI) { emojiTabs.updateEmojiPacks(packs); } if (animated) { emojiGridView.setItemAnimator(emojiItemAnimator); } else { emojiGridView.setItemAnimator(null); } if (diff) { DiffUtil.calculateDiff(new DiffUtil.Callback() { @Override public int getOldListSize() { return prevRowHashCodes.size(); } @Override public int getNewListSize() { return rowHashCodes.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return prevRowHashCodes.get(oldItemPosition).equals(rowHashCodes.get(newItemPosition)); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return true; } }, false).dispatchUpdatesTo(adapter); } else { adapter.notifyDataSetChanged(); } if (!emojiGridView.scrolledByUserOnce) { emojiGridView.scrollToPosition(0); } } public void notifyDataSetChanged() { if (adapter != null) { adapter.notifyDataSetChanged(); } } public void expand(int position, View expandButton) { int index = positionToExpand.get(position); Integer from = null, count = null; boolean last; int maxlen; int fromCount, start, toCount; animateExpandFromButtonTranslate = 0; if (index >= 0 && index < packs.size()) { maxlen = SPAN_COUNT_FOR_EMOJI * EXPAND_MAX_LINES; EmojiView.EmojiPack pack = packs.get(index); if (pack.expanded) { return; } last = index + 1 == packs.size(); start = sectionToPosition.get(index); expandedEmojiSets.add(pack.set.id); fromCount = pack.expanded ? pack.documents.size() : Math.min(maxlen, pack.documents.size()); if (pack.documents.size() > maxlen) { from = start + 1 + fromCount; } pack.expanded = true; toCount = pack.documents.size(); } else if (index == -1) { maxlen = SPAN_COUNT_FOR_EMOJI * RECENT_MAX_LINES; if (recentExpanded) { return; } last = false; start = (searchRow != -1 ? 1 : 0) + (longtapHintRow != -1 ? 1 : 0) + (includeEmpty ? 1 : 0); fromCount = recentExpanded ? recent.size() : Math.min(maxlen - (includeEmpty ? 1 : 0) - 2, recent.size()); toCount = recent.size(); recentExpanded = true; // animateExpandFromButtonTranslate = AndroidUtilities.dp(8); } else { return; } if (toCount > fromCount) { from = start + 1 + fromCount; count = toCount - fromCount; } updateRows(false, true); if (from != null && count != null) { animateExpandFromButton = expandButton; animateExpandFromPosition = from; animateExpandToPosition = from + count; animateExpandStartTime = SystemClock.elapsedRealtime(); if (last) { final int scrollTo = from; final float durationMultiplier = count > maxlen / 2 ? 1.5f : 3.5f; post(() -> { try { LinearSmoothScrollerCustom linearSmoothScroller = new LinearSmoothScrollerCustom(emojiGridView.getContext(), LinearSmoothScrollerCustom.POSITION_MIDDLE, durationMultiplier); linearSmoothScroller.setTargetPosition(scrollTo); layoutManager.startSmoothScroll(linearSmoothScroller); } catch (Exception e) { FileLog.e(e); } }); } } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (drawBackground && type != TYPE_TOPIC_ICON && type != TYPE_AVATAR_CONSTRUCTOR) { super.onMeasure( MeasureSpec.makeMeasureSpec((int) Math.min(AndroidUtilities.dp(340 - 16), AndroidUtilities.displaySize.x * .95f), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec((int) Math.min(AndroidUtilities.dp(410 - 16 - 64), AndroidUtilities.displaySize.y * .75f), MeasureSpec.AT_MOST) ); } else if (type == TYPE_CHAT_REACTIONS) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec((int) (AndroidUtilities.displaySize.y * .35f), MeasureSpec.AT_MOST)); } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (changed && type == TYPE_CHAT_REACTIONS) { int items = getMeasuredWidth() / AndroidUtilities.dp(42); int spanCount = items * 5; layoutManager.setSpanCount(spanCount); } } private int getCacheType() { // if (type == TYPE_STICKER_SET_EMOJI) { // return AnimatedEmojiDrawable.CACHE_TYPE_ALERT_STANDARD_EMOJI; // } if (type == TYPE_SET_REPLY_ICON || type == TYPE_SET_REPLY_ICON_BOTTOM) { return AnimatedEmojiDrawable.CACHE_TYPE_ALERT_PREVIEW_STATIC; } if (type == TYPE_CHAT_REACTIONS) { return AnimatedEmojiDrawable.getCacheTypeForEnterView(); } if (type == TYPE_TOPIC_ICON || type == TYPE_AVATAR_CONSTRUCTOR) { return AnimatedEmojiDrawable.CACHE_TYPE_ALERT_PREVIEW_STATIC; } return type == TYPE_EMOJI_STATUS || type == TYPE_EMOJI_STATUS_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_EMOJI_STATUS_CHANNEL_TOP || type == TYPE_SET_DEFAULT_REACTION ? AnimatedEmojiDrawable.CACHE_TYPE_KEYBOARD : AnimatedEmojiDrawable.CACHE_TYPE_ALERT_PREVIEW; } public class EmojiListView extends RecyclerListView { public EmojiListView(Context context) { super(context); setDrawSelectorBehind(true); setClipToPadding(false); setSelectorRadius(AndroidUtilities.dp(4)); setSelectorDrawableColor(Theme.getColor(Theme.key_listSelector, resourcesProvider)); } SparseArray<ArrayList<ImageViewEmoji>> viewsGroupedByLines = new SparseArray<>(); ArrayList<ArrayList<ImageViewEmoji>> unusedArrays = new ArrayList<>(); ArrayList<DrawingInBackgroundLine> unusedLineDrawables = new ArrayList<>(); ArrayList<DrawingInBackgroundLine> lineDrawables = new ArrayList<>(); ArrayList<DrawingInBackgroundLine> lineDrawablesTmp = new ArrayList<>(); private boolean invalidated; private LongSparseArray<AnimatedEmojiDrawable> animatedEmojiDrawables = new LongSparseArray<>(); @Override public boolean drawChild(Canvas canvas, View child, long drawingTime) { // if (child instanceof ImageViewEmoji) { // return false; // } return super.drawChild(canvas, child, drawingTime); } @Override protected boolean canHighlightChildAt(View child, float x, float y) { if (child instanceof ImageViewEmoji && (((ImageViewEmoji) child).empty || ((ImageViewEmoji) child).drawable instanceof AnimatedEmojiDrawable && ((AnimatedEmojiDrawable) ((ImageViewEmoji) child).drawable).canOverrideColor())) { setSelectorDrawableColor(ColorUtils.setAlphaComponent(accentColor, 30)); } else { setSelectorDrawableColor(Theme.getColor(Theme.key_listSelector, resourcesProvider)); } return super.canHighlightChildAt(child, x, y); } private int lastChildCount = -1; @Override public void setAlpha(float alpha) { super.setAlpha(alpha); invalidate(); } @Override public void dispatchDraw(Canvas canvas) { if (getVisibility() != View.VISIBLE) { return; } invalidated = false; int restoreTo = canvas.getSaveCount(); if (type != TYPE_CHAT_REACTIONS) { if (!selectorRect.isEmpty()) { selectorDrawable.setBounds(selectorRect); canvas.save(); if (selectorTransformer != null) { selectorTransformer.accept(canvas); } selectorDrawable.draw(canvas); canvas.restore(); } } for (int i = 0; i < viewsGroupedByLines.size(); i++) { ArrayList<ImageViewEmoji> arrayList = viewsGroupedByLines.valueAt(i); arrayList.clear(); unusedArrays.add(arrayList); } viewsGroupedByLines.clear(); final boolean animatedExpandIn = animateExpandStartTime > 0 && (SystemClock.elapsedRealtime() - animateExpandStartTime) < animateExpandDuration(); final boolean drawButton = animatedExpandIn && animateExpandFromButton != null && animateExpandFromPosition >= 0; if (animatedEmojiDrawables != null) { for (int i = 0; i < getChildCount(); ++i) { View child = getChildAt(i); if (child instanceof ImageViewEmoji) { ImageViewEmoji imageViewEmoji = (ImageViewEmoji) child; imageViewEmoji.updatePressedProgress(); int top = smoothScrolling ? (int) child.getY() : child.getTop(); ArrayList<ImageViewEmoji> arrayList = viewsGroupedByLines.get(top); canvas.save(); canvas.translate(imageViewEmoji.getX(), imageViewEmoji.getY()); imageViewEmoji.drawSelected(canvas, this); canvas.restore(); if (imageViewEmoji.getBackground() != null) { imageViewEmoji.getBackground().setBounds((int) imageViewEmoji.getX(), (int) imageViewEmoji.getY(), (int) imageViewEmoji.getX() + imageViewEmoji.getWidth(), (int) imageViewEmoji.getY() + imageViewEmoji.getHeight()); int wasAlpha = 255; // imageViewEmoji.getBackground().getAlpha(); imageViewEmoji.getBackground().setAlpha((int) (wasAlpha * imageViewEmoji.getAlpha())); imageViewEmoji.getBackground().draw(canvas); imageViewEmoji.getBackground().setAlpha(wasAlpha); } if (arrayList == null) { if (!unusedArrays.isEmpty()) { arrayList = unusedArrays.remove(unusedArrays.size() - 1); } else { arrayList = new ArrayList<>(); } viewsGroupedByLines.put(top, arrayList); } arrayList.add(imageViewEmoji); if (imageViewEmoji.premiumLockIconView != null && imageViewEmoji.premiumLockIconView.getVisibility() == View.VISIBLE) { if (imageViewEmoji.premiumLockIconView.getImageReceiver() == null && imageViewEmoji.imageReceiverToDraw != null) { imageViewEmoji.premiumLockIconView.setImageReceiver(imageViewEmoji.imageReceiverToDraw); } } } if (drawButton && child != null) { int position = getChildAdapterPosition(child); if (position == animateExpandFromPosition - (animateExpandFromButtonTranslate > 0 ? 0 : 1)) { float t = CubicBezierInterpolator.EASE_OUT.getInterpolation(MathUtils.clamp((SystemClock.elapsedRealtime() - animateExpandStartTime) / 200f, 0, 1)); if (t < 1) { canvas.saveLayerAlpha(child.getLeft(), child.getTop(), child.getRight(), child.getBottom(), (int) (255 * (1f - t)), Canvas.ALL_SAVE_FLAG); canvas.translate(child.getLeft(), child.getTop() + animateExpandFromButtonTranslate); final float scale = .5f + .5f * (1f - t); canvas.scale(scale, scale, child.getWidth() / 2f, child.getHeight() / 2f); animateExpandFromButton.draw(canvas); canvas.restore(); } } } } } lineDrawablesTmp.clear(); lineDrawablesTmp.addAll(lineDrawables); lineDrawables.clear(); long time = System.currentTimeMillis(); for (int i = 0; i < viewsGroupedByLines.size(); i++) { ArrayList<ImageViewEmoji> arrayList = viewsGroupedByLines.valueAt(i); ImageViewEmoji firstView = arrayList.get(0); int position = getChildAdapterPosition(firstView); DrawingInBackgroundLine drawable = null; for (int k = 0; k < lineDrawablesTmp.size(); k++) { if (lineDrawablesTmp.get(k).position == position) { drawable = lineDrawablesTmp.get(k); lineDrawablesTmp.remove(k); break; } } if (drawable == null) { if (!unusedLineDrawables.isEmpty()) { drawable = unusedLineDrawables.remove(unusedLineDrawables.size() - 1); } else { drawable = new DrawingInBackgroundLine(); drawable.setLayerNum(7); } drawable.position = position; drawable.onAttachToWindow(); } lineDrawables.add(drawable); drawable.imageViewEmojis = arrayList; canvas.save(); canvas.translate(firstView.getLeft(), firstView.getY()/* + firstView.getPaddingTop()*/); drawable.startOffset = firstView.getLeft(); int w = getMeasuredWidth() - firstView.getLeft() * 2; int h = firstView.getMeasuredHeight(); if (w > 0 && h > 0) { drawable.draw(canvas, time, w, h, getAlpha()); } canvas.restore(); } for (int i = 0; i < lineDrawablesTmp.size(); i++) { if (unusedLineDrawables.size() < 3) { unusedLineDrawables.add(lineDrawablesTmp.get(i)); lineDrawablesTmp.get(i).imageViewEmojis = null; lineDrawablesTmp.get(i).reset(); } else { lineDrawablesTmp.get(i).onDetachFromWindow(); } } lineDrawablesTmp.clear(); for (int i = 0; i < getChildCount(); ++i) { View child = getChildAt(i); if (child instanceof ImageViewEmoji) { ImageViewEmoji imageViewEmoji = (ImageViewEmoji) child; if (imageViewEmoji.premiumLockIconView != null && imageViewEmoji.premiumLockIconView.getVisibility() == View.VISIBLE) { canvas.save(); canvas.translate( (int) (imageViewEmoji.getX() + imageViewEmoji.getMeasuredWidth() - imageViewEmoji.premiumLockIconView.getMeasuredWidth()), (int) (imageViewEmoji.getY() + imageViewEmoji.getMeasuredHeight() - imageViewEmoji.premiumLockIconView.getMeasuredHeight()) ); imageViewEmoji.premiumLockIconView.draw(canvas); canvas.restore(); } } else if (child != null && child != animateExpandFromButton) { canvas.save(); canvas.translate((int) child.getX(), (int) child.getY()); child.draw(canvas); canvas.restore(); } } canvas.restoreToCount(restoreTo); HwEmojis.exec(); } public class DrawingInBackgroundLine extends DrawingInBackgroundThreadDrawable { public int position; public int startOffset; ArrayList<ImageViewEmoji> imageViewEmojis; ArrayList<ImageViewEmoji> drawInBackgroundViews = new ArrayList<>(); float skewAlpha = 1f; boolean skewBelow = false; boolean lite = LiteMode.isEnabled(LiteMode.FLAG_ANIMATED_EMOJI_REACTIONS); @Override public void draw(Canvas canvas, long time, int w, int h, float alpha) { if (imageViewEmojis == null) { return; } skewAlpha = 1f; skewBelow = false; if (!imageViewEmojis.isEmpty()) { View firstView = imageViewEmojis.get(0); if (firstView.getY() > getHeight() - getPaddingBottom() - firstView.getHeight()) { skewAlpha = MathUtils.clamp(-(firstView.getY() - getHeight() + getPaddingBottom()) / firstView.getHeight(), 0, 1); skewAlpha = .25f + .75f * skewAlpha; } } boolean drawInUi = type == TYPE_STICKER_SET_EMOJI || skewAlpha < 1 || isAnimating() || imageViewEmojis.size() <= 4 || !lite || enterAnimationInProgress() || type == TYPE_AVATAR_CONSTRUCTOR || type == TYPE_CHAT_REACTIONS; if (!drawInUi) { boolean animatedExpandIn = animateExpandStartTime > 0 && (SystemClock.elapsedRealtime() - animateExpandStartTime) < animateExpandDuration(); for (int i = 0; i < imageViewEmojis.size(); i++) { ImageViewEmoji img = imageViewEmojis.get(i); if (img.pressedProgress != 0 || img.backAnimator != null || img.getTranslationX() != 0 || img.getTranslationY() != 0 || img.getAlpha() != 1 || (animatedExpandIn && img.position > animateExpandFromPosition && img.position < animateExpandToPosition) || img.isStaticIcon) { drawInUi = true; break; } } } if (HwEmojis.isHwEnabled()) { alpha = 1f; } if (drawInUi || HwEmojis.isPreparing()) { prepareDraw(System.currentTimeMillis()); drawInUiThread(canvas, alpha); reset(); } else { super.draw(canvas, time, w, h, alpha); } } // float[] verts = new float[16]; @Override public void drawBitmap(Canvas canvas, Bitmap bitmap, Paint paint) { // if (skewAlpha < 1) { // final float w = bitmap.getWidth(); // final float h = bitmap.getHeight(); // final float skew = .85f + .15f * skewAlpha; ///* // verts[0] = hw + w * (0 - .5f) * (skewBelow ? skew : 1f); // x // verts[2] = hw + w * (0.33f - .5f) * (skewBelow ? skew : 1f); // x // verts[4] = hw + w * (0.66f - .5f) * (skewBelow ? skew : 1f); // x // verts[6] = hw + w * (1 - .5f) * (skewBelow ? skew : 1f); // x // verts[1] = verts[3] = verts[5] = verts[7] = (skewBelow ? 1f - skewAlpha : 0) * h; // y // // verts[8] = hw + w * (0 - .5f) * (skewBelow ? 1f : skew); // x // verts[10] = hw + w * (0.33f - .5f) * (skewBelow ? 1f : skew); // x // verts[12] = hw + w * (0.66f - .5f) * (skewBelow ? 1f : skew); // x // verts[14] = hw + w * (1 - .5f) * (skewBelow ? 1f : skew); // x // verts[9] = verts[11] = verts[13] = verts[15] = (skewBelow ? 1f : skewAlpha) * h; // y // */ // verts[0] = (skewBelow ? w * (.5f - .5f * skew) : 0); // verts[2] = w * (skewBelow ? (.5f - .166667f * skew) : .333333f); // verts[4] = w * (skewBelow ? (.5f + .166667f * skew) : .666666f); // verts[6] = (skewBelow ? w * (.5f + .5f * skew) : w); // verts[1] = verts[3] = verts[5] = verts[7] = (skewBelow ? h * (1f - skewAlpha) : 0); // y // // verts[8] = (skewBelow ? 0 : w * (.5f - .5f * skew)); // verts[10] = w * (skewBelow ? .333333f : (.5f - .166667f * skew)); // verts[12] = w * (skewBelow ? .666666f : (.5f + .166667f * skew)); // verts[14] = (skewBelow ? w : w * (.5f + .5f * skew)); // verts[9] = verts[11] = verts[13] = verts[15] = (skewBelow ? h : h * skewAlpha); // y // // canvas.drawBitmapMesh(bitmap, 3, 1, verts, 0, null, 0, paint); // } else { canvas.drawBitmap(bitmap, 0, 0, paint); // } } @Override public void prepareDraw(long time) { drawInBackgroundViews.clear(); for (int i = 0; i < imageViewEmojis.size(); i++) { ImageViewEmoji imageView = imageViewEmojis.get(i); if (imageView.notDraw) { continue; } ImageReceiver imageReceiver; if (imageView.empty) { Drawable drawable = getPremiumStar(); float scale = type == TYPE_SET_REPLY_ICON || type == TYPE_EMOJI_STATUS_CHANNEL_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_SET_REPLY_ICON_BOTTOM ? 1.3f : 1f; if (imageView.pressedProgress != 0 || imageView.selected) { scale *= 0.8f + 0.2f * (1f - (imageView.selected ? .7f : imageView.pressedProgress)); } if (drawable == null) { continue; } drawable.setAlpha(255); int topOffset = 0; // (int) (imageView.getHeight() * .03f); int w = imageView.getWidth() - imageView.getPaddingLeft() - imageView.getPaddingRight(); int h = imageView.getHeight() - imageView.getPaddingTop() - imageView.getPaddingBottom(); AndroidUtilities.rectTmp2.set( (int) (imageView.getWidth() / 2f - w / 2f * imageView.getScaleX() * scale), (int) (imageView.getHeight() / 2f - h / 2f * imageView.getScaleY() * scale), (int) (imageView.getWidth() / 2f + w / 2f * imageView.getScaleX() * scale), (int) (imageView.getHeight() / 2f + h / 2f * imageView.getScaleY() * scale) ); AndroidUtilities.rectTmp2.offset(imageView.getLeft() - startOffset, topOffset); if (imageView.drawableBounds == null) { imageView.drawableBounds = new Rect(); } imageView.drawableBounds.set(AndroidUtilities.rectTmp2); imageView.setDrawable(drawable); drawInBackgroundViews.add(imageView); } else { float scale = 1, alpha = 1; if (imageView.pressedProgress != 0 || imageView.selected) { scale *= 0.8f + 0.2f * (1f - (imageView.selected ? .7f : imageView.pressedProgress)); } boolean animatedExpandIn = animateExpandStartTime > 0 && (SystemClock.elapsedRealtime() - animateExpandStartTime) < animateExpandDuration(); if (animatedExpandIn && animateExpandFromPosition >= 0 && animateExpandToPosition >= 0 && animateExpandStartTime > 0) { int position = getChildAdapterPosition(imageView); final int pos = position - animateExpandFromPosition; final int count = animateExpandToPosition - animateExpandFromPosition; if (pos >= 0 && pos < count) { final float appearDuration = animateExpandAppearDuration(); final float AppearT = (MathUtils.clamp((SystemClock.elapsedRealtime() - animateExpandStartTime) / appearDuration, 0, 1)); final float alphaT = AndroidUtilities.cascade(AppearT, pos, count, count / 4f); final float scaleT = AndroidUtilities.cascade(AppearT, pos, count, count / 4f); scale *= .5f + appearScaleInterpolator.getInterpolation(scaleT) * .5f; alpha *= alphaT; } } else { alpha *= imageView.getAlpha(); } if (!imageView.isDefaultReaction && !imageView.isStaticIcon) { AnimatedEmojiSpan span = imageView.span; if (span == null) { continue; } AnimatedEmojiDrawable drawable = null; if (imageView.drawable instanceof AnimatedEmojiDrawable) { drawable = (AnimatedEmojiDrawable) imageView.drawable; } if (drawable == null || drawable.getImageReceiver() == null) { continue; } imageReceiver = drawable.getImageReceiver(); drawable.setAlpha((int) (255 * alpha)); imageView.setDrawable(drawable); imageView.drawable.setColorFilter(premiumStarColorFilter); } else { imageReceiver = imageView.imageReceiver; imageReceiver.setAlpha(alpha); } if (imageReceiver == null) { continue; } if (imageView.selected) { imageReceiver.setRoundRadius(AndroidUtilities.dp(4)); } else { imageReceiver.setRoundRadius(0); } imageView.backgroundThreadDrawHolder[threadIndex] = imageReceiver.setDrawInBackgroundThread(imageView.backgroundThreadDrawHolder[threadIndex], threadIndex); imageView.backgroundThreadDrawHolder[threadIndex].time = time; imageView.imageReceiverToDraw = imageReceiver; imageView.update(time); int topOffset = 0; // (int) (imageView.getHeight() * .03f); int w = imageView.getWidth() - imageView.getPaddingLeft() - imageView.getPaddingRight(); int h = imageView.getHeight() - imageView.getPaddingTop() - imageView.getPaddingBottom(); AndroidUtilities.rectTmp2.set(imageView.getPaddingLeft(), imageView.getPaddingTop(), imageView.getWidth() - imageView.getPaddingRight(), imageView.getHeight() - imageView.getPaddingBottom()); if (imageView.selected && type != TYPE_TOPIC_ICON && type != TYPE_AVATAR_CONSTRUCTOR) { AndroidUtilities.rectTmp2.set( (int) Math.round(AndroidUtilities.rectTmp2.centerX() - AndroidUtilities.rectTmp2.width() / 2f * 0.86f), (int) Math.round(AndroidUtilities.rectTmp2.centerY() - AndroidUtilities.rectTmp2.height() / 2f * 0.86f), (int) Math.round(AndroidUtilities.rectTmp2.centerX() + AndroidUtilities.rectTmp2.width() / 2f * 0.86f), (int) Math.round(AndroidUtilities.rectTmp2.centerY() + AndroidUtilities.rectTmp2.height() / 2f * 0.86f) ); } AndroidUtilities.rectTmp2.offset(imageView.getLeft() + (int) imageView.getTranslationX() - startOffset, topOffset); imageView.backgroundThreadDrawHolder[threadIndex].setBounds(AndroidUtilities.rectTmp2); imageView.skewAlpha = 1f; imageView.skewIndex = i; drawInBackgroundViews.add(imageView); } } } @Override public void drawInBackground(Canvas canvas) { for (int i = 0; i < drawInBackgroundViews.size(); i++) { ImageViewEmoji imageView = drawInBackgroundViews.get(i); if (!imageView.notDraw) { if (imageView.empty) { imageView.drawable.setBounds(imageView.drawableBounds); imageView.drawable.draw(canvas); } else if (imageView.imageReceiverToDraw != null) { // imageView.drawable.setColorFilter(premiumStarColorFilter); imageView.imageReceiverToDraw.draw(canvas, imageView.backgroundThreadDrawHolder[threadIndex]); } } } } private OvershootInterpolator appearScaleInterpolator = new OvershootInterpolator(3f); @Override protected void drawInUiThread(Canvas canvas, float alpha) { if (imageViewEmojis != null) { canvas.save(); canvas.translate(-startOffset, 0); for (int i = 0; i < imageViewEmojis.size(); i++) { ImageViewEmoji imageView = imageViewEmojis.get(i); if (imageView.notDraw) { continue; } float scale = imageView.getScaleX(); if (type == TYPE_STICKER_SET_EMOJI) { scale *= .87f; } if (imageView.pressedProgress != 0 || imageView.selected) { scale *= 0.8f + 0.2f * (1f - ((imageView.selected && type != TYPE_TOPIC_ICON && type != TYPE_AVATAR_CONSTRUCTOR) ? 0.7f : imageView.pressedProgress)); } boolean animatedExpandIn = animateExpandStartTime > 0 && (SystemClock.elapsedRealtime() - animateExpandStartTime) < animateExpandDuration(); boolean animatedExpandInLocal = animatedExpandIn && animateExpandFromPosition >= 0 && animateExpandToPosition >= 0 && animateExpandStartTime > 0; if (animatedExpandInLocal) { int position = getChildAdapterPosition(imageView); final int pos = position - animateExpandFromPosition; final int count = animateExpandToPosition - animateExpandFromPosition; if (pos >= 0 && pos < count) { final float appearDuration = animateExpandAppearDuration(); final float AppearT = (MathUtils.clamp((SystemClock.elapsedRealtime() - animateExpandStartTime) / appearDuration, 0, 1)); final float alphaT = AndroidUtilities.cascade(AppearT, pos, count, count / 4f); final float scaleT = AndroidUtilities.cascade(AppearT, pos, count, count / 4f); scale *= .5f + appearScaleInterpolator.getInterpolation(scaleT) * .5f; alpha = alphaT; } } else { alpha *= imageView.getAlpha(); } AndroidUtilities.rectTmp2.set((int) imageView.getX() + imageView.getPaddingLeft(), imageView.getPaddingTop(), (int) imageView.getX() + imageView.getWidth() - imageView.getPaddingRight(), imageView.getHeight() - imageView.getPaddingBottom()); if (!smoothScrolling && !animatedExpandIn) { AndroidUtilities.rectTmp2.offset(0, (int) imageView.getTranslationY()); } Drawable drawable = null; if (imageView.empty) { drawable = getPremiumStar(); if (type == TYPE_SET_REPLY_ICON || type == TYPE_EMOJI_STATUS_CHANNEL_TOP || type == TYPE_EMOJI_STATUS_CHANNEL || type == TYPE_SET_REPLY_ICON_BOTTOM) { AndroidUtilities.rectTmp2.inset((int) (-AndroidUtilities.rectTmp2.width() * .15f), (int) (-AndroidUtilities.rectTmp2.height() * .15f)); } drawable.setBounds(AndroidUtilities.rectTmp2); drawable.setAlpha(255); } else if (!imageView.isDefaultReaction && !imageView.isStaticIcon) { AnimatedEmojiSpan span = imageView.span; if (span == null && type != TYPE_STICKER_SET_EMOJI || imageView.notDraw) { continue; } drawable = imageView.drawable; if (drawable == null) { continue; } drawable.setAlpha(255); drawable.setBounds(AndroidUtilities.rectTmp2); } else if (imageView.imageReceiver != null) { imageView.imageReceiver.setImageCoords(AndroidUtilities.rectTmp2); } if (premiumStarColorFilter != null && imageView.drawable instanceof AnimatedEmojiDrawable) { imageView.drawable.setColorFilter(premiumStarColorFilter); } imageView.skewAlpha = skewAlpha; imageView.skewIndex = i; if (scale != 1 || skewAlpha < 1) { canvas.save(); if (imageView.selected && type != TYPE_TOPIC_ICON && type != TYPE_AVATAR_CONSTRUCTOR && type != TYPE_CHAT_REACTIONS) { //scale here only selected emoji canvas.scale(0.85f, 0.85f, AndroidUtilities.rectTmp2.centerX(), AndroidUtilities.rectTmp2.centerY()); } if (type == TYPE_CHAT_REACTIONS || type == TYPE_STICKER_SET_EMOJI) { canvas.scale(scale, scale, AndroidUtilities.rectTmp2.centerX(), AndroidUtilities.rectTmp2.centerY()); } else { skew(canvas, i, imageView.getHeight()); } drawImage(canvas, drawable, imageView, alpha); canvas.restore(); } else { drawImage(canvas, drawable, imageView, alpha); } } canvas.restore(); } } private void skew(Canvas canvas, int i, int h) { if (skewAlpha < 1) { if (skewBelow) { canvas.translate(0, h); canvas.skew((1f - 2f * i / imageViewEmojis.size()) * -(1f - skewAlpha), 0); canvas.translate(0, -h); } else { canvas.scale(1f, skewAlpha, 0, 0); canvas.skew((1f - 2f * i / imageViewEmojis.size()) * (1f - skewAlpha), 0); } } } private void drawImage(Canvas canvas, Drawable drawable, ImageViewEmoji imageView, float alpha) { if (drawable != null) { drawable.setAlpha((int) (255 * alpha)); drawable.draw(canvas); drawable.setColorFilter(premiumStarColorFilter); } else if ((imageView.isDefaultReaction || imageView.isStaticIcon) && imageView.imageReceiver != null) { canvas.save(); canvas.clipRect(imageView.imageReceiver.getImageX(), imageView.imageReceiver.getImageY(), imageView.imageReceiver.getImageX2(), imageView.imageReceiver.getImageY2()); imageView.imageReceiver.setAlpha(alpha); imageView.imageReceiver.draw(canvas); canvas.restore(); } } @Override public void onFrameReady() { super.onFrameReady(); for (int i = 0; i < drawInBackgroundViews.size(); i++) { ImageViewEmoji imageView = drawInBackgroundViews.get(i); if (imageView.backgroundThreadDrawHolder[threadIndex] != null) { imageView.backgroundThreadDrawHolder[threadIndex].release(); } } emojiGridView.invalidate(); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (this == emojiGridView) { bigReactionImageReceiver.onAttachedToWindow(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (this == emojiGridView) { bigReactionImageReceiver.onDetachedFromWindow(); } release(unusedLineDrawables); release(lineDrawables); release(lineDrawablesTmp); } private void release(ArrayList<DrawingInBackgroundLine> lineDrawables) { for (int i = 0; i < lineDrawables.size(); i++) { lineDrawables.get(i).onDetachFromWindow(); } lineDrawables.clear(); } @Override public void invalidateViews() { if (HwEmojis.grab(this)) { return; } super.invalidateViews(); } @Override public void invalidate() { if (HwEmojis.grab(this)) { return; } if (invalidated) { return; } invalidated = true; super.invalidate(); } @Override public void invalidate(int l, int t, int r, int b) { if (HwEmojis.grab(this)) { return; } super.invalidate(l, t, r, b); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); isAttached = true; NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.featuredEmojiDidLoad); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.stickersDidLoad); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.recentEmojiStatusesUpdate); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.groupStickersDidLoad); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded); if (scrimDrawable != null) { scrimDrawable.setSecondParent(this); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); setBigReactionAnimatedEmoji(null); isAttached = false; NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.featuredEmojiDidLoad); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.stickersDidLoad); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.recentEmojiStatusesUpdate); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.groupStickersDidLoad); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.emojiLoaded); if (scrimDrawable != null) { scrimDrawable.setSecondParent(null); } } private final Runnable updateRows = () -> updateRows(true, true); private final Runnable updateRowsDelayed = () -> { NotificationCenter.getGlobalInstance().removeDelayed(updateRows); NotificationCenter.getGlobalInstance().doOnIdle(updateRows); }; private void updateRowsDelayed() { AndroidUtilities.cancelRunOnUIThread(updateRowsDelayed); AndroidUtilities.runOnUIThread(updateRowsDelayed); } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.stickersDidLoad) { if (((int) args[0]) == MediaDataController.TYPE_EMOJIPACKS || (((int) args[0]) == MediaDataController.TYPE_IMAGE && showStickers)) { updateRowsDelayed(); } } else if (id == NotificationCenter.featuredEmojiDidLoad) { updateRowsDelayed(); } else if (id == NotificationCenter.recentEmojiStatusesUpdate) { updateRowsDelayed(); } else if (id == NotificationCenter.groupStickersDidLoad) { updateRowsDelayed(); } else if (id == NotificationCenter.emojiLoaded) { AndroidUtilities.forEachViews(emojiGridView, View::invalidate); if (emojiGridView != null) { emojiGridView.invalidate(); } } } private static boolean isFirstOpen = true; private Runnable dismiss; final float durationScale = 1f; final long showDuration = (long) (800 * durationScale); private ValueAnimator showAnimator; private ValueAnimator hideAnimator; private AnimationNotificationsLocker notificationsLocker = new AnimationNotificationsLocker(); private boolean isAnimatedShow() { return type != TYPE_TOPIC_ICON && type != TYPE_AVATAR_CONSTRUCTOR && type != TYPE_CHAT_REACTIONS; } public void onShow(Runnable dismiss) { if (listStateId != null) { Parcelable state = listStates.get(listStateId); if (state != null) { // layoutManager.onRestoreInstanceState(state); // updateTabsPosition(layoutManager.findFirstCompletelyVisibleItemPosition()); } } this.dismiss = dismiss; if (!drawBackground) { checkScroll(); for (int i = 0; i < emojiGridView.getChildCount(); ++i) { View child = emojiGridView.getChildAt(i); child.setScaleX(1); child.setScaleY(1); } return; } if (showAnimator != null) { showAnimator.cancel(); showAnimator = null; } if (hideAnimator != null) { hideAnimator.cancel(); hideAnimator = null; } boolean animated = isAnimatedShow(); if (animated) { showAnimator = ValueAnimator.ofFloat(0f, 1f); showAnimator.addUpdateListener(anm -> { updateShow((float) anm.getAnimatedValue()); }); showAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { HwEmojis.disableHw(); emojiGridView.setLayerType(LAYER_TYPE_NONE, null); searchBox.setLayerType(LAYER_TYPE_NONE, null); emojiTabsShadow.setLayerType(LAYER_TYPE_NONE, null); backgroundView.setLayerType(LAYER_TYPE_NONE, null); if (bubble2View != null) { bubble2View.setLayerType(LAYER_TYPE_NONE, null); } if (bubble1View != null) { bubble1View.setLayerType(LAYER_TYPE_NONE, null); } searchBox.checkInitialization(); emojiTabs.showRecentTabStub(false); NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.startAllHeavyOperations, 512); notificationsLocker.unlock(); AndroidUtilities.runOnUIThread(NotificationCenter.getGlobalInstance()::runDelayedNotifications); checkScroll(); updateShow(1); for (int i = 0; i < emojiGridView.getChildCount(); ++i) { View child = emojiGridView.getChildAt(i); child.setScaleX(1); child.setScaleY(1); } for (int i = 0; i < emojiTabs.contentView.getChildCount(); ++i) { View child = emojiTabs.contentView.getChildAt(i); child.setScaleX(1); child.setScaleY(1); } emojiTabs.contentView.invalidate(); emojiGridViewContainer.invalidate(); emojiGridView.invalidate(); } }); if (isFirstOpen && type != TYPE_SET_REPLY_ICON && type != TYPE_EMOJI_STATUS_CHANNEL_TOP && type != TYPE_SET_REPLY_ICON_BOTTOM) { isFirstOpen = false; AnimatedEmojiDrawable.getDocumentFetcher(currentAccount).setUiDbCallback(() -> { HwEmojis.enableHw(); AndroidUtilities.runOnUIThread(() -> showAnimator.start(), 0); }); HwEmojis.prepare(null, true); } else { Runnable action = () -> { HwEmojis.enableHw(); AndroidUtilities.runOnUIThread(() -> showAnimator.start(), 0); }; HwEmojis.prepare(action, true); } NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.stopAllHeavyOperations, 512); notificationsLocker.lock(); showAnimator.setDuration(showDuration); emojiGridView.setLayerType(LAYER_TYPE_HARDWARE, null); searchBox.setLayerType(LAYER_TYPE_HARDWARE, null); emojiTabsShadow.setLayerType(LAYER_TYPE_HARDWARE, null); backgroundView.setLayerType(LAYER_TYPE_HARDWARE, null); if (bubble2View != null) { bubble2View.setLayerType(LAYER_TYPE_HARDWARE, null); } if (bubble1View != null) { bubble1View.setLayerType(LAYER_TYPE_HARDWARE, null); } emojiTabs.showRecentTabStub(true); updateShow(0); } else { checkScroll(); updateShow(1); } } public class SearchBox extends FrameLayout { private FrameLayout box; private ImageView search; private ImageView clear; private FrameLayout inputBox; private View inputBoxGradient; private SearchStateDrawable searchStateDrawable; private EditTextCaption input; private StickerCategoriesListView categoriesListView; private float inputBoxGradientAlpha; private ValueAnimator inputBoxGradientAnimator; public SearchBox(Context context, boolean drawBackground) { super(context); setClickable(true); box = new FrameLayout(context); if (drawBackground) { setBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground, resourcesProvider)); } box.setBackground(Theme.createRoundRectDrawable(dp(18), Theme.getColor(Theme.key_chat_emojiPanelBackground, resourcesProvider))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { box.setClipToOutline(true); box.setOutlineProvider(new ViewOutlineProvider() { @Override public void getOutline(View view, Outline outline) { outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), (int) dp(18)); } }); } addView(box, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.TOP | Gravity.FILL_HORIZONTAL, 8, 8 + 4, 8, 8)); search = new ImageView(context); search.setScaleType(ImageView.ScaleType.CENTER); searchStateDrawable = new SearchStateDrawable(); searchStateDrawable.setIconState(SearchStateDrawable.State.STATE_SEARCH, false); searchStateDrawable.setColor(Theme.getColor(Theme.key_chat_emojiSearchIcon, resourcesProvider)); search.setImageDrawable(searchStateDrawable); search.setOnClickListener(e -> { if (searchStateDrawable.getIconState() == SearchStateDrawable.State.STATE_BACK) { input.setText(""); search(null, true, false); if (categoriesListView != null) { categoriesListView.selectCategory(null); categoriesListView.updateCategoriesShown(true, true); categoriesListView.scrollToStart(); } input.clearAnimation(); input.animate().translationX(0).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).start(); showInputBoxGradient(false); } }); box.addView(search, LayoutHelper.createFrame(36, 36, Gravity.LEFT | Gravity.TOP)); inputBox = new FrameLayout(context) { Paint fadePaint; @Override protected void dispatchDraw(Canvas canvas) { if (!drawBackground && inputBoxGradientAlpha > 0) { if (fadePaint == null) { fadePaint = new Paint(); fadePaint.setShader(new LinearGradient(0, 0, AndroidUtilities.dp(18), 0, new int[]{0xffffffff, 0}, new float[]{0f, 1f}, Shader.TileMode.CLAMP)); fadePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); } canvas.saveLayerAlpha(0, 0, getMeasuredWidth(), getMeasuredHeight(), 255, Canvas.ALL_SAVE_FLAG); super.dispatchDraw(canvas); fadePaint.setAlpha((int) (inputBoxGradientAlpha * 255)); canvas.drawRect(0, 0, AndroidUtilities.dp(18), getMeasuredHeight(), fadePaint); canvas.restore(); } else { super.dispatchDraw(canvas); } } }; box.addView(inputBox, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.FILL, 36, 0, 0, 0)); input = new EditTextCaption(context, resourcesProvider) { @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP && prevWindowKeyboardVisible()) { AndroidUtilities.runOnUIThread(() -> { requestFocus(); }, 200); return false; } return super.onTouchEvent(event); } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { if (focused) { onInputFocus(); AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.showKeyboard(input); }, 200); } super.onFocusChanged(focused, direction, previouslyFocusedRect); } @Override public void invalidate() { if (HwEmojis.isHwEnabled()) { return; } super.invalidate(); } }; input.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { final String query = input.getText() == null || AndroidUtilities.trim(input.getText(), null).length() == 0 ? null : input.getText().toString(); search(query); if (categoriesListView != null) { categoriesListView.selectCategory(null); categoriesListView.updateCategoriesShown(TextUtils.isEmpty(query), true); } if (input != null) { input.clearAnimation(); input.animate().translationX(0).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).start(); } showInputBoxGradient(false); } }); input.setBackground(null); input.setPadding(0, 0, AndroidUtilities.dp(4), 0); input.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); input.setHint(LocaleController.getString("Search", R.string.Search)); input.setHintTextColor(Theme.getColor(Theme.key_chat_emojiSearchIcon, resourcesProvider)); input.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider)); input.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI); input.setCursorColor(Theme.getColor(Theme.key_featuredStickers_addedIcon, resourcesProvider)); input.setCursorSize(dp(20)); input.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); input.setCursorWidth(1.5f); input.setMaxLines(1); input.setSingleLine(true); input.setLines(1); input.setTranslationY(AndroidUtilities.dp(-1)); inputBox.addView(input, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.FILL, 0, 0, 32, 0)); if (drawBackground) { inputBoxGradient = new View(context); Drawable gradientDrawable = context.getResources().getDrawable(R.drawable.gradient_right).mutate(); gradientDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelBackground, resourcesProvider), PorterDuff.Mode.MULTIPLY)); inputBoxGradient.setBackground(gradientDrawable); inputBoxGradient.setAlpha(0f); inputBox.addView(inputBoxGradient, LayoutHelper.createFrame(18, LayoutHelper.MATCH_PARENT, Gravity.LEFT)); } setOnClickListener(e -> { if (prevWindowKeyboardVisible()) { return; } onInputFocus(); input.requestFocus(); scrollToPosition(0, 0); }); clear = new ImageView(context); clear.setScaleType(ImageView.ScaleType.CENTER); clear.setImageDrawable(new CloseProgressDrawable2(1.25f) { { setSide(AndroidUtilities.dp(7)); } @Override protected int getCurrentColor() { return Theme.getColor(Theme.key_chat_emojiSearchIcon, resourcesProvider); } }); clear.setBackground(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector, resourcesProvider), Theme.RIPPLE_MASK_CIRCLE_20DP, AndroidUtilities.dp(15))); clear.setAlpha(0f); clear.setOnClickListener(e -> { input.setText(""); search(null, true, false); if (categoriesListView != null) { categoriesListView.selectCategory(null); categoriesListView.updateCategoriesShown(true, true); } input.clearAnimation(); input.animate().translationX(0).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).start(); showInputBoxGradient(false); }); box.addView(clear, LayoutHelper.createFrame(36, 36, Gravity.RIGHT | Gravity.TOP)); if (!HwEmojis.isFirstOpen()) { createCategoriesListView(); } } public void checkInitialization() { createCategoriesListView(); } private void createCategoriesListView() { if (categoriesListView != null || getContext() == null) { return; } if (type != TYPE_REACTIONS && type != TYPE_TAGS && type != TYPE_SET_DEFAULT_REACTION && type != TYPE_EMOJI_STATUS && type != TYPE_EMOJI_STATUS_TOP && type != TYPE_AVATAR_CONSTRUCTOR && type != TYPE_EMOJI_STATUS_CHANNEL_TOP && type != TYPE_EMOJI_STATUS_CHANNEL) { return; } int categoriesType; switch (type) { case TYPE_EMOJI_STATUS: case TYPE_EMOJI_STATUS_TOP: categoriesType = StickerCategoriesListView.CategoriesType.STATUS; break; case TYPE_AVATAR_CONSTRUCTOR: categoriesType = StickerCategoriesListView.CategoriesType.PROFILE_PHOTOS; break; case TYPE_REACTIONS: case TYPE_TAGS: default: categoriesType = StickerCategoriesListView.CategoriesType.DEFAULT; break; } categoriesListView = new StickerCategoriesListView(getContext(), categoriesType, resourcesProvider) { @Override public void selectCategory(int categoryIndex) { super.selectCategory(categoryIndex); updateButton(); } @Override protected boolean isTabIconsAnimationEnabled(boolean loaded) { return LiteMode.isEnabled(LiteMode.FLAG_ANIMATED_EMOJI_KEYBOARD) || type == TYPE_AVATAR_CONSTRUCTOR; } }; categoriesListView.setShownButtonsAtStart(type == TYPE_AVATAR_CONSTRUCTOR ? 6.5f : 4.5f); categoriesListView.setDontOccupyWidth((int) (input.getPaint().measureText(input.getHint() + ""))); categoriesListView.setOnScrollIntoOccupiedWidth(scrolled -> { input.setTranslationX(-Math.max(0, scrolled)); showInputBoxGradient(scrolled > 0); updateButton(); }); categoriesListView.setOnCategoryClick(category -> { if (categoriesListView.getSelectedCategory() == category) { search(null, false, false); categoriesListView.selectCategory(null); } else { search(category.emojis, false, false); categoriesListView.selectCategory(category); } }); box.addView(categoriesListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.FILL, 36, 0, 0, 0)); } private Runnable delayedToggle; private void toggleClear(boolean enabled) { if (enabled) { if (delayedToggle == null) { AndroidUtilities.runOnUIThread(delayedToggle = () -> { AndroidUtilities.updateViewShow(clear, true); }, 340); } } else { if (delayedToggle != null) { AndroidUtilities.cancelRunOnUIThread(delayedToggle); delayedToggle = null; } AndroidUtilities.updateViewShow(clear, false); } } private boolean inputBoxShown = false; private void showInputBoxGradient(boolean show) { if (show == inputBoxShown) { return; } inputBoxShown = show; if (inputBoxGradientAnimator != null) { inputBoxGradientAnimator.cancel(); } inputBoxGradientAnimator = ValueAnimator.ofFloat(inputBoxGradientAlpha, show ? 1f : 0); inputBoxGradientAnimator.addUpdateListener(animation -> { inputBoxGradientAlpha = (float) animation.getAnimatedValue(); if (inputBoxGradient != null) { inputBoxGradient.setAlpha(inputBoxGradientAlpha); } else if (inputBox != null) { inputBox.invalidate(); } }); inputBoxGradientAnimator.setDuration(120); inputBoxGradientAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); inputBoxGradientAnimator.start(); } public boolean isInProgress() { return searchStateDrawable.getIconState() == SearchStateDrawable.State.STATE_PROGRESS; } public void showProgress(boolean progress) { if (progress) { searchStateDrawable.setIconState(SearchStateDrawable.State.STATE_PROGRESS); } else { updateButton(true); } } private void updateButton() { updateButton(false); } private void updateButton(boolean force) { if (!isInProgress() || input.length() == 0 && (categoriesListView == null || categoriesListView.getSelectedCategory() == null) || force) { boolean backButton = input.length() > 0 || categoriesListView != null && categoriesListView.isCategoriesShown() && (categoriesListView.isScrolledIntoOccupiedWidth() || categoriesListView.getSelectedCategory() != null); searchStateDrawable.setIconState(backButton ? SearchStateDrawable.State.STATE_BACK : SearchStateDrawable.State.STATE_SEARCH); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(8 + 36 + 8), MeasureSpec.EXACTLY)); } @Override public void invalidate() { if (HwEmojis.grab(this)) { return; } super.invalidate(); } } protected void onInputFocus() { } private void updateShow(float t) { if (bubble1View != null) { float bubble1t = MathUtils.clamp((t * showDuration - 0) / 120 / durationScale, 0, 1); bubble1t = CubicBezierInterpolator.EASE_OUT.getInterpolation(bubble1t); bubble1View.setAlpha(bubble1t); bubble1View.setScaleX(bubble1t); bubble1View.setScaleY(bubble1t * (isBottom() ? -1 : 1)); } if (bubble2View != null) { float bubble2t = MathUtils.clamp((t * showDuration - 30) / 120 / durationScale, 0, 1); // bubble2t = CubicBezierInterpolator.EASE_OUT.getInterpolation(bubble2t); bubble2View.setAlpha(bubble2t); bubble2View.setScaleX(bubble2t); bubble2View.setScaleY(bubble2t * (isBottom() ? -1 : 1)); } float containerx = MathUtils.clamp((t * showDuration - 40) / 700, 0, 1); float containery = MathUtils.clamp((t * showDuration - 80) / 700, 0, 1); float containeritemst = MathUtils.clamp((t * showDuration - 40) / 750, 0, 1); float containeralphat = MathUtils.clamp((t * showDuration - 30) / 120, 0, 1); containerx = CubicBezierInterpolator.EASE_OUT_QUINT.getInterpolation(containerx); containery = CubicBezierInterpolator.EASE_OUT_QUINT.getInterpolation(containery); // containeritemst = endslow.getInterpolation(containeritemst); // containeralphat = CubicBezierInterpolator.EASE_OUT.getInterpolation(containeralphat); backgroundView.setAlpha(containeralphat); searchBox.setAlpha(containeralphat); for (int i = 0; i < emojiTabs.contentView.getChildCount(); i++) { View child = emojiTabs.contentView.getChildAt(i); child.setAlpha(containeralphat); } if (scrimDrawable != null) { invalidate(); } contentView.setTranslationY(dp(-5) * (1f - containeralphat)); if (bubble2View != null) { bubble2View.setTranslationY(dp(-5) * (1f - containeralphat)); } this.scaleX = .15f + .85f * containerx; this.scaleY = .075f + .925f * containery; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { contentView.invalidateOutline(); } else { backgroundView.setVisibility(GONE); contentView.setAlpha(containeralphat); contentView.invalidate(); } if (bubble2View != null) { bubble2View.setAlpha(containeralphat); } emojiTabsShadow.setAlpha(containeralphat); emojiTabsShadow.setScaleX(Math.min(scaleX, 1)); final float px = emojiTabsShadow.getPivotX(), py = 0; final float fullr = (float) Math.sqrt(Math.max( px * px + Math.pow(contentView.getHeight(), 2), Math.pow(contentView.getWidth() - px, 2) + Math.pow(contentView.getHeight(), 2) )); for (int i = 0; i < emojiTabs.contentView.getChildCount(); ++i) { View child = emojiTabs.contentView.getChildAt(i); if (t == 0) { child.setLayerType(LAYER_TYPE_HARDWARE, null); } else if (t == 1) { child.setLayerType(LAYER_TYPE_NONE, null); } final float ccx = child.getLeft() + child.getWidth() / 2f - px; float ccy = child.getTop() + child.getHeight() / 2f; if (isBottom()) { ccy = getMeasuredHeight() - ccy; } final float distance = (float) Math.sqrt(ccx * ccx + ccy * ccy * .4f); float scale = AndroidUtilities.cascade(containeritemst, distance, fullr, child.getHeight() * 1.75f); if (Float.isNaN(scale)) { scale = 0; } child.setScaleX(scale); child.setScaleY(scale); } for (int i = 0; i < emojiGridView.getChildCount(); ++i) { View child = emojiGridView.getChildAt(i); if (child instanceof ImageViewEmoji) { ImageViewEmoji imageViewEmoji = (ImageViewEmoji) child; float cx = child.getLeft() + child.getWidth() / 2f - px; float cy = child.getTop() + child.getHeight() / 2f; if (isBottom()) { cy = getMeasuredHeight() - cy; } float distance = (float) Math.sqrt(cx * cx + cy * cy * .2f); float scale = AndroidUtilities.cascade(containeritemst, distance, fullr, child.getHeight() * 1.75f); if (Float.isNaN(scale)) { scale = 0; } imageViewEmoji.setAnimatedScale(scale); } } emojiGridViewContainer.invalidate(); emojiGridView.invalidate(); } public void onDismiss(Runnable dismiss) { if (listStateId != null) { listStates.put(listStateId, layoutManager.onSaveInstanceState()); } if (hideAnimator != null) { hideAnimator.cancel(); hideAnimator = null; } hideAnimator = ValueAnimator.ofFloat(0, 1); hideAnimator.addUpdateListener(anm -> { float t = 1f - (float) anm.getAnimatedValue(); setTranslationY(AndroidUtilities.dp(8) * (1f - t)); if (bubble1View != null) { bubble1View.setAlpha(t); } if (bubble2View != null) { bubble2View.setAlpha(t * t); } contentView.setAlpha(t); contentView.invalidate(); invalidate(); }); hideAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { dismiss.run(); if (selectStatusDateDialog != null) { selectStatusDateDialog.dismiss(); selectStatusDateDialog = null; } } }); hideAnimator.setDuration(200); hideAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); hideAnimator.start(); if (searchBox != null) { AndroidUtilities.hideKeyboard(searchBox.input); } } public void setDrawBackground(boolean drawBackground) { this.drawBackground = drawBackground; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { contentView.setClipToOutline(drawBackground); } if (!drawBackground) { backgroundView.setVisibility(GONE); } else { backgroundView.setVisibility(VISIBLE); } } public void setRecentReactions(List<ReactionsLayoutInBubble.VisibleReaction> reactions) { recentReactionsToSet = reactions; updateRows(false, true); } public void resetBackgroundBitmaps() { for (int i = 0; i < emojiGridView.lineDrawables.size(); i++) { EmojiListView.DrawingInBackgroundLine line = emojiGridView.lineDrawables.get(i); for (int j = 0; j < line.imageViewEmojis.size(); j++) { if (line.imageViewEmojis.get(j).notDraw) { line.imageViewEmojis.get(j).notDraw = false; line.imageViewEmojis.get(j).invalidate(); line.reset(); } } } emojiGridView.invalidate(); for (int i = 0; i < emojiSearchGridView.lineDrawables.size(); i++) { EmojiListView.DrawingInBackgroundLine line = emojiSearchGridView.lineDrawables.get(i); for (int j = 0; j < line.imageViewEmojis.size(); j++) { if (line.imageViewEmojis.get(j).notDraw) { line.imageViewEmojis.get(j).notDraw = false; line.imageViewEmojis.get(j).invalidate(); line.reset(); } } } emojiSearchGridView.invalidate(); } public void setSelected(Long documentId) { selectedDocumentIds.clear(); selectedDocumentIds.add(documentId); if (emojiGridView != null) { for (int i = 0; i < emojiGridView.getChildCount(); i++) { if (emojiGridView.getChildAt(i) instanceof ImageViewEmoji) { ImageViewEmoji imageViewEmoji = (ImageViewEmoji) emojiGridView.getChildAt(i); if (imageViewEmoji.span != null) { imageViewEmoji.setViewSelected(selectedDocumentIds.contains(imageViewEmoji.span.getDocumentId()), true); } else { imageViewEmoji.setViewSelected(selectedDocumentIds.contains(0L), true); } } } emojiGridView.invalidate(); } } public void setMultiSelected(Long documentId, boolean animated) { boolean isSelected; if (!selectedDocumentIds.contains(documentId)) { isSelected = true; selectedDocumentIds.add(documentId); } else { isSelected = false; selectedDocumentIds.remove(documentId); } if (emojiGridView != null) { for (int i = 0; i < emojiGridView.getChildCount(); i++) { if (emojiGridView.getChildAt(i) instanceof ImageViewEmoji) { ImageViewEmoji imageViewEmoji = (ImageViewEmoji) emojiGridView.getChildAt(i); if (imageViewEmoji.span != null && imageViewEmoji.span.getDocumentId() == documentId) { imageViewEmoji.setViewSelectedWithScale(isSelected, animated); } else if (imageViewEmoji.document != null && imageViewEmoji.document.id == documentId) { imageViewEmoji.setViewSelectedWithScale(isSelected, animated); } } } emojiGridView.invalidate(); } } public boolean unselect(Long documentId) { selectedDocumentIds.remove(documentId); boolean found = false; if (emojiGridView != null) { for (int i = 0; i < emojiGridView.getChildCount(); i++) { if (emojiGridView.getChildAt(i) instanceof ImageViewEmoji) { ImageViewEmoji imageViewEmoji = (ImageViewEmoji) emojiGridView.getChildAt(i); if (imageViewEmoji.span != null && imageViewEmoji.span.getDocumentId() == documentId) { imageViewEmoji.unselectWithScale(); found = true; } else if (imageViewEmoji.document != null && imageViewEmoji.document.id == documentId) { imageViewEmoji.unselectWithScale(); found = true; } } } emojiGridView.invalidate(); if (!found) { for (int i = 0; i < rowHashCodes.size(); i++) { long hash = rowHashCodes.get(i); if (hash == 62425L + 13L * documentId || hash == 3212 + 13L * documentId) { if (adapter != null) { adapter.notifyItemChanged(i); } found = true; break; } } } } return found; } public void clearSelectedDocuments() { selectedDocumentIds.clear(); } public void setScrimDrawable(AnimatedEmojiDrawable.SwapAnimatedEmojiDrawable scrimDrawable, View drawableParent) { this.scrimColor = scrimDrawable == null || scrimDrawable.getColor() == null ? 0 : scrimDrawable.getColor(); this.scrimDrawable = scrimDrawable; this.scrimDrawableParent = drawableParent; if (isAttached && scrimDrawable != null) { scrimDrawable.setSecondParent(this); } invalidate(); } Paint paint = new Paint(); public void drawBigReaction(Canvas canvas, View view) { if (selectedReactionView == null) { return; } bigReactionImageReceiver.setParentView(view); if (selectedReactionView != null) { if (pressedProgress != 1f && !cancelPressed) { pressedProgress += 16f / 1500f; if (pressedProgress >= 1f) { pressedProgress = 1f; if (bigReactionListener != null) { bigReactionListener.onLongPressed(selectedReactionView); } } selectedReactionView.bigReactionSelectedProgress = pressedProgress; } float pressedViewScale = 1 + 2 * pressedProgress; canvas.save(); canvas.translate(emojiGridView.getX() + selectedReactionView.getX(), gridViewContainer.getY() + emojiGridView.getY() + selectedReactionView.getY()); paint.setColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground, resourcesProvider)); canvas.drawRect(0, 0, selectedReactionView.getMeasuredWidth(), selectedReactionView.getMeasuredHeight(), paint); canvas.scale(pressedViewScale, pressedViewScale, selectedReactionView.getMeasuredWidth() / 2f, selectedReactionView.getMeasuredHeight()); ImageReceiver imageReceiver = selectedReactionView.isDefaultReaction ? bigReactionImageReceiver : selectedReactionView.imageReceiverToDraw; if (bigReactionAnimatedEmoji != null && bigReactionAnimatedEmoji.getImageReceiver() != null && bigReactionAnimatedEmoji.getImageReceiver().hasBitmapImage()) { imageReceiver = bigReactionAnimatedEmoji.getImageReceiver(); } if (imageReceiver != null) { imageReceiver.setImageCoords(0, 0, selectedReactionView.getMeasuredWidth(), selectedReactionView.getMeasuredHeight()); imageReceiver.draw(canvas); } canvas.restore(); view.invalidate(); } } private static HashMap<Integer, Parcelable> listStates = new HashMap<Integer, Parcelable>(); private Integer listStateId; public void setSaveState(int saveId) { listStateId = saveId; } public static void clearState(int saveId) { listStates.remove(saveId); } public void setOnLongPressedListener(onLongPressedListener l) { bigReactionListener = l; } public void setOnRecentClearedListener(SelectAnimatedEmojiDialog.onRecentClearedListener onRecentClearedListener) { this.onRecentClearedListener = onRecentClearedListener; } public interface onLongPressedListener { void onLongPressed(ImageViewEmoji view); } public interface onRecentClearedListener { void onRecentCleared(); } private class SelectStatusDurationDialog extends Dialog { private ImageViewEmoji imageViewEmoji; private ImageReceiver imageReceiver; private Rect from = new Rect(), to = new Rect(), current = new Rect(); private Theme.ResourcesProvider resourcesProvider; private Runnable parentDialogDismiss; private View parentDialogView; private int blurBitmapWidth, blurBitmapHeight; private Bitmap blurBitmap; private Paint blurBitmapPaint; private WindowInsets lastInsets; private ContentView contentView; private LinearLayout linearLayoutView; private View emojiPreviewView; private ActionBarPopupWindow.ActionBarPopupWindowLayout menuView; private BottomSheet dateBottomSheet; private boolean changeToScrimColor; private int parentDialogX, parentDialogY; private int clipBottom; private int[] tempLocation = new int[2]; private class ContentView extends FrameLayout { public ContentView(Context context) { super(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure( MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec), MeasureSpec.EXACTLY) ); } @Override protected void dispatchDraw(Canvas canvas) { if (blurBitmap != null && blurBitmapPaint != null) { canvas.save(); canvas.scale(12f, 12f); blurBitmapPaint.setAlpha((int) (255 * showT)); canvas.drawBitmap(blurBitmap, 0, 0, blurBitmapPaint); canvas.restore(); } super.dispatchDraw(canvas); if (imageViewEmoji != null) { Drawable drawable = imageViewEmoji.drawable; if (drawable != null) { if (changeToScrimColor) { drawable.setColorFilter(new PorterDuffColorFilter(ColorUtils.blendARGB(scrimColor, accentColor, showT), PorterDuff.Mode.MULTIPLY)); } else { drawable.setColorFilter(premiumStarColorFilter); } drawable.setAlpha((int) (255 * (1f - showT))); AndroidUtilities.rectTmp.set(current); float scale = 1f; if (imageViewEmoji.pressedProgress != 0 || imageViewEmoji.selected) { scale *= 0.8f + 0.2f * (1f - (imageViewEmoji.selected ? .7f : imageViewEmoji.pressedProgress)); } AndroidUtilities.rectTmp2.set( (int) (AndroidUtilities.rectTmp.centerX() - AndroidUtilities.rectTmp.width() / 2 * scale), (int) (AndroidUtilities.rectTmp.centerY() - AndroidUtilities.rectTmp.height() / 2 * scale), (int) (AndroidUtilities.rectTmp.centerX() + AndroidUtilities.rectTmp.width() / 2 * scale), (int) (AndroidUtilities.rectTmp.centerY() + AndroidUtilities.rectTmp.height() / 2 * scale) ); float skew = 1f - (1f - imageViewEmoji.skewAlpha) * (1f - showT); canvas.save(); if (skew < 1) { canvas.translate(AndroidUtilities.rectTmp2.left, AndroidUtilities.rectTmp2.top); canvas.scale(1f, skew, 0, 0); canvas.skew((1f - 2f * imageViewEmoji.skewIndex / SPAN_COUNT_FOR_EMOJI) * (1f - skew), 0); canvas.translate(-AndroidUtilities.rectTmp2.left, -AndroidUtilities.rectTmp2.top); } canvas.clipRect(0, 0, getWidth(), clipBottom + showT * AndroidUtilities.dp(45)); drawable.setBounds(AndroidUtilities.rectTmp2); drawable.draw(canvas); canvas.restore(); if (imageViewEmoji.skewIndex == 0) { AndroidUtilities.rectTmp2.offset(AndroidUtilities.dp(8 * skew), 0); } else if (imageViewEmoji.skewIndex == 1) { AndroidUtilities.rectTmp2.offset(AndroidUtilities.dp(4 * skew), 0); } else if (imageViewEmoji.skewIndex == SPAN_COUNT_FOR_EMOJI - 2) { AndroidUtilities.rectTmp2.offset(-AndroidUtilities.dp(-4 * skew), 0); } else if (imageViewEmoji.skewIndex == SPAN_COUNT_FOR_EMOJI - 1) { AndroidUtilities.rectTmp2.offset(AndroidUtilities.dp(-8 * skew), 0); } canvas.saveLayerAlpha(AndroidUtilities.rectTmp2.left, AndroidUtilities.rectTmp2.top, AndroidUtilities.rectTmp2.right, AndroidUtilities.rectTmp2.bottom, (int) (255 * (1f - showT)), Canvas.ALL_SAVE_FLAG); canvas.clipRect(AndroidUtilities.rectTmp2); canvas.translate((int) (bottomGradientView.getX() + SelectAnimatedEmojiDialog.this.contentView.getX() + parentDialogX), (int) bottomGradientView.getY() + SelectAnimatedEmojiDialog.this.contentView.getY() + parentDialogY); bottomGradientView.draw(canvas); canvas.restore(); } else if (imageViewEmoji.isDefaultReaction && imageViewEmoji.imageReceiver != null) { imageViewEmoji.imageReceiver.setAlpha(1f - showT); imageViewEmoji.imageReceiver.setImageCoords(current); imageViewEmoji.imageReceiver.draw(canvas); } } if (imageReceiver != null) { imageReceiver.setAlpha(showT); imageReceiver.setImageCoords(current); imageReceiver.draw(canvas); } } @Override protected void onConfigurationChanged(Configuration newConfig) { lastInsets = null; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (imageReceiver != null) { imageReceiver.onAttachedToWindow(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (imageReceiver != null) { imageReceiver.onDetachedFromWindow(); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); Activity parentActivity = getParentActivity(); if (parentActivity == null) { return; } View parentView = parentActivity.getWindow().getDecorView(); if (blurBitmap == null || blurBitmap.getWidth() != parentView.getMeasuredWidth() || blurBitmap.getHeight() != parentView.getMeasuredHeight()) { prepareBlurBitmap(); } } } public SelectStatusDurationDialog(Context context, Runnable parentDialogDismiss, View parentDialogView, ImageViewEmoji imageViewEmoji, Theme.ResourcesProvider resourcesProvider) { super(context); this.imageViewEmoji = imageViewEmoji; this.resourcesProvider = resourcesProvider; this.parentDialogDismiss = parentDialogDismiss; this.parentDialogView = parentDialogView; setContentView( this.contentView = new ContentView(context), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) ); linearLayoutView = new LinearLayout(context); linearLayoutView.setOrientation(LinearLayout.VERTICAL); emojiPreviewView = new View(context) { @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); getLocationOnScreen(tempLocation); to.set( tempLocation[0], tempLocation[1], tempLocation[0] + getWidth(), tempLocation[1] + getHeight() ); AndroidUtilities.lerp(from, to, showT, current); } }; linearLayoutView.addView(emojiPreviewView, LayoutHelper.createLinear(160, 160, Gravity.CENTER, 0, 0, 0, 16)); menuView = new ActionBarPopupWindow.ActionBarPopupWindowLayout(context, R.drawable.popup_fixed_alert2, resourcesProvider); linearLayoutView.addView(menuView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 0, 0, 0)); ActionBarMenuItem.addItem(true, false, menuView, 0, LocaleController.getString("SetEmojiStatusUntil1Hour", R.string.SetEmojiStatusUntil1Hour), false, resourcesProvider) .setOnClickListener(e -> done((int) (System.currentTimeMillis() / 1000 + 60 * 60))); ActionBarMenuItem.addItem(false, false, menuView, 0, LocaleController.getString("SetEmojiStatusUntil2Hours", R.string.SetEmojiStatusUntil2Hours), false, resourcesProvider) .setOnClickListener(e -> done((int) (System.currentTimeMillis() / 1000 + 2 * 60 * 60))); ActionBarMenuItem.addItem(false, false, menuView, 0, LocaleController.getString("SetEmojiStatusUntil8Hours", R.string.SetEmojiStatusUntil8Hours), false, resourcesProvider) .setOnClickListener(e -> done((int) (System.currentTimeMillis() / 1000 + 8 * 60 * 60))); ActionBarMenuItem.addItem(false, false, menuView, 0, LocaleController.getString("SetEmojiStatusUntil2Days", R.string.SetEmojiStatusUntil2Days), false, resourcesProvider) .setOnClickListener(e -> done((int) (System.currentTimeMillis() / 1000 + 2 * 24 * 60 * 60))); ActionBarMenuItem.addItem(false, true, menuView, 0, LocaleController.getString("SetEmojiStatusUntilOther", R.string.SetEmojiStatusUntilOther), false, resourcesProvider) .setOnClickListener(e -> { if (dateBottomSheet != null) { return; } boolean[] selected = new boolean[1]; BottomSheet.Builder builder = AlertsCreator.createStatusUntilDatePickerDialog(context, System.currentTimeMillis() / 1000, date -> { selected[0] = true; done(date); }); builder.setOnPreDismissListener(di -> { if (!selected[0]) { animateMenuShow(true, null); } dateBottomSheet = null; }); dateBottomSheet = builder.show(); animateMenuShow(false, null); }); contentView.addView(linearLayoutView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); Window window = getWindow(); if (window != null) { window.setWindowAnimations(R.style.DialogNoAnimation); window.setBackgroundDrawable(null); WindowManager.LayoutParams params = window.getAttributes(); params.width = ViewGroup.LayoutParams.MATCH_PARENT; params.gravity = Gravity.TOP | Gravity.LEFT; params.dimAmount = 0; params.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND; params.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; if (Build.VERSION.SDK_INT >= 21) { params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS; contentView.setOnApplyWindowInsetsListener((v, insets) -> { lastInsets = insets; v.requestLayout(); return Build.VERSION.SDK_INT >= 30 ? WindowInsets.CONSUMED : insets.consumeSystemWindowInsets(); }); } params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; contentView.setFitsSystemWindows(true); contentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN); params.height = ViewGroup.LayoutParams.MATCH_PARENT; if (Build.VERSION.SDK_INT >= 28) { params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; } window.setAttributes(params); } if (imageViewEmoji != null) { imageViewEmoji.notDraw = true; } prepareBlurBitmap(); imageReceiver = new ImageReceiver(); imageReceiver.setParentView(contentView); imageReceiver.setLayerNum(7); TLRPC.Document document = imageViewEmoji.document; if (document == null && imageViewEmoji != null && imageViewEmoji.drawable instanceof AnimatedEmojiDrawable) { document = ((AnimatedEmojiDrawable) imageViewEmoji.drawable).getDocument(); } if (document != null) { String filter = "160_160"; ImageLocation mediaLocation; String mediaFilter; SvgHelper.SvgDrawable thumbDrawable = DocumentObject.getSvgThumb(document.thumbs, Theme.key_windowBackgroundWhiteGrayIcon, 0.2f); TLRPC.PhotoSize thumb = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 90); if ("video/webm".equals(document.mime_type)) { mediaLocation = ImageLocation.getForDocument(document); mediaFilter = filter + "_" + ImageLoader.AUTOPLAY_FILTER; if (thumbDrawable != null) { thumbDrawable.overrideWidthAndHeight(512, 512); } } else { if (thumbDrawable != null && MessageObject.isAnimatedStickerDocument(document, false)) { thumbDrawable.overrideWidthAndHeight(512, 512); } mediaLocation = ImageLocation.getForDocument(document); mediaFilter = filter; } imageReceiver.setImage(mediaLocation, mediaFilter, ImageLocation.getForDocument(thumb, document), filter, null, null, thumbDrawable, document.size, null, document, 1); if (imageViewEmoji.drawable instanceof AnimatedEmojiDrawable && (MessageObject.isTextColorEmoji(document) || ((AnimatedEmojiDrawable) imageViewEmoji.drawable).canOverrideColor())) { imageReceiver.setColorFilter(MessageObject.isTextColorEmoji(document) || AnimatedEmojiDrawable.isDefaultStatusEmoji((AnimatedEmojiDrawable) imageViewEmoji.drawable) ? premiumStarColorFilter : Theme.getAnimatedEmojiColorFilter(resourcesProvider)); } } imageViewEmoji.getLocationOnScreen(tempLocation); from.left = tempLocation[0] + imageViewEmoji.getPaddingLeft(); from.top = tempLocation[1] + imageViewEmoji.getPaddingTop(); from.right = tempLocation[0] + imageViewEmoji.getWidth() - imageViewEmoji.getPaddingRight(); from.bottom = tempLocation[1] + imageViewEmoji.getHeight() - imageViewEmoji.getPaddingBottom(); AndroidUtilities.lerp(from, to, showT, current); parentDialogView.getLocationOnScreen(tempLocation); parentDialogX = tempLocation[0]; clipBottom = (parentDialogY = tempLocation[1]) + parentDialogView.getHeight(); } private boolean done = false; private void done(Integer date) { if (done) { return; } done = true; boolean showback; if (showback = changeToScrimColor = date != null && getOutBounds(from)) { parentDialogView.getLocationOnScreen(tempLocation); from.offset(tempLocation[0], tempLocation[1]); } else { imageViewEmoji.getLocationOnScreen(tempLocation); from.left = tempLocation[0] + imageViewEmoji.getPaddingLeft(); from.top = tempLocation[1] + imageViewEmoji.getPaddingTop(); from.right = tempLocation[0] + imageViewEmoji.getWidth() - imageViewEmoji.getPaddingRight(); from.bottom = tempLocation[1] + imageViewEmoji.getHeight() - imageViewEmoji.getPaddingBottom(); } if (date != null && parentDialogDismiss != null) { parentDialogDismiss.run(); } animateShow(false, () -> { onEnd(date); try { super.dismiss(); } catch (Exception ignore) { } }, () -> { if (date != null) { try { performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); } catch (Exception ignore) {} onEndPartly(date); } }, !showback); animateMenuShow(false, null); } protected boolean getOutBounds(Rect rect) { return false; } protected void onEnd(Integer date) { } protected void onEndPartly(Integer date) { } private Activity getParentActivity() { Context currentContext = getContext(); while (currentContext instanceof ContextWrapper) { if (currentContext instanceof Activity) return (Activity) currentContext; currentContext = ((ContextWrapper) currentContext).getBaseContext(); } return null; } private void prepareBlurBitmap() { Activity parentActivity = getParentActivity(); if (parentActivity == null) { return; } View parentView = parentActivity.getWindow().getDecorView(); int w = (int) (parentView.getMeasuredWidth() / 12.0f); int h = (int) (parentView.getMeasuredHeight() / 12.0f); Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); canvas.scale(1.0f / 12.0f, 1.0f / 12.0f); canvas.drawColor(Theme.getColor(Theme.key_windowBackgroundWhite)); parentView.draw(canvas); if (parentActivity instanceof LaunchActivity && ((LaunchActivity) parentActivity).getActionBarLayout().getLastFragment().getVisibleDialog() != null) { ((LaunchActivity) parentActivity).getActionBarLayout().getLastFragment().getVisibleDialog().getWindow().getDecorView().draw(canvas); } if (parentDialogView != null) { parentDialogView.getLocationOnScreen(tempLocation); canvas.save(); canvas.translate(tempLocation[0], tempLocation[1]); parentDialogView.draw(canvas); canvas.restore(); } Utilities.stackBlurBitmap(bitmap, Math.max(10, Math.max(w, h) / 180)); blurBitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG); blurBitmap = bitmap; } private float showT; private boolean showing; private ValueAnimator showAnimator; private void animateShow(boolean show, Runnable onDone, Runnable onPartly, boolean showback) { if (imageViewEmoji == null) { if (onDone != null) { onDone.run(); } return; } if (showAnimator != null) { if (showing == show) { return; } showAnimator.cancel(); } showing = show; if (show) { imageViewEmoji.notDraw = true; } final boolean[] partlydone = new boolean[1]; showAnimator = ValueAnimator.ofFloat(showT, show ? 1f : 0); showAnimator.addUpdateListener(anm -> { showT = (float) anm.getAnimatedValue(); AndroidUtilities.lerp(from, to, showT, current); contentView.invalidate(); if (!show) { menuView.setAlpha(showT); } if (showT < 0.025f && !show) { if (showback) { imageViewEmoji.notDraw = false; emojiGridView.invalidate(); } NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.startAllHeavyOperations, 4); } if (showT < .5f && !show && onPartly != null && !partlydone[0]) { partlydone[0] = true; onPartly.run(); } }); showAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { showT = show ? 1f : 0; AndroidUtilities.lerp(from, to, showT, current); contentView.invalidate(); if (!show) { menuView.setAlpha(showT); } if (showT < .5f && !show && onPartly != null && !partlydone[0]) { partlydone[0] = true; onPartly.run(); } if (!show) { if (showback) { imageViewEmoji.notDraw = false; emojiGridView.invalidate(); } NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.startAllHeavyOperations, 4); } showAnimator = null; contentView.invalidate(); if (onDone != null) { onDone.run(); } } }); showAnimator.setDuration(420); showAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); showAnimator.start(); } private float showMenuT; private boolean showingMenu; private ValueAnimator showMenuAnimator; private void animateMenuShow(boolean show, Runnable onDone) { if (showMenuAnimator != null) { if (showingMenu == show) { return; } showMenuAnimator.cancel(); } showingMenu = show; // imageViewEmoji.notDraw = true; showMenuAnimator = ValueAnimator.ofFloat(showMenuT, show ? 1f : 0); showMenuAnimator.addUpdateListener(anm -> { showMenuT = (float) anm.getAnimatedValue(); menuView.setBackScaleY(showMenuT); menuView.setAlpha(CubicBezierInterpolator.EASE_OUT.getInterpolation(showMenuT)); final int count = menuView.getItemsCount(); for (int i = 0; i < count; ++i) { final float at = AndroidUtilities.cascade(showMenuT, i, count, 4); menuView.getItemAt(i).setTranslationY((1f - at) * AndroidUtilities.dp(-12)); menuView.getItemAt(i).setAlpha(at); } }); showMenuAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { showMenuT = show ? 1f : 0; menuView.setBackScaleY(showMenuT); menuView.setAlpha(CubicBezierInterpolator.EASE_OUT.getInterpolation(showMenuT)); final int count = menuView.getItemsCount(); for (int i = 0; i < count; ++i) { final float at = AndroidUtilities.cascade(showMenuT, i, count, 4); menuView.getItemAt(i).setTranslationY((1f - at) * AndroidUtilities.dp(-12)); menuView.getItemAt(i).setAlpha(at); } showMenuAnimator = null; if (onDone != null) { onDone.run(); } } }); if (show) { showMenuAnimator.setDuration(360); showMenuAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); } else { showMenuAnimator.setDuration(240); showMenuAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT); } showMenuAnimator.start(); } @Override public boolean dispatchTouchEvent(@NonNull MotionEvent ev) { boolean res = super.dispatchTouchEvent(ev); if (!res && ev.getAction() == MotionEvent.ACTION_DOWN) { dismiss(); return false; } return res; } @Override public void show() { super.show(); NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.stopAllHeavyOperations, 4); animateShow(true, null, null, true); animateMenuShow(true, null); } private boolean dismissed = false; @Override public void dismiss() { if (dismissed) { return; } done(null); dismissed = true; } } public void setForumIconDrawable(Drawable drawable) { forumIconDrawable = drawable; if (forumIconImage != null) { forumIconImage.imageReceiver.setImageBitmap(forumIconDrawable); } } @Override public void setPressed(boolean pressed) { return; } public void setAnimationsEnabled(boolean aniationsEnabled) { this.animationsEnabled = aniationsEnabled; } public void setEnterAnimationInProgress(boolean enterAnimationInProgress) { if (this.enterAnimationInProgress != enterAnimationInProgress) { this.enterAnimationInProgress = enterAnimationInProgress; if (!enterAnimationInProgress) { AndroidUtilities.forEachViews(emojiGridView, (child) -> { child.setScaleX(1); child.setScaleY(1); }); for (int i = 0; i < emojiTabs.contentView.getChildCount(); ++i) { View child = emojiTabs.contentView.getChildAt(i); child.setScaleX(1); child.setScaleY(1); } emojiTabs.contentView.invalidate(); } } } public void setBackgroundDelegate(BackgroundDelegate backgroundDelegate) { this.backgroundDelegate = backgroundDelegate; } public interface BackgroundDelegate { void drawRect(Canvas canvas, int left, int top, int right, int bottom, float x, float y); } public boolean prevWindowKeyboardVisible() { return false; } public static class SetTitleDocument extends TLRPC.Document { public final String title; public SetTitleDocument(String title) { this.title = title; } } private ArrayList<TLRPC.Document> filter(ArrayList<TLRPC.Document> documents, HashSet<Long> restricted) { if (restricted == null) return documents; for (int i = 0; i < documents.size(); ++i) { TLRPC.Document d = documents.get(i); if (d == null || restricted.contains(d.id)) { documents.remove(i); i--; } } return documents; } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/SelectAnimatedEmojiDialog.java
2,185
package com.airbnb.lottie.parser; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableColorValue; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableGradientColorValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatablePointValue; import com.airbnb.lottie.model.animatable.AnimatableScaleValue; import com.airbnb.lottie.model.animatable.AnimatableShapeValue; import com.airbnb.lottie.model.animatable.AnimatableTextFrame; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.utils.Utils; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; import java.util.List; public class AnimatableValueParser { private AnimatableValueParser() { } public static AnimatableFloatValue parseFloat( JsonReader reader, LottieComposition composition) throws IOException { return parseFloat(reader, composition, true); } public static AnimatableFloatValue parseFloat( JsonReader reader, LottieComposition composition, boolean isDp) throws IOException { return new AnimatableFloatValue( parse(reader, isDp ? Utils.dpScale() : 1f, composition, FloatParser.INSTANCE)); } static AnimatableIntegerValue parseInteger( JsonReader reader, LottieComposition composition) throws IOException { return new AnimatableIntegerValue(parse(reader, composition, IntegerParser.INSTANCE)); } static AnimatablePointValue parsePoint( JsonReader reader, LottieComposition composition) throws IOException { return new AnimatablePointValue(KeyframesParser.parse(reader, composition, Utils.dpScale(), PointFParser.INSTANCE, true)); } static AnimatableScaleValue parseScale( JsonReader reader, LottieComposition composition) throws IOException { return new AnimatableScaleValue(parse(reader, composition, ScaleXYParser.INSTANCE)); } static AnimatableShapeValue parseShapeData( JsonReader reader, LottieComposition composition) throws IOException { return new AnimatableShapeValue( parse(reader, Utils.dpScale(), composition, ShapeDataParser.INSTANCE)); } static AnimatableTextFrame parseDocumentData( JsonReader reader, LottieComposition composition) throws IOException { return new AnimatableTextFrame(parse(reader, Utils.dpScale(), composition, DocumentDataParser.INSTANCE)); } static AnimatableColorValue parseColor( JsonReader reader, LottieComposition composition) throws IOException { return new AnimatableColorValue(parse(reader, composition, ColorParser.INSTANCE)); } static AnimatableGradientColorValue parseGradientColor( JsonReader reader, LottieComposition composition, int points) throws IOException { AnimatableGradientColorValue animatableGradientColorValue = new AnimatableGradientColorValue( parse(reader, composition, new GradientColorParser(points))); return animatableGradientColorValue; } /** * Will return null if the animation can't be played such as if it has expressions. */ private static <T> List<Keyframe<T>> parse(JsonReader reader, LottieComposition composition, ValueParser<T> valueParser) throws IOException { return KeyframesParser.parse(reader, composition, 1, valueParser, false); } /** * Will return null if the animation can't be played such as if it has expressions. */ private static <T> List<Keyframe<T>> parse( JsonReader reader, float scale, LottieComposition composition, ValueParser<T> valueParser) throws IOException { return KeyframesParser.parse(reader, composition, scale, valueParser, false); } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/parser/AnimatableValueParser.java
2,186
/* * Copyright 2002-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.scheduling.concurrent; import java.util.Properties; import java.util.concurrent.Executor; import javax.naming.NamingException; import org.springframework.beans.factory.InitializingBean; import org.springframework.jndi.JndiLocatorDelegate; import org.springframework.jndi.JndiTemplate; /** * JNDI-based variant of {@link ConcurrentTaskExecutor}, performing a default lookup for * JSR-236's "java:comp/DefaultManagedExecutorService" in a Jakarta EE/8 environment. * * <p>Note: This class is not strictly JSR-236 based; it can work with any regular * {@link java.util.concurrent.Executor} that can be found in JNDI. * The actual adapting to {@link jakarta.enterprise.concurrent.ManagedExecutorService} * happens in the base class {@link ConcurrentTaskExecutor} itself. * * @author Juergen Hoeller * @since 4.0 * @see jakarta.enterprise.concurrent.ManagedExecutorService */ public class DefaultManagedTaskExecutor extends ConcurrentTaskExecutor implements InitializingBean { private final JndiLocatorDelegate jndiLocator = new JndiLocatorDelegate(); private String jndiName = "java:comp/DefaultManagedExecutorService"; public DefaultManagedTaskExecutor() { // Executor initialization happens in afterPropertiesSet super(null); } /** * Set the JNDI template to use for JNDI lookups. * @see org.springframework.jndi.JndiAccessor#setJndiTemplate */ public void setJndiTemplate(JndiTemplate jndiTemplate) { this.jndiLocator.setJndiTemplate(jndiTemplate); } /** * Set the JNDI environment to use for JNDI lookups. * @see org.springframework.jndi.JndiAccessor#setJndiEnvironment */ public void setJndiEnvironment(Properties jndiEnvironment) { this.jndiLocator.setJndiEnvironment(jndiEnvironment); } /** * Set whether the lookup occurs in a Jakarta EE container, i.e. if the prefix * "java:comp/env/" needs to be added if the JNDI name doesn't already * contain it. PersistenceAnnotationBeanPostProcessor's default is "true". * @see org.springframework.jndi.JndiLocatorSupport#setResourceRef */ public void setResourceRef(boolean resourceRef) { this.jndiLocator.setResourceRef(resourceRef); } /** * Specify a JNDI name of the {@link java.util.concurrent.Executor} to delegate to, * replacing the default JNDI name "java:comp/DefaultManagedExecutorService". * <p>This can either be a fully qualified JNDI name, or the JNDI name relative * to the current environment naming context if "resourceRef" is set to "true". * @see #setConcurrentExecutor * @see #setResourceRef */ public void setJndiName(String jndiName) { this.jndiName = jndiName; } @Override public void afterPropertiesSet() throws NamingException { setConcurrentExecutor(this.jndiLocator.lookup(this.jndiName, Executor.class)); } }
spring-projects/spring-framework
spring-context/src/main/java/org/springframework/scheduling/concurrent/DefaultManagedTaskExecutor.java
2,187
package com.taobao.arthas.core.util; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * @author diecui1202 on 2017/10/25. */ public final class DateUtils { private DateUtils() { throw new AssertionError(); } private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); public static String getCurrentDateTime() { return DATE_TIME_FORMATTER.format(LocalDateTime.now()); } public static String formatDateTime(LocalDateTime dateTime) { return DATE_TIME_FORMATTER.format(dateTime); } }
alibaba/arthas
core/src/main/java/com/taobao/arthas/core/util/DateUtils.java
2,188
/* * Copyright 2002-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.scheduling.concurrent; import java.util.Properties; import java.util.concurrent.ScheduledExecutorService; import javax.naming.NamingException; import org.springframework.beans.factory.InitializingBean; import org.springframework.jndi.JndiLocatorDelegate; import org.springframework.jndi.JndiTemplate; /** * JNDI-based variant of {@link ConcurrentTaskScheduler}, performing a default lookup for * JSR-236's "java:comp/DefaultManagedScheduledExecutorService" in a Jakarta EE environment. * Expected to be exposed as a bean, in particular as the default lookup happens in the * standard {@link InitializingBean#afterPropertiesSet()} callback. * * <p>Note: This class is not strictly JSR-236 based; it can work with any regular * {@link java.util.concurrent.ScheduledExecutorService} that can be found in JNDI. * The actual adapting to {@link jakarta.enterprise.concurrent.ManagedScheduledExecutorService} * happens in the base class {@link ConcurrentTaskScheduler} itself. * * @author Juergen Hoeller * @since 4.0 * @see jakarta.enterprise.concurrent.ManagedScheduledExecutorService */ public class DefaultManagedTaskScheduler extends ConcurrentTaskScheduler implements InitializingBean { private final JndiLocatorDelegate jndiLocator = new JndiLocatorDelegate(); private String jndiName = "java:comp/DefaultManagedScheduledExecutorService"; public DefaultManagedTaskScheduler() { // Executor initialization happens in afterPropertiesSet super(null); } /** * Set the JNDI template to use for JNDI lookups. * @see org.springframework.jndi.JndiAccessor#setJndiTemplate */ public void setJndiTemplate(JndiTemplate jndiTemplate) { this.jndiLocator.setJndiTemplate(jndiTemplate); } /** * Set the JNDI environment to use for JNDI lookups. * @see org.springframework.jndi.JndiAccessor#setJndiEnvironment */ public void setJndiEnvironment(Properties jndiEnvironment) { this.jndiLocator.setJndiEnvironment(jndiEnvironment); } /** * Set whether the lookup occurs in a Jakarta EE container, i.e. if the prefix * "java:comp/env/" needs to be added if the JNDI name doesn't already * contain it. PersistenceAnnotationBeanPostProcessor's default is "true". * @see org.springframework.jndi.JndiLocatorSupport#setResourceRef */ public void setResourceRef(boolean resourceRef) { this.jndiLocator.setResourceRef(resourceRef); } /** * Specify a JNDI name of the {@link java.util.concurrent.Executor} to delegate to, * replacing the default JNDI name "java:comp/DefaultManagedScheduledExecutorService". * <p>This can either be a fully qualified JNDI name, or the JNDI name relative * to the current environment naming context if "resourceRef" is set to "true". * @see #setConcurrentExecutor * @see #setResourceRef */ public void setJndiName(String jndiName) { this.jndiName = jndiName; } @Override public void afterPropertiesSet() throws NamingException { ScheduledExecutorService executor = this.jndiLocator.lookup(this.jndiName, ScheduledExecutorService.class); setConcurrentExecutor(executor); setScheduledExecutor(executor); } }
spring-projects/spring-framework
spring-context/src/main/java/org/springframework/scheduling/concurrent/DefaultManagedTaskScheduler.java
2,189
/* * Copyright (C) 2012 The Project Lombok Authors. * * 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 lombok.eclipse; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Mark a handler class with this annotation to indicate that this handler should not be run in the diet parse phase. * 'diet parse' is where method bodies aren't filled in yet. If you have a method-level annotation that modifies the contents of that method, * you need to put this annotation on your handler. Otherwise, do not put this annotation on your handler. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DeferUntilPostDiet { }
projectlombok/lombok
src/core/lombok/eclipse/DeferUntilPostDiet.java
2,190
package org.telegram.ui.Components; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import androidx.core.graphics.ColorUtils; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.Utilities; public class GradientTools { public boolean isDiagonal; public boolean isRotate; public Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); int color1; int color2; int color3; int color4; private final static int INTERNAL_WIDTH = 60; private final static int INTERNAL_HEIGHT = 80; RectF bounds = new RectF(); Shader shader; Matrix matrix = new Matrix(); Bitmap gradientBitmap = null; int[] colors = new int[4]; public boolean isLinear; public void setColors(int color1, int color2) { setColors(color1, color2, 0, 0); } public void setColors(int color1, int color2, int color3) { setColors(color1, color2, color3, 0); } public void setColors(int color1, int color2, int color3, int color4) { if (shader != null && this.color1 == color1 && this.color2 == color2 && this.color3 == color3 && this.color4 == color4) { return; } colors[0] = this.color1 = color1; colors[1] = this.color2 = color2; colors[2] = this.color3 = color3; colors[3] = this.color4 = color4; if (color2 == 0) { paint.setShader(shader = null); paint.setColor(color1); } else if (color3 == 0) { if (isDiagonal && isRotate) { paint.setShader(shader = new LinearGradient(0, 0, INTERNAL_HEIGHT, INTERNAL_HEIGHT, new int[]{color1, color2}, null, Shader.TileMode.CLAMP)); } else { paint.setShader(shader = new LinearGradient(isDiagonal ? INTERNAL_HEIGHT : 0, 0, 0, INTERNAL_HEIGHT, new int[]{color1, color2}, null, Shader.TileMode.CLAMP)); } } else { if (isLinear) { if (isDiagonal && isRotate) { paint.setShader(shader = new LinearGradient(0, 0, INTERNAL_HEIGHT, INTERNAL_HEIGHT, new int[]{color1, color2, color3}, null, Shader.TileMode.CLAMP)); } else { paint.setShader(shader = new LinearGradient(isDiagonal ? INTERNAL_HEIGHT : 0, 0, 0, INTERNAL_HEIGHT, new int[]{color1, color2, color3}, null, Shader.TileMode.CLAMP)); } } else { if (gradientBitmap == null) { gradientBitmap = Bitmap.createBitmap(INTERNAL_WIDTH, INTERNAL_HEIGHT, Bitmap.Config.ARGB_8888); } Utilities.generateGradient(gradientBitmap, true, 0, 0, gradientBitmap.getWidth(), gradientBitmap.getHeight(), gradientBitmap.getRowBytes(), colors); paint.setShader(shader = new BitmapShader(gradientBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); } } updateBounds(); } public void setBounds(RectF bounds) { if (this.bounds.top == bounds.top && this.bounds.bottom == bounds.bottom && this.bounds.left == bounds.left && this.bounds.right == bounds.right) { return; } this.bounds.set(bounds); updateBounds(); } protected void updateBounds() { if (shader == null) { return; } float sx = bounds.width() / (float) INTERNAL_WIDTH; float sy = bounds.height() / (float) INTERNAL_HEIGHT; matrix.reset(); matrix.postTranslate(bounds.left, bounds.top); matrix.preScale(sx, sy); shader.setLocalMatrix(matrix); } public void setBounds(float left, float top, float right, float bottom) { AndroidUtilities.rectTmp.set(left, top, right, bottom); setBounds(AndroidUtilities.rectTmp); } public int getAverageColor() { int color = color1; if (color2 != 0) { color = ColorUtils.blendARGB(color, color2, 0.5f); } if (color3 != 0) { color = ColorUtils.blendARGB(color, color3, 0.5f); } if (color4 != 0) { color = ColorUtils.blendARGB(color, color4, 0.5f); } return color; } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/ui/Components/GradientTools.java
2,191
/* * 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.kafka.streams; import org.apache.kafka.clients.CommonClientConfigs; import org.apache.kafka.clients.admin.Admin; import org.apache.kafka.clients.admin.ListOffsetsResult.ListOffsetsResultInfo; import org.apache.kafka.clients.admin.MemberToRemove; import org.apache.kafka.clients.admin.RemoveMembersFromConsumerGroupOptions; import org.apache.kafka.clients.admin.RemoveMembersFromConsumerGroupResult; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.common.KafkaFuture; import org.apache.kafka.common.Metric; import org.apache.kafka.common.MetricName; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.annotation.InterfaceStability.Evolving; import org.apache.kafka.common.errors.TimeoutException; import org.apache.kafka.common.metrics.KafkaMetricsContext; import org.apache.kafka.common.metrics.MetricConfig; import org.apache.kafka.common.metrics.Metrics; import org.apache.kafka.common.metrics.MetricsContext; import org.apache.kafka.common.metrics.MetricsReporter; import org.apache.kafka.common.metrics.Sensor; import org.apache.kafka.common.metrics.Sensor.RecordingLevel; import org.apache.kafka.common.serialization.Serializer; import org.apache.kafka.common.utils.LogContext; import org.apache.kafka.common.utils.Time; import org.apache.kafka.common.utils.Timer; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.streams.errors.InvalidStateStoreException; import org.apache.kafka.streams.errors.InvalidStateStorePartitionException; import org.apache.kafka.streams.errors.ProcessorStateException; import org.apache.kafka.streams.errors.StreamsException; import org.apache.kafka.streams.errors.StreamsNotStartedException; import org.apache.kafka.streams.errors.StreamsStoppedException; import org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler; import org.apache.kafka.streams.errors.UnknownStateStoreException; import org.apache.kafka.streams.internals.ClientInstanceIdsImpl; import org.apache.kafka.streams.internals.metrics.ClientMetrics; import org.apache.kafka.streams.processor.StandbyUpdateListener; import org.apache.kafka.streams.processor.StateRestoreListener; import org.apache.kafka.streams.processor.StateStore; import org.apache.kafka.streams.processor.StreamPartitioner; import org.apache.kafka.streams.processor.TaskId; import org.apache.kafka.streams.processor.internals.ClientUtils; import org.apache.kafka.streams.processor.internals.GlobalStreamThread; import org.apache.kafka.streams.processor.internals.StateDirectory; import org.apache.kafka.streams.processor.internals.StreamThread; import org.apache.kafka.streams.processor.internals.StreamsMetadataState; import org.apache.kafka.streams.processor.internals.Task; import org.apache.kafka.streams.processor.internals.ThreadStateTransitionValidator; import org.apache.kafka.streams.processor.internals.TopologyMetadata; import org.apache.kafka.streams.processor.internals.assignment.AssignorError; import org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl; import org.apache.kafka.streams.processor.internals.namedtopology.NamedTopology; import org.apache.kafka.streams.query.FailureReason; import org.apache.kafka.streams.query.PositionBound; import org.apache.kafka.streams.query.QueryConfig; import org.apache.kafka.streams.query.QueryResult; import org.apache.kafka.streams.query.StateQueryRequest; import org.apache.kafka.streams.query.StateQueryResult; import org.apache.kafka.streams.state.HostInfo; import org.apache.kafka.streams.state.internals.GlobalStateStoreProvider; import org.apache.kafka.streams.state.internals.QueryableStoreProvider; import org.apache.kafka.streams.state.internals.StreamThreadStateStoreProvider; import org.slf4j.Logger; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT; import static org.apache.kafka.streams.internals.ApiUtils.prepareMillisCheckFailMsgPrefix; import static org.apache.kafka.streams.internals.ApiUtils.validateMillisecondDuration; import static org.apache.kafka.streams.internals.StreamsConfigUtils.getTotalCacheSize; import static org.apache.kafka.streams.processor.internals.ClientUtils.fetchEndOffsets; import static org.apache.kafka.streams.processor.internals.TopologyMetadata.UNNAMED_TOPOLOGY; /** * A Kafka client that allows for performing continuous computation on input coming from one or more input topics and * sends output to zero, one, or more output topics. * <p> * The computational logic can be specified either by using the {@link Topology} to define a DAG topology of * {@link org.apache.kafka.streams.processor.api.Processor}s or by using the {@link StreamsBuilder} which provides the high-level DSL to define * transformations. * <p> * One {@code KafkaStreams} instance can contain one or more threads specified in the configs for the processing work. * <p> * A {@code KafkaStreams} instance can co-ordinate with any other instances with the same * {@link StreamsConfig#APPLICATION_ID_CONFIG application ID} (whether in the same process, on other processes on this * machine, or on remote machines) as a single (possibly distributed) stream processing application. * These instances will divide up the work based on the assignment of the input topic partitions so that all partitions * are being consumed. * If instances are added or fail, all (remaining) instances will rebalance the partition assignment among themselves * to balance processing load and ensure that all input topic partitions are processed. * <p> * Internally a {@code KafkaStreams} instance contains a normal {@link KafkaProducer} and {@link KafkaConsumer} instance * that is used for reading input and writing output. * <p> * A simple example might look like this: * <pre>{@code * Properties props = new Properties(); * props.put(StreamsConfig.APPLICATION_ID_CONFIG, "my-stream-processing-application"); * props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); * props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass()); * props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass()); * * StreamsBuilder builder = new StreamsBuilder(); * builder.<String, String>stream("my-input-topic").mapValues(value -> String.valueOf(value.length())).to("my-output-topic"); * * KafkaStreams streams = new KafkaStreams(builder.build(), props); * streams.start(); * }</pre> * * @see org.apache.kafka.streams.StreamsBuilder * @see org.apache.kafka.streams.Topology */ public class KafkaStreams implements AutoCloseable { private static final String JMX_PREFIX = "kafka.streams"; // processId is expected to be unique across JVMs and to be used // in userData of the subscription request to allow assignor be aware // of the co-location of stream thread's consumers. It is for internal // usage only and should not be exposed to users at all. private final Time time; private final Logger log; protected final String clientId; private final Metrics metrics; protected final StreamsConfig applicationConfigs; protected final List<StreamThread> threads; protected final StreamsMetadataState streamsMetadataState; private final ScheduledExecutorService stateDirCleaner; private final ScheduledExecutorService rocksDBMetricsRecordingService; protected final Admin adminClient; private final StreamsMetricsImpl streamsMetrics; private final long totalCacheSize; private final StreamStateListener streamStateListener; private final DelegatingStateRestoreListener delegatingStateRestoreListener; private final Map<Long, StreamThread.State> threadState; private final UUID processId; private final KafkaClientSupplier clientSupplier; protected final TopologyMetadata topologyMetadata; private final QueryableStoreProvider queryableStoreProvider; private final DelegatingStandbyUpdateListener delegatingStandbyUpdateListener; GlobalStreamThread globalStreamThread; protected StateDirectory stateDirectory = null; private KafkaStreams.StateListener stateListener; private boolean oldHandler; private BiConsumer<Throwable, Boolean> streamsUncaughtExceptionHandler; private final Object changeThreadCount = new Object(); // container states /** * Kafka Streams states are the possible state that a Kafka Streams instance can be in. * An instance must only be in one state at a time. * The expected state transition with the following defined states is: * * <pre> * +--------------+ * +&lt;----- | Created (0) | * | +-----+--------+ * | | * | v * | +----+--+------+ * | | Re- | * +&lt;----- | Balancing (1)| --------&gt;+ * | +-----+-+------+ | * | | ^ | * | v | | * | +--------------+ v * | | Running (2) | --------&gt;+ * | +------+-------+ | * | | | * | v | * | +------+-------+ +----+-------+ * +-----&gt; | Pending | | Pending | * | Shutdown (3) | | Error (5) | * +------+-------+ +-----+------+ * | | * v v * +------+-------+ +-----+--------+ * | Not | | Error (6) | * | Running (4) | +--------------+ * +--------------+ * * * </pre> * Note the following: * - RUNNING state will transit to REBALANCING if any of its threads is in PARTITION_REVOKED or PARTITIONS_ASSIGNED state * - REBALANCING state will transit to RUNNING if all of its threads are in RUNNING state * - Any state except NOT_RUNNING, PENDING_ERROR or ERROR can go to PENDING_SHUTDOWN (whenever close is called) * - Of special importance: If the global stream thread dies, or all stream threads die (or both) then * the instance will be in the ERROR state. The user will not need to close it. */ public enum State { // Note: if you add a new state, check the below methods and how they are used within Streams to see if // any of them should be updated to include the new state. For example a new shutdown path or terminal // state would likely need to be included in methods like isShuttingDown(), hasCompletedShutdown(), etc. CREATED(1, 3), // 0 REBALANCING(2, 3, 5), // 1 RUNNING(1, 2, 3, 5), // 2 PENDING_SHUTDOWN(4), // 3 NOT_RUNNING, // 4 PENDING_ERROR(6), // 5 ERROR; // 6 private final Set<Integer> validTransitions = new HashSet<>(); State(final Integer... validTransitions) { this.validTransitions.addAll(Arrays.asList(validTransitions)); } public boolean hasNotStarted() { return equals(CREATED); } public boolean isRunningOrRebalancing() { return equals(RUNNING) || equals(REBALANCING); } public boolean isShuttingDown() { return equals(PENDING_SHUTDOWN) || equals(PENDING_ERROR); } public boolean hasCompletedShutdown() { return equals(NOT_RUNNING) || equals(ERROR); } public boolean hasStartedOrFinishedShuttingDown() { return isShuttingDown() || hasCompletedShutdown(); } public boolean isValidTransition(final State newState) { return validTransitions.contains(newState.ordinal()); } } private final Object stateLock = new Object(); protected volatile State state = State.CREATED; private boolean waitOnState(final State targetState, final long waitMs) { final long begin = time.milliseconds(); synchronized (stateLock) { boolean interrupted = false; long elapsedMs = 0L; try { while (state != targetState) { if (waitMs > elapsedMs) { final long remainingMs = waitMs - elapsedMs; try { stateLock.wait(remainingMs); } catch (final InterruptedException e) { interrupted = true; } } else { log.debug("Cannot transit to {} within {}ms", targetState, waitMs); return false; } elapsedMs = time.milliseconds() - begin; } } finally { // Make sure to restore the interruption status before returning. // We do not always own the current thread that executes this method, i.e., we do not know the // interruption policy of the thread. The least we can do is restore the interruption status before // the current thread exits this method. if (interrupted) { Thread.currentThread().interrupt(); } } return true; } } /** * Sets the state * @param newState New state */ private boolean setState(final State newState) { final State oldState; synchronized (stateLock) { oldState = state; if (state == State.PENDING_SHUTDOWN && newState != State.NOT_RUNNING) { // when the state is already in PENDING_SHUTDOWN, all other transitions than NOT_RUNNING (due to thread dying) will be // refused but we do not throw exception here, to allow appropriate error handling return false; } else if (state == State.NOT_RUNNING && (newState == State.PENDING_SHUTDOWN || newState == State.NOT_RUNNING)) { // when the state is already in NOT_RUNNING, its transition to PENDING_SHUTDOWN or NOT_RUNNING (due to consecutive close calls) // will be refused but we do not throw exception here, to allow idempotent close calls return false; } else if (state == State.REBALANCING && newState == State.REBALANCING) { // when the state is already in REBALANCING, it should not transit to REBALANCING again return false; } else if (state == State.ERROR && (newState == State.PENDING_ERROR || newState == State.ERROR)) { // when the state is already in ERROR, its transition to PENDING_ERROR or ERROR (due to consecutive close calls) return false; } else if (state == State.PENDING_ERROR && newState != State.ERROR) { // when the state is already in PENDING_ERROR, all other transitions than ERROR (due to thread dying) will be // refused but we do not throw exception here, to allow appropriate error handling return false; } else if (!state.isValidTransition(newState)) { throw new IllegalStateException("Stream-client " + clientId + ": Unexpected state transition from " + oldState + " to " + newState); } else { log.info("State transition from {} to {}", oldState, newState); } state = newState; stateLock.notifyAll(); } // we need to call the user customized state listener outside the state lock to avoid potential deadlocks if (stateListener != null) { stateListener.onChange(newState, oldState); } return true; } /** * Return the current {@link State} of this {@code KafkaStreams} instance. * * @return the current state of this Kafka Streams instance */ public State state() { return state; } protected boolean isRunningOrRebalancing() { synchronized (stateLock) { return state.isRunningOrRebalancing(); } } protected boolean hasStartedOrFinishedShuttingDown() { synchronized (stateLock) { return state.hasStartedOrFinishedShuttingDown(); } } protected void validateIsRunningOrRebalancing() { synchronized (stateLock) { if (state.hasNotStarted()) { throw new StreamsNotStartedException("KafkaStreams has not been started, you can retry after calling start()"); } if (!state.isRunningOrRebalancing()) { throw new IllegalStateException("KafkaStreams is not running. State is " + state + "."); } } } /** * Listen to {@link State} change events. */ public interface StateListener { /** * Called when state changes. * * @param newState new state * @param oldState previous state */ void onChange(final State newState, final State oldState); } /** * An app can set a single {@link KafkaStreams.StateListener} so that the app is notified when state changes. * * @param listener a new state listener * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. */ public void setStateListener(final KafkaStreams.StateListener listener) { synchronized (stateLock) { if (state.hasNotStarted()) { stateListener = listener; } else { throw new IllegalStateException("Can only set StateListener before calling start(). Current state is: " + state); } } } /** * Set the handler invoked when an internal {@link StreamsConfig#NUM_STREAM_THREADS_CONFIG stream thread} abruptly * terminates due to an uncaught exception. * * @param uncaughtExceptionHandler the uncaught exception handler for all internal threads; {@code null} deletes the current handler * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. * * @deprecated Since 2.8.0. Use {@link KafkaStreams#setUncaughtExceptionHandler(StreamsUncaughtExceptionHandler)} instead. * */ @Deprecated public void setUncaughtExceptionHandler(final Thread.UncaughtExceptionHandler uncaughtExceptionHandler) { synchronized (stateLock) { if (state.hasNotStarted()) { oldHandler = true; processStreamThread(thread -> thread.setUncaughtExceptionHandler(uncaughtExceptionHandler)); if (globalStreamThread != null) { globalStreamThread.setUncaughtExceptionHandler(uncaughtExceptionHandler); } } else { throw new IllegalStateException("Can only set UncaughtExceptionHandler before calling start(). " + "Current state is: " + state); } } } /** * Set the handler invoked when an internal {@link StreamsConfig#NUM_STREAM_THREADS_CONFIG stream thread} * throws an unexpected exception. * These might be exceptions indicating rare bugs in Kafka Streams, or they * might be exceptions thrown by your code, for example a NullPointerException thrown from your processor logic. * The handler will execute on the thread that produced the exception. * In order to get the thread that threw the exception, use {@code Thread.currentThread()}. * <p> * Note, this handler must be threadsafe, since it will be shared among all threads, and invoked from any * thread that encounters such an exception. * * @param userStreamsUncaughtExceptionHandler the uncaught exception handler of type {@link StreamsUncaughtExceptionHandler} for all internal threads * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. * @throws NullPointerException if userStreamsUncaughtExceptionHandler is null. */ public void setUncaughtExceptionHandler(final StreamsUncaughtExceptionHandler userStreamsUncaughtExceptionHandler) { synchronized (stateLock) { if (state.hasNotStarted()) { Objects.requireNonNull(userStreamsUncaughtExceptionHandler); streamsUncaughtExceptionHandler = (exception, skipThreadReplacement) -> handleStreamsUncaughtException(exception, userStreamsUncaughtExceptionHandler, skipThreadReplacement); processStreamThread(thread -> thread.setStreamsUncaughtExceptionHandler(streamsUncaughtExceptionHandler)); if (globalStreamThread != null) { globalStreamThread.setUncaughtExceptionHandler( exception -> handleStreamsUncaughtException(exception, userStreamsUncaughtExceptionHandler, false) ); } processStreamThread(thread -> thread.setUncaughtExceptionHandler((t, e) -> { } )); if (globalStreamThread != null) { globalStreamThread.setUncaughtExceptionHandler((t, e) -> { } ); } } else { throw new IllegalStateException("Can only set UncaughtExceptionHandler before calling start(). " + "Current state is: " + state); } } } private void defaultStreamsUncaughtExceptionHandler(final Throwable throwable, final boolean skipThreadReplacement) { if (oldHandler) { threads.remove(Thread.currentThread()); if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } else if (throwable instanceof Error) { throw (Error) throwable; } else { throw new RuntimeException("Unexpected checked exception caught in the uncaught exception handler", throwable); } } else { handleStreamsUncaughtException(throwable, t -> SHUTDOWN_CLIENT, skipThreadReplacement); } } private void replaceStreamThread(final Throwable throwable) { if (globalStreamThread != null && Thread.currentThread().getName().equals(globalStreamThread.getName())) { log.warn("The global thread cannot be replaced. Reverting to shutting down the client."); log.error("Encountered the following exception during processing " + " The streams client is going to shut down now. ", throwable); closeToError(); } final StreamThread deadThread = (StreamThread) Thread.currentThread(); deadThread.shutdown(); addStreamThread(); if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } else if (throwable instanceof Error) { throw (Error) throwable; } else { throw new RuntimeException("Unexpected checked exception caught in the uncaught exception handler", throwable); } } private void handleStreamsUncaughtException(final Throwable throwable, final StreamsUncaughtExceptionHandler streamsUncaughtExceptionHandler, final boolean skipThreadReplacement) { final StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse action = streamsUncaughtExceptionHandler.handle(throwable); if (oldHandler) { log.warn("Stream's new uncaught exception handler is set as well as the deprecated old handler." + "The old handler will be ignored as long as a new handler is set."); } switch (action) { case REPLACE_THREAD: if (!skipThreadReplacement) { log.error("Replacing thread in the streams uncaught exception handler", throwable); replaceStreamThread(throwable); } else { log.debug("Skipping thread replacement for recoverable error"); } break; case SHUTDOWN_CLIENT: log.error("Encountered the following exception during processing " + "and the registered exception handler opted to " + action + "." + " The streams client is going to shut down now. ", throwable); closeToError(); break; case SHUTDOWN_APPLICATION: if (getNumLiveStreamThreads() == 1) { log.warn("Attempt to shut down the application requires adding a thread to communicate the shutdown. No processing will be done on this thread"); addStreamThread(); } if (throwable instanceof Error) { log.error("This option requires running threads to shut down the application." + "but the uncaught exception was an Error, which means this runtime is no " + "longer in a well-defined state. Attempting to send the shutdown command anyway.", throwable); } if (Thread.currentThread().equals(globalStreamThread) && getNumLiveStreamThreads() == 0) { log.error("Exception in global thread caused the application to attempt to shutdown." + " This action will succeed only if there is at least one StreamThread running on this client." + " Currently there are no running threads so will now close the client."); closeToError(); break; } processStreamThread(thread -> thread.sendShutdownRequest(AssignorError.SHUTDOWN_REQUESTED)); log.error("Encountered the following exception during processing " + "and sent shutdown request for the entire application.", throwable); break; } } /** * Set the listener which is triggered whenever a {@link StateStore} is being restored in order to resume * processing. * * @param globalStateRestoreListener The listener triggered when {@link StateStore} is being restored. * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. */ public void setGlobalStateRestoreListener(final StateRestoreListener globalStateRestoreListener) { synchronized (stateLock) { if (state.hasNotStarted()) { delegatingStateRestoreListener.setUserStateRestoreListener(globalStateRestoreListener); } else { throw new IllegalStateException("Can only set GlobalStateRestoreListener before calling start(). " + "Current state is: " + state); } } } /** * Set the listener which is triggered whenever a standby task is updated * * @param standbyListener The listener triggered when a standby task is updated. * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. */ public void setStandbyUpdateListener(final StandbyUpdateListener standbyListener) { synchronized (stateLock) { if (state.hasNotStarted()) { this.delegatingStandbyUpdateListener.setUserStandbyListener(standbyListener); } else { throw new IllegalStateException("Can only set StandbyUpdateListener before calling start(). " + "Current state is: " + state); } } } /** * Get read-only handle on global metrics registry, including streams client's own metrics plus * its embedded producer, consumer and admin clients' metrics. * * @return Map of all metrics. */ public Map<MetricName, ? extends Metric> metrics() { final Map<MetricName, Metric> result = new LinkedHashMap<>(); // producer and consumer clients are per-thread processStreamThread(thread -> { result.putAll(thread.producerMetrics()); result.putAll(thread.consumerMetrics()); // admin client is shared, so we can actually move it // to result.putAll(adminClient.metrics()). // we did it intentionally just for flexibility. result.putAll(thread.adminClientMetrics()); }); // global thread's consumer client if (globalStreamThread != null) { result.putAll(globalStreamThread.consumerMetrics()); } // self streams metrics result.putAll(metrics.metrics()); return Collections.unmodifiableMap(result); } /** * Class that handles stream thread transitions */ final class StreamStateListener implements StreamThread.StateListener { private final Map<Long, StreamThread.State> threadState; private GlobalStreamThread.State globalThreadState; // this lock should always be held before the state lock private final Object threadStatesLock; StreamStateListener(final Map<Long, StreamThread.State> threadState, final GlobalStreamThread.State globalThreadState) { this.threadState = threadState; this.globalThreadState = globalThreadState; this.threadStatesLock = new Object(); } /** * If all threads are up, including the global thread, set to RUNNING */ private void maybeSetRunning() { // state can be transferred to RUNNING if // 1) all threads are either RUNNING or DEAD // 2) thread is pending-shutdown and there are still other threads running final boolean hasRunningThread = threadState.values().stream().anyMatch(s -> s == StreamThread.State.RUNNING); for (final StreamThread.State state : threadState.values()) { if (state == StreamThread.State.PENDING_SHUTDOWN && hasRunningThread) continue; if (state != StreamThread.State.RUNNING && state != StreamThread.State.DEAD) { return; } } // the global state thread is relevant only if it is started. There are cases // when we don't have a global state thread at all, e.g., when we don't have global KTables if (globalThreadState != null && globalThreadState != GlobalStreamThread.State.RUNNING) { return; } setState(State.RUNNING); } @Override public synchronized void onChange(final Thread thread, final ThreadStateTransitionValidator abstractNewState, final ThreadStateTransitionValidator abstractOldState) { synchronized (threadStatesLock) { // StreamThreads first if (thread instanceof StreamThread) { final StreamThread.State newState = (StreamThread.State) abstractNewState; threadState.put(thread.getId(), newState); if (newState == StreamThread.State.PARTITIONS_REVOKED || newState == StreamThread.State.PARTITIONS_ASSIGNED) { setState(State.REBALANCING); } else if (newState == StreamThread.State.RUNNING) { maybeSetRunning(); } } else if (thread instanceof GlobalStreamThread) { // global stream thread has different invariants final GlobalStreamThread.State newState = (GlobalStreamThread.State) abstractNewState; globalThreadState = newState; if (newState == GlobalStreamThread.State.RUNNING) { maybeSetRunning(); } else if (newState == GlobalStreamThread.State.DEAD) { if (state != State.PENDING_SHUTDOWN) { log.error("Global thread has died. The streams application or client will now close to ERROR."); closeToError(); } } } } } } static final class DelegatingStateRestoreListener implements StateRestoreListener { private StateRestoreListener userStateRestoreListener; private void throwOnFatalException(final Exception fatalUserException, final TopicPartition topicPartition, final String storeName) { throw new StreamsException( String.format("Fatal user code error in store restore listener for store %s, partition %s.", storeName, topicPartition), fatalUserException); } void setUserStateRestoreListener(final StateRestoreListener userStateRestoreListener) { this.userStateRestoreListener = userStateRestoreListener; } @Override public void onRestoreStart(final TopicPartition topicPartition, final String storeName, final long startingOffset, final long endingOffset) { if (userStateRestoreListener != null) { try { userStateRestoreListener.onRestoreStart(topicPartition, storeName, startingOffset, endingOffset); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } @Override public void onBatchRestored(final TopicPartition topicPartition, final String storeName, final long batchEndOffset, final long numRestored) { if (userStateRestoreListener != null) { try { userStateRestoreListener.onBatchRestored(topicPartition, storeName, batchEndOffset, numRestored); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } @Override public void onRestoreEnd(final TopicPartition topicPartition, final String storeName, final long totalRestored) { if (userStateRestoreListener != null) { try { userStateRestoreListener.onRestoreEnd(topicPartition, storeName, totalRestored); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } @Override public void onRestoreSuspended(final TopicPartition topicPartition, final String storeName, final long totalRestored) { if (userStateRestoreListener != null) { try { userStateRestoreListener.onRestoreSuspended(topicPartition, storeName, totalRestored); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } } final static class DelegatingStandbyUpdateListener implements StandbyUpdateListener { private StandbyUpdateListener userStandbyListener; private void throwOnFatalException(final Exception fatalUserException, final TopicPartition topicPartition, final String storeName) { throw new StreamsException( String.format("Fatal user code error in standby update listener for store %s, partition %s.", storeName, topicPartition), fatalUserException); } @Override public void onUpdateStart(final TopicPartition topicPartition, final String storeName, final long startingOffset) { if (userStandbyListener != null) { try { userStandbyListener.onUpdateStart(topicPartition, storeName, startingOffset); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } @Override public void onBatchLoaded(final TopicPartition topicPartition, final String storeName, final TaskId taskId, final long batchEndOffset, final long batchSize, final long currentEndOffset) { if (userStandbyListener != null) { try { userStandbyListener.onBatchLoaded(topicPartition, storeName, taskId, batchEndOffset, batchSize, currentEndOffset); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } @Override public void onUpdateSuspended(final TopicPartition topicPartition, final String storeName, final long storeOffset, final long currentEndOffset, final SuspendReason reason) { if (userStandbyListener != null) { try { userStandbyListener.onUpdateSuspended(topicPartition, storeName, storeOffset, currentEndOffset, reason); } catch (final Exception fatalUserException) { throwOnFatalException(fatalUserException, topicPartition, storeName); } } } void setUserStandbyListener(final StandbyUpdateListener userStandbyListener) { this.userStandbyListener = userStandbyListener; } } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param props properties for {@link StreamsConfig} * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final Properties props) { this(topology, new StreamsConfig(props)); } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param props properties for {@link StreamsConfig} * @param clientSupplier the Kafka clients supplier which provides underlying producer and consumer clients * for the new {@code KafkaStreams} instance * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final Properties props, final KafkaClientSupplier clientSupplier) { this(topology, new StreamsConfig(props), clientSupplier, Time.SYSTEM); } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param props properties for {@link StreamsConfig} * @param time {@code Time} implementation; cannot be null * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final Properties props, final Time time) { this(topology, new StreamsConfig(props), time); } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param props properties for {@link StreamsConfig} * @param clientSupplier the Kafka clients supplier which provides underlying producer and consumer clients * for the new {@code KafkaStreams} instance * @param time {@code Time} implementation; cannot be null * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final Properties props, final KafkaClientSupplier clientSupplier, final Time time) { this(topology, new StreamsConfig(props), clientSupplier, time); } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param applicationConfigs configs for Kafka Streams * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final StreamsConfig applicationConfigs) { this(topology, applicationConfigs, applicationConfigs.getKafkaClientSupplier()); } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param applicationConfigs configs for Kafka Streams * @param clientSupplier the Kafka clients supplier which provides underlying producer and consumer clients * for the new {@code KafkaStreams} instance * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final StreamsConfig applicationConfigs, final KafkaClientSupplier clientSupplier) { this(new TopologyMetadata(topology.internalTopologyBuilder, applicationConfigs), applicationConfigs, clientSupplier); } /** * Create a {@code KafkaStreams} instance. * <p> * Note: even if you never call {@link #start()} on a {@code KafkaStreams} instance, * you still must {@link #close()} it to avoid resource leaks. * * @param topology the topology specifying the computational logic * @param applicationConfigs configs for Kafka Streams * @param time {@code Time} implementation; cannot be null * @throws StreamsException if any fatal error occurs */ public KafkaStreams(final Topology topology, final StreamsConfig applicationConfigs, final Time time) { this(new TopologyMetadata(topology.internalTopologyBuilder, applicationConfigs), applicationConfigs, applicationConfigs.getKafkaClientSupplier(), time); } private KafkaStreams(final Topology topology, final StreamsConfig applicationConfigs, final KafkaClientSupplier clientSupplier, final Time time) throws StreamsException { this(new TopologyMetadata(topology.internalTopologyBuilder, applicationConfigs), applicationConfigs, clientSupplier, time); } protected KafkaStreams(final TopologyMetadata topologyMetadata, final StreamsConfig applicationConfigs, final KafkaClientSupplier clientSupplier) throws StreamsException { this(topologyMetadata, applicationConfigs, clientSupplier, Time.SYSTEM); } @SuppressWarnings("this-escape") private KafkaStreams(final TopologyMetadata topologyMetadata, final StreamsConfig applicationConfigs, final KafkaClientSupplier clientSupplier, final Time time) throws StreamsException { this.applicationConfigs = applicationConfigs; this.time = time; this.topologyMetadata = topologyMetadata; this.topologyMetadata.buildAndRewriteTopology(); final boolean hasGlobalTopology = topologyMetadata.hasGlobalTopology(); try { stateDirectory = new StateDirectory(applicationConfigs, time, topologyMetadata.hasPersistentStores(), topologyMetadata.hasNamedTopologies()); processId = stateDirectory.initializeProcessId(); } catch (final ProcessorStateException fatal) { Utils.closeQuietly(stateDirectory, "streams state directory"); throw new StreamsException(fatal); } // The application ID is a required config and hence should always have value final String userClientId = applicationConfigs.getString(StreamsConfig.CLIENT_ID_CONFIG); final String applicationId = applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG); if (userClientId.length() <= 0) { clientId = applicationId + "-" + processId; } else { clientId = userClientId; } final LogContext logContext = new LogContext(String.format("stream-client [%s] ", clientId)); this.log = logContext.logger(getClass()); topologyMetadata.setLog(logContext); // use client id instead of thread client id since this admin client may be shared among threads this.clientSupplier = clientSupplier; adminClient = clientSupplier.getAdmin(applicationConfigs.getAdminConfigs(ClientUtils.getSharedAdminClientId(clientId))); log.info("Kafka Streams version: {}", ClientMetrics.version()); log.info("Kafka Streams commit ID: {}", ClientMetrics.commitId()); metrics = getMetrics(applicationConfigs, time, clientId); streamsMetrics = new StreamsMetricsImpl( metrics, clientId, applicationConfigs.getString(StreamsConfig.BUILT_IN_METRICS_VERSION_CONFIG), time ); ClientMetrics.addVersionMetric(streamsMetrics); ClientMetrics.addCommitIdMetric(streamsMetrics); ClientMetrics.addApplicationIdMetric(streamsMetrics, applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG)); ClientMetrics.addTopologyDescriptionMetric(streamsMetrics, (metricsConfig, now) -> this.topologyMetadata.topologyDescriptionString()); ClientMetrics.addStateMetric(streamsMetrics, (metricsConfig, now) -> state); threads = Collections.synchronizedList(new LinkedList<>()); ClientMetrics.addNumAliveStreamThreadMetric(streamsMetrics, (metricsConfig, now) -> getNumLiveStreamThreads()); streamsMetadataState = new StreamsMetadataState( this.topologyMetadata, parseHostInfo(applicationConfigs.getString(StreamsConfig.APPLICATION_SERVER_CONFIG)), logContext ); oldHandler = false; streamsUncaughtExceptionHandler = this::defaultStreamsUncaughtExceptionHandler; delegatingStateRestoreListener = new DelegatingStateRestoreListener(); delegatingStandbyUpdateListener = new DelegatingStandbyUpdateListener(); totalCacheSize = getTotalCacheSize(applicationConfigs); final int numStreamThreads = topologyMetadata.getNumStreamThreads(applicationConfigs); final long cacheSizePerThread = getCacheSizePerThread(numStreamThreads); GlobalStreamThread.State globalThreadState = null; if (hasGlobalTopology) { final String globalThreadId = clientId + "-GlobalStreamThread"; globalStreamThread = new GlobalStreamThread( topologyMetadata.globalTaskTopology(), applicationConfigs, clientSupplier.getGlobalConsumer(applicationConfigs.getGlobalConsumerConfigs(clientId)), stateDirectory, cacheSizePerThread, streamsMetrics, time, globalThreadId, delegatingStateRestoreListener, exception -> defaultStreamsUncaughtExceptionHandler(exception, false) ); globalThreadState = globalStreamThread.state(); } threadState = new HashMap<>(numStreamThreads); streamStateListener = new StreamStateListener(threadState, globalThreadState); final GlobalStateStoreProvider globalStateStoreProvider = new GlobalStateStoreProvider(this.topologyMetadata.globalStateStores()); if (hasGlobalTopology) { globalStreamThread.setStateListener(streamStateListener); } queryableStoreProvider = new QueryableStoreProvider(globalStateStoreProvider); for (int i = 1; i <= numStreamThreads; i++) { createAndAddStreamThread(cacheSizePerThread, i); } stateDirCleaner = setupStateDirCleaner(); rocksDBMetricsRecordingService = maybeCreateRocksDBMetricsRecordingService(clientId, applicationConfigs); } private StreamThread createAndAddStreamThread(final long cacheSizePerThread, final int threadIdx) { final StreamThread streamThread = StreamThread.create( topologyMetadata, applicationConfigs, clientSupplier, adminClient, processId, clientId, streamsMetrics, time, streamsMetadataState, cacheSizePerThread, stateDirectory, delegatingStateRestoreListener, delegatingStandbyUpdateListener, threadIdx, KafkaStreams.this::closeToError, streamsUncaughtExceptionHandler ); streamThread.setStateListener(streamStateListener); threads.add(streamThread); threadState.put(streamThread.getId(), streamThread.state()); queryableStoreProvider.addStoreProviderForThread(streamThread.getName(), new StreamThreadStateStoreProvider(streamThread)); return streamThread; } static Metrics getMetrics(final StreamsConfig config, final Time time, final String clientId) { final MetricConfig metricConfig = new MetricConfig() .samples(config.getInt(StreamsConfig.METRICS_NUM_SAMPLES_CONFIG)) .recordLevel(Sensor.RecordingLevel.forName(config.getString(StreamsConfig.METRICS_RECORDING_LEVEL_CONFIG))) .timeWindow(config.getLong(StreamsConfig.METRICS_SAMPLE_WINDOW_MS_CONFIG), TimeUnit.MILLISECONDS); final List<MetricsReporter> reporters = CommonClientConfigs.metricsReporters(clientId, config); final MetricsContext metricsContext = new KafkaMetricsContext(JMX_PREFIX, config.originalsWithPrefix(CommonClientConfigs.METRICS_CONTEXT_PREFIX)); return new Metrics(metricConfig, reporters, time, metricsContext); } /** * Adds and starts a stream thread in addition to the stream threads that are already running in this * Kafka Streams client. * <p> * Since the number of stream threads increases, the sizes of the caches in the new stream thread * and the existing stream threads are adapted so that the sum of the cache sizes over all stream * threads does not exceed the total cache size specified in configuration * {@link StreamsConfig#STATESTORE_CACHE_MAX_BYTES_CONFIG}. * <p> * Stream threads can only be added if this Kafka Streams client is in state RUNNING or REBALANCING. * * @return name of the added stream thread or empty if a new stream thread could not be added */ public Optional<String> addStreamThread() { if (isRunningOrRebalancing()) { final StreamThread streamThread; synchronized (changeThreadCount) { final int threadIdx = getNextThreadIndex(); final int numLiveThreads = getNumLiveStreamThreads(); final long cacheSizePerThread = getCacheSizePerThread(numLiveThreads + 1); log.info("Adding StreamThread-{}, there will now be {} live threads and the new cache size per thread is {}", threadIdx, numLiveThreads + 1, cacheSizePerThread); resizeThreadCache(cacheSizePerThread); // Creating thread should hold the lock in order to avoid duplicate thread index. // If the duplicate index happen, the metadata of thread may be duplicate too. streamThread = createAndAddStreamThread(cacheSizePerThread, threadIdx); } synchronized (stateLock) { if (isRunningOrRebalancing()) { streamThread.start(); return Optional.of(streamThread.getName()); } else { log.warn("Terminating the new thread because the Kafka Streams client is in state {}", state); streamThread.shutdown(); threads.remove(streamThread); final long cacheSizePerThread = getCacheSizePerThread(getNumLiveStreamThreads()); log.info("Resizing thread cache due to terminating added thread, new cache size per thread is {}", cacheSizePerThread); resizeThreadCache(cacheSizePerThread); return Optional.empty(); } } } else { log.warn("Cannot add a stream thread when Kafka Streams client is in state {}", state); return Optional.empty(); } } /** * Removes one stream thread out of the running stream threads from this Kafka Streams client. * <p> * The removed stream thread is gracefully shut down. This method does not specify which stream * thread is shut down. * <p> * Since the number of stream threads decreases, the sizes of the caches in the remaining stream * threads are adapted so that the sum of the cache sizes over all stream threads equals the total * cache size specified in configuration {@link StreamsConfig#STATESTORE_CACHE_MAX_BYTES_CONFIG}. * * @return name of the removed stream thread or empty if a stream thread could not be removed because * no stream threads are alive */ public Optional<String> removeStreamThread() { return removeStreamThread(Long.MAX_VALUE); } /** * Removes one stream thread out of the running stream threads from this Kafka Streams client. * <p> * The removed stream thread is gracefully shut down. This method does not specify which stream * thread is shut down. * <p> * Since the number of stream threads decreases, the sizes of the caches in the remaining stream * threads are adapted so that the sum of the cache sizes over all stream threads equals the total * cache size specified in configuration {@link StreamsConfig#STATESTORE_CACHE_MAX_BYTES_CONFIG}. * * @param timeout The length of time to wait for the thread to shut down * @throws org.apache.kafka.common.errors.TimeoutException if the thread does not stop in time * @return name of the removed stream thread or empty if a stream thread could not be removed because * no stream threads are alive */ public Optional<String> removeStreamThread(final Duration timeout) { final String msgPrefix = prepareMillisCheckFailMsgPrefix(timeout, "timeout"); final long timeoutMs = validateMillisecondDuration(timeout, msgPrefix); return removeStreamThread(timeoutMs); } private Optional<String> removeStreamThread(final long timeoutMs) throws TimeoutException { final long startMs = time.milliseconds(); if (isRunningOrRebalancing()) { synchronized (changeThreadCount) { // make a copy of threads to avoid holding lock for (final StreamThread streamThread : new ArrayList<>(threads)) { final boolean callingThreadIsNotCurrentStreamThread = !streamThread.getName().equals(Thread.currentThread().getName()); if (streamThread.isThreadAlive() && (callingThreadIsNotCurrentStreamThread || getNumLiveStreamThreads() == 1)) { log.info("Removing StreamThread " + streamThread.getName()); final Optional<String> groupInstanceID = streamThread.getGroupInstanceID(); streamThread.requestLeaveGroupDuringShutdown(); streamThread.shutdown(); if (!streamThread.getName().equals(Thread.currentThread().getName())) { final long remainingTimeMs = timeoutMs - (time.milliseconds() - startMs); if (remainingTimeMs <= 0 || !streamThread.waitOnThreadState(StreamThread.State.DEAD, remainingTimeMs)) { log.warn("{} did not shutdown in the allotted time.", streamThread.getName()); // Don't remove from threads until shutdown is complete. We will trim it from the // list once it reaches DEAD, and if for some reason it's hanging indefinitely in the // shutdown then we should just consider this thread.id to be burned } else { log.info("Successfully removed {} in {}ms", streamThread.getName(), time.milliseconds() - startMs); threads.remove(streamThread); queryableStoreProvider.removeStoreProviderForThread(streamThread.getName()); } } else { log.info("{} is the last remaining thread and must remove itself, therefore we cannot wait " + "for it to complete shutdown as this will result in deadlock.", streamThread.getName()); } final long cacheSizePerThread = getCacheSizePerThread(getNumLiveStreamThreads()); log.info("Resizing thread cache due to thread removal, new cache size per thread is {}", cacheSizePerThread); resizeThreadCache(cacheSizePerThread); if (groupInstanceID.isPresent() && callingThreadIsNotCurrentStreamThread) { final MemberToRemove memberToRemove = new MemberToRemove(groupInstanceID.get()); final Collection<MemberToRemove> membersToRemove = Collections.singletonList(memberToRemove); final RemoveMembersFromConsumerGroupResult removeMembersFromConsumerGroupResult = adminClient.removeMembersFromConsumerGroup( applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG), new RemoveMembersFromConsumerGroupOptions(membersToRemove) ); try { final long remainingTimeMs = timeoutMs - (time.milliseconds() - startMs); removeMembersFromConsumerGroupResult.memberResult(memberToRemove).get(remainingTimeMs, TimeUnit.MILLISECONDS); } catch (final java.util.concurrent.TimeoutException exception) { log.error( String.format( "Could not remove static member %s from consumer group %s due to a timeout:", groupInstanceID.get(), applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG) ), exception ); throw new TimeoutException(exception.getMessage(), exception); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } catch (final ExecutionException exception) { log.error( String.format( "Could not remove static member %s from consumer group %s due to:", groupInstanceID.get(), applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG) ), exception ); throw new StreamsException( "Could not remove static member " + groupInstanceID.get() + " from consumer group " + applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG) + " for the following reason: ", exception.getCause() ); } } final long remainingTimeMs = timeoutMs - (time.milliseconds() - startMs); if (remainingTimeMs <= 0) { throw new TimeoutException("Thread " + streamThread.getName() + " did not stop in the allotted time"); } return Optional.of(streamThread.getName()); } } } log.warn("There are no threads eligible for removal"); } else { log.warn("Cannot remove a stream thread when Kafka Streams client is in state " + state()); } return Optional.empty(); } /* * Takes a snapshot and counts the number of stream threads which are not in PENDING_SHUTDOWN or DEAD * * note: iteration over SynchronizedList is not thread safe so it must be manually synchronized. However, we may * require other locks when looping threads and it could cause deadlock. Hence, we create a copy to avoid holding * threads lock when looping threads. * @return number of alive stream threads */ private int getNumLiveStreamThreads() { final AtomicInteger numLiveThreads = new AtomicInteger(0); synchronized (threads) { processStreamThread(thread -> { if (thread.state() == StreamThread.State.DEAD) { log.debug("Trimming thread {} from the threads list since it's state is {}", thread.getName(), StreamThread.State.DEAD); threads.remove(thread); } else if (thread.state() == StreamThread.State.PENDING_SHUTDOWN) { log.debug("Skipping thread {} from num live threads computation since it's state is {}", thread.getName(), StreamThread.State.PENDING_SHUTDOWN); } else { numLiveThreads.incrementAndGet(); } }); return numLiveThreads.get(); } } private int getNextThreadIndex() { final HashSet<String> allLiveThreadNames = new HashSet<>(); final AtomicInteger maxThreadId = new AtomicInteger(1); synchronized (threads) { processStreamThread(thread -> { // trim any DEAD threads from the list so we can reuse the thread.id // this is only safe to do once the thread has fully completed shutdown if (thread.state() == StreamThread.State.DEAD) { threads.remove(thread); } else { allLiveThreadNames.add(thread.getName()); // Assume threads are always named with the "-StreamThread-<threadId>" suffix final int threadId = Integer.parseInt(thread.getName().substring(thread.getName().lastIndexOf("-") + 1)); if (threadId > maxThreadId.get()) { maxThreadId.set(threadId); } } }); final String baseName = clientId + "-StreamThread-"; for (int i = 1; i <= maxThreadId.get(); i++) { final String name = baseName + i; if (!allLiveThreadNames.contains(name)) { return i; } } // It's safe to use threads.size() rather than getNumLiveStreamThreads() to infer the number of threads // here since we trimmed any DEAD threads earlier in this method while holding the lock return threads.size() + 1; } } private long getCacheSizePerThread(final int numStreamThreads) { if (numStreamThreads == 0) { return totalCacheSize; } return totalCacheSize / (numStreamThreads + (topologyMetadata.hasGlobalTopology() ? 1 : 0)); } private void resizeThreadCache(final long cacheSizePerThread) { processStreamThread(thread -> thread.resizeCache(cacheSizePerThread)); if (globalStreamThread != null) { globalStreamThread.resize(cacheSizePerThread); } } private ScheduledExecutorService setupStateDirCleaner() { return Executors.newSingleThreadScheduledExecutor(r -> { final Thread thread = new Thread(r, clientId + "-CleanupThread"); thread.setDaemon(true); return thread; }); } private static ScheduledExecutorService maybeCreateRocksDBMetricsRecordingService(final String clientId, final StreamsConfig config) { if (RecordingLevel.forName(config.getString(StreamsConfig.METRICS_RECORDING_LEVEL_CONFIG)) == RecordingLevel.DEBUG) { return Executors.newSingleThreadScheduledExecutor(r -> { final Thread thread = new Thread(r, clientId + "-RocksDBMetricsRecordingTrigger"); thread.setDaemon(true); return thread; }); } return null; } private static HostInfo parseHostInfo(final String endPoint) { final HostInfo hostInfo = HostInfo.buildFromEndpoint(endPoint); if (hostInfo == null) { return StreamsMetadataState.UNKNOWN_HOST; } else { return hostInfo; } } /** * Start the {@code KafkaStreams} instance by starting all its threads. * This function is expected to be called only once during the life cycle of the client. * <p> * Because threads are started in the background, this method does not block. * However, if you have global stores in your topology, this method blocks until all global stores are restored. * As a consequence, any fatal exception that happens during processing is by default only logged. * If you want to be notified about dying threads, you can * {@link #setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler) register an uncaught exception handler} * before starting the {@code KafkaStreams} instance. * <p> * Note, for brokers with version {@code 0.9.x} or lower, the broker version cannot be checked. * There will be no error and the client will hang and retry to verify the broker version until it * {@link StreamsConfig#REQUEST_TIMEOUT_MS_CONFIG times out}. * @throws IllegalStateException if process was already started * @throws StreamsException if the Kafka brokers have version 0.10.0.x or * if {@link StreamsConfig#PROCESSING_GUARANTEE_CONFIG exactly-once} is enabled for pre 0.11.0.x brokers */ public synchronized void start() throws IllegalStateException, StreamsException { if (setState(State.REBALANCING)) { log.debug("Starting Streams client"); if (globalStreamThread != null) { globalStreamThread.start(); } final int numThreads = processStreamThread(StreamThread::start); log.info("Started {} stream threads", numThreads); final Long cleanupDelay = applicationConfigs.getLong(StreamsConfig.STATE_CLEANUP_DELAY_MS_CONFIG); stateDirCleaner.scheduleAtFixedRate(() -> { // we do not use lock here since we only read on the value and act on it if (state == State.RUNNING) { stateDirectory.cleanRemovedTasks(cleanupDelay); } }, cleanupDelay, cleanupDelay, TimeUnit.MILLISECONDS); final long recordingDelay = 0; final long recordingInterval = 1; if (rocksDBMetricsRecordingService != null) { rocksDBMetricsRecordingService.scheduleAtFixedRate( streamsMetrics.rocksDBMetricsRecordingTrigger(), recordingDelay, recordingInterval, TimeUnit.MINUTES ); } } else { throw new IllegalStateException("The client is either already started or already stopped, cannot re-start"); } } /** * Class that handles options passed in case of {@code KafkaStreams} instance scale down */ public static class CloseOptions { private Duration timeout = Duration.ofMillis(Long.MAX_VALUE); private boolean leaveGroup = false; public CloseOptions timeout(final Duration timeout) { this.timeout = timeout; return this; } public CloseOptions leaveGroup(final boolean leaveGroup) { this.leaveGroup = leaveGroup; return this; } } /** * Shutdown this {@code KafkaStreams} instance by signaling all the threads to stop, and then wait for them to join. * This will block until all threads have stopped. */ public void close() { close(Long.MAX_VALUE, false); } private Thread shutdownHelper(final boolean error, final long timeoutMs, final boolean leaveGroup) { stateDirCleaner.shutdownNow(); if (rocksDBMetricsRecordingService != null) { rocksDBMetricsRecordingService.shutdownNow(); } // wait for all threads to join in a separate thread; // save the current thread so that if it is a stream thread // we don't attempt to join it and cause a deadlock return new Thread(() -> { // notify all the threads to stop; avoid deadlocks by stopping any // further state reports from the thread since we're shutting down int numStreamThreads = processStreamThread(StreamThread::shutdown); log.info("Shutting down {} stream threads", numStreamThreads); topologyMetadata.wakeupThreads(); numStreamThreads = processStreamThread(thread -> { try { if (!thread.isRunning()) { log.debug("Shutdown {} complete", thread.getName()); thread.join(); } } catch (final InterruptedException ex) { log.warn("Shutdown {} interrupted", thread.getName()); Thread.currentThread().interrupt(); } }); if (leaveGroup) { processStreamThread(streamThreadLeaveConsumerGroup(timeoutMs)); } log.info("Shutdown {} stream threads complete", numStreamThreads); if (globalStreamThread != null) { log.info("Shutting down the global stream threads"); globalStreamThread.shutdown(); } if (globalStreamThread != null && !globalStreamThread.stillRunning()) { try { globalStreamThread.join(); } catch (final InterruptedException e) { log.warn("Shutdown the global stream thread interrupted"); Thread.currentThread().interrupt(); } globalStreamThread = null; log.info("Shutdown global stream threads complete"); } stateDirectory.close(); adminClient.close(); streamsMetrics.removeAllClientLevelSensorsAndMetrics(); metrics.close(); if (!error) { setState(State.NOT_RUNNING); } else { setState(State.ERROR); } }, clientId + "-CloseThread"); } private boolean close(final long timeoutMs, final boolean leaveGroup) { if (state.hasCompletedShutdown()) { log.info("Streams client is already in the terminal {} state, all resources are closed and the client has stopped.", state); return true; } if (state.isShuttingDown()) { log.info("Streams client is in {}, all resources are being closed and the client will be stopped.", state); if (state == State.PENDING_ERROR && waitOnState(State.ERROR, timeoutMs)) { log.info("Streams client stopped to ERROR completely"); return true; } else if (state == State.PENDING_SHUTDOWN && waitOnState(State.NOT_RUNNING, timeoutMs)) { log.info("Streams client stopped to NOT_RUNNING completely"); return true; } else { log.warn("Streams client cannot transition to {} completely within the timeout", state == State.PENDING_SHUTDOWN ? State.NOT_RUNNING : State.ERROR); return false; } } if (!setState(State.PENDING_SHUTDOWN)) { // if we can't transition to PENDING_SHUTDOWN but not because we're already shutting down, then it must be fatal log.error("Failed to transition to PENDING_SHUTDOWN, current state is {}", state); throw new StreamsException("Failed to shut down while in state " + state); } else { final Thread shutdownThread = shutdownHelper(false, timeoutMs, leaveGroup); shutdownThread.setDaemon(true); shutdownThread.start(); } if (waitOnState(State.NOT_RUNNING, timeoutMs)) { log.info("Streams client stopped completely"); return true; } else { log.info("Streams client cannot stop completely within the {}ms timeout", timeoutMs); return false; } } private void closeToError() { if (!setState(State.PENDING_ERROR)) { log.info("Skipping shutdown since we are already in " + state()); } else { final Thread shutdownThread = shutdownHelper(true, -1, false); shutdownThread.setDaemon(true); shutdownThread.start(); } } /** * Shutdown this {@code KafkaStreams} by signaling all the threads to stop, and then wait up to the timeout for the * threads to join. * A {@code timeout} of Duration.ZERO (or any other zero duration) makes the close operation asynchronous. * Negative-duration timeouts are rejected. * * @param timeout how long to wait for the threads to shutdown * @return {@code true} if all threads were successfully stopped&mdash;{@code false} if the timeout was reached * before all threads stopped * Note that this method must not be called in the {@link StateListener#onChange(KafkaStreams.State, KafkaStreams.State)} callback of {@link StateListener}. * @throws IllegalArgumentException if {@code timeout} can't be represented as {@code long milliseconds} */ public synchronized boolean close(final Duration timeout) throws IllegalArgumentException { final String msgPrefix = prepareMillisCheckFailMsgPrefix(timeout, "timeout"); final long timeoutMs = validateMillisecondDuration(timeout, msgPrefix); if (timeoutMs < 0) { throw new IllegalArgumentException("Timeout can't be negative."); } log.debug("Stopping Streams client with timeoutMillis = {} ms.", timeoutMs); return close(timeoutMs, false); } /** * Shutdown this {@code KafkaStreams} by signaling all the threads to stop, and then wait up to the timeout for the * threads to join. * @param options contains timeout to specify how long to wait for the threads to shutdown, and a flag leaveGroup to * trigger consumer leave call * @return {@code true} if all threads were successfully stopped&mdash;{@code false} if the timeout was reached * before all threads stopped * Note that this method must not be called in the {@link StateListener#onChange(KafkaStreams.State, KafkaStreams.State)} callback of {@link StateListener}. * @throws IllegalArgumentException if {@code timeout} can't be represented as {@code long milliseconds} */ public synchronized boolean close(final CloseOptions options) throws IllegalArgumentException { Objects.requireNonNull(options, "options cannot be null"); final String msgPrefix = prepareMillisCheckFailMsgPrefix(options.timeout, "timeout"); final long timeoutMs = validateMillisecondDuration(options.timeout, msgPrefix); if (timeoutMs < 0) { throw new IllegalArgumentException("Timeout can't be negative."); } log.debug("Stopping Streams client with timeoutMillis = {} ms.", timeoutMs); return close(timeoutMs, options.leaveGroup); } private Consumer<StreamThread> streamThreadLeaveConsumerGroup(final long remainingTimeMs) { return thread -> { final Optional<String> groupInstanceId = thread.getGroupInstanceID(); if (groupInstanceId.isPresent()) { log.debug("Sending leave group trigger to removing instance from consumer group: {}.", groupInstanceId.get()); final MemberToRemove memberToRemove = new MemberToRemove(groupInstanceId.get()); final Collection<MemberToRemove> membersToRemove = Collections.singletonList(memberToRemove); final RemoveMembersFromConsumerGroupResult removeMembersFromConsumerGroupResult = adminClient .removeMembersFromConsumerGroup( applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG), new RemoveMembersFromConsumerGroupOptions(membersToRemove) ); try { removeMembersFromConsumerGroupResult.memberResult(memberToRemove) .get(remainingTimeMs, TimeUnit.MILLISECONDS); } catch (final Exception e) { final String msg = String.format("Could not remove static member %s from consumer group %s.", groupInstanceId.get(), applicationConfigs.getString(StreamsConfig.APPLICATION_ID_CONFIG)); log.error(msg, e); } } }; } /** * Do a clean up of the local {@link StateStore} directory ({@link StreamsConfig#STATE_DIR_CONFIG}) by deleting all * data with regard to the {@link StreamsConfig#APPLICATION_ID_CONFIG application ID}. * <p> * May only be called either before this {@code KafkaStreams} instance is {@link #start() started} or after the * instance is {@link #close() closed}. * <p> * Calling this method triggers a restore of local {@link StateStore}s on the next {@link #start() application start}. * * @throws IllegalStateException if this {@code KafkaStreams} instance has been started and hasn't fully shut down * @throws StreamsException if cleanup failed */ public void cleanUp() { if (!(state.hasNotStarted() || state.hasCompletedShutdown())) { throw new IllegalStateException("Cannot clean up while running."); } stateDirectory.clean(); } /** * Find all currently running {@code KafkaStreams} instances (potentially remotely) that use the same * {@link StreamsConfig#APPLICATION_ID_CONFIG application ID} as this instance (i.e., all instances that belong to * the same Kafka Streams application) and return {@link StreamsMetadata} for each discovered instance. * <p> * Note: this is a point in time view and it may change due to partition reassignment. * * @return {@link StreamsMetadata} for each {@code KafkaStreams} instances of this application * @deprecated since 3.0.0 use {@link KafkaStreams#metadataForAllStreamsClients} */ @Deprecated public Collection<org.apache.kafka.streams.state.StreamsMetadata> allMetadata() { validateIsRunningOrRebalancing(); return streamsMetadataState.getAllMetadata().stream().map(streamsMetadata -> new org.apache.kafka.streams.state.StreamsMetadata(streamsMetadata.hostInfo(), streamsMetadata.stateStoreNames(), streamsMetadata.topicPartitions(), streamsMetadata.standbyStateStoreNames(), streamsMetadata.standbyTopicPartitions())) .collect(Collectors.toSet()); } /** * Find all currently running {@code KafkaStreams} instances (potentially remotely) that use the same * {@link StreamsConfig#APPLICATION_ID_CONFIG application ID} as this instance (i.e., all instances that belong to * the same Kafka Streams application) and return {@link StreamsMetadata} for each discovered instance. * <p> * Note: this is a point in time view and it may change due to partition reassignment. * * @return {@link StreamsMetadata} for each {@code KafkaStreams} instances of this application */ public Collection<StreamsMetadata> metadataForAllStreamsClients() { validateIsRunningOrRebalancing(); return streamsMetadataState.getAllMetadata(); } /** * Find all currently running {@code KafkaStreams} instances (potentially remotely) that * <ul> * <li>use the same {@link StreamsConfig#APPLICATION_ID_CONFIG application ID} as this instance (i.e., all * instances that belong to the same Kafka Streams application)</li> * <li>and that contain a {@link StateStore} with the given {@code storeName}</li> * </ul> * and return {@link StreamsMetadata} for each discovered instance. * <p> * Note: this is a point in time view and it may change due to partition reassignment. * * @param storeName the {@code storeName} to find metadata for * @return {@link StreamsMetadata} for each {@code KafkaStreams} instances with the provide {@code storeName} of * this application * @deprecated since 3.0.0 use {@link KafkaStreams#streamsMetadataForStore} instead */ @Deprecated public Collection<org.apache.kafka.streams.state.StreamsMetadata> allMetadataForStore(final String storeName) { validateIsRunningOrRebalancing(); return streamsMetadataState.getAllMetadataForStore(storeName).stream().map(streamsMetadata -> new org.apache.kafka.streams.state.StreamsMetadata(streamsMetadata.hostInfo(), streamsMetadata.stateStoreNames(), streamsMetadata.topicPartitions(), streamsMetadata.standbyStateStoreNames(), streamsMetadata.standbyTopicPartitions())) .collect(Collectors.toSet()); } /** * Find all currently running {@code KafkaStreams} instances (potentially remotely) that * <ul> * <li>use the same {@link StreamsConfig#APPLICATION_ID_CONFIG application ID} as this instance (i.e., all * instances that belong to the same Kafka Streams application)</li> * <li>and that contain a {@link StateStore} with the given {@code storeName}</li> * </ul> * and return {@link StreamsMetadata} for each discovered instance. * <p> * Note: this is a point in time view and it may change due to partition reassignment. * * @param storeName the {@code storeName} to find metadata for * @return {@link StreamsMetadata} for each {@code KafkaStreams} instances with the provide {@code storeName} of * this application */ public Collection<StreamsMetadata> streamsMetadataForStore(final String storeName) { validateIsRunningOrRebalancing(); return streamsMetadataState.getAllMetadataForStore(storeName); } /** * Finds the metadata containing the active hosts and standby hosts where the key being queried would reside. * * @param storeName the {@code storeName} to find metadata for * @param key the key to find metadata for * @param keySerializer serializer for the key * @param <K> key type * Returns {@link KeyQueryMetadata} containing all metadata about hosting the given key for the given store, * or {@code null} if no matching metadata could be found. */ public <K> KeyQueryMetadata queryMetadataForKey(final String storeName, final K key, final Serializer<K> keySerializer) { validateIsRunningOrRebalancing(); return streamsMetadataState.getKeyQueryMetadataForKey(storeName, key, keySerializer); } /** * Finds the metadata containing the active hosts and standby hosts where the key being queried would reside. * * @param storeName the {@code storeName} to find metadata for * @param key the key to find metadata for * @param partitioner the partitioner to be use to locate the host for the key * @param <K> key type * Returns {@link KeyQueryMetadata} containing all metadata about hosting the given key for the given store, using the * the supplied partitioner, or {@code null} if no matching metadata could be found. */ public <K> KeyQueryMetadata queryMetadataForKey(final String storeName, final K key, final StreamPartitioner<? super K, ?> partitioner) { validateIsRunningOrRebalancing(); return streamsMetadataState.getKeyQueryMetadataForKey(storeName, key, partitioner); } /** * Get a facade wrapping the local {@link StateStore} instances with the provided {@link StoreQueryParameters}. * The returned object can be used to query the {@link StateStore} instances. * * @param storeQueryParameters the parameters used to fetch a queryable store * @return A facade wrapping the local {@link StateStore} instances * @throws StreamsNotStartedException If Streams has not yet been started. Just call {@link KafkaStreams#start()} * and then retry this call. * @throws UnknownStateStoreException If the specified store name does not exist in the topology. * @throws InvalidStateStorePartitionException If the specified partition does not exist. * @throws InvalidStateStoreException If the Streams instance isn't in a queryable state. * If the store's type does not match the QueryableStoreType, * the Streams instance is not in a queryable state with respect * to the parameters, or if the store is not available locally, then * an InvalidStateStoreException is thrown upon store access. */ public <T> T store(final StoreQueryParameters<T> storeQueryParameters) { validateIsRunningOrRebalancing(); final String storeName = storeQueryParameters.storeName(); if (!topologyMetadata.hasStore(storeName)) { throw new UnknownStateStoreException( "Cannot get state store " + storeName + " because no such store is registered in the topology." ); } return queryableStoreProvider.getStore(storeQueryParameters); } /** * This method pauses processing for the KafkaStreams instance. * * <p>Paused topologies will only skip over a) processing, b) punctuation, and c) standby tasks. * Notably, paused topologies will still poll Kafka consumers, and commit offsets. * This method sets transient state that is not maintained or managed among instances. * Note that pause() can be called before start() in order to start a KafkaStreams instance * in a manner where the processing is paused as described, but the consumers are started up. */ public void pause() { if (topologyMetadata.hasNamedTopologies()) { for (final NamedTopology namedTopology : topologyMetadata.getAllNamedTopologies()) { topologyMetadata.pauseTopology(namedTopology.name()); } } else { topologyMetadata.pauseTopology(UNNAMED_TOPOLOGY); } } /** * @return true when the KafkaStreams instance has its processing paused. */ public boolean isPaused() { if (topologyMetadata.hasNamedTopologies()) { return topologyMetadata.getAllNamedTopologies().stream() .map(NamedTopology::name) .allMatch(topologyMetadata::isPaused); } else { return topologyMetadata.isPaused(UNNAMED_TOPOLOGY); } } /** * This method resumes processing for the KafkaStreams instance. */ public void resume() { if (topologyMetadata.hasNamedTopologies()) { for (final NamedTopology namedTopology : topologyMetadata.getAllNamedTopologies()) { topologyMetadata.resumeTopology(namedTopology.name()); } } else { topologyMetadata.resumeTopology(UNNAMED_TOPOLOGY); } threads.forEach(StreamThread::signalResume); } /** * handle each stream thread in a snapshot of threads. * noted: iteration over SynchronizedList is not thread safe so it must be manually synchronized. However, we may * require other locks when looping threads and it could cause deadlock. Hence, we create a copy to avoid holding * threads lock when looping threads. * @param consumer handler */ protected int processStreamThread(final Consumer<StreamThread> consumer) { final List<StreamThread> copy = new ArrayList<>(threads); for (final StreamThread thread : copy) consumer.accept(thread); return copy.size(); } /** * Returns the internal clients' assigned {@code client instance ids}. * * @return The internal clients' assigned instance ids used for metrics collection. * * @throws IllegalArgumentException If {@code timeout} is negative. * @throws IllegalStateException If {@code KafkaStreams} is not running. * @throws TimeoutException Indicates that a request timed out. * @throws StreamsException For any other error that might occur. */ public synchronized ClientInstanceIds clientInstanceIds(final Duration timeout) { if (timeout.isNegative()) { throw new IllegalArgumentException("The timeout cannot be negative."); } if (state().hasNotStarted()) { throw new IllegalStateException("KafkaStreams has not been started, you can retry after calling start()."); } if (state().isShuttingDown() || state.hasCompletedShutdown()) { throw new IllegalStateException("KafkaStreams has been stopped (" + state + ")."); } final Timer remainingTime = time.timer(timeout.toMillis()); final ClientInstanceIdsImpl clientInstanceIds = new ClientInstanceIdsImpl(); // (1) fan-out calls to threads // StreamThread for main/restore consumers and producer(s) final Map<String, KafkaFuture<Uuid>> consumerFutures = new HashMap<>(); final Map<String, KafkaFuture<Map<String, KafkaFuture<Uuid>>>> producerFutures = new HashMap<>(); synchronized (changeThreadCount) { for (final StreamThread streamThread : threads) { consumerFutures.putAll(streamThread.consumerClientInstanceIds(timeout)); producerFutures.put(streamThread.getName(), streamThread.producersClientInstanceIds(timeout)); } } // GlobalThread KafkaFuture<Uuid> globalThreadFuture = null; if (globalStreamThread != null) { globalThreadFuture = globalStreamThread.globalConsumerInstanceId(timeout); } // (2) get admin client instance id in a blocking fashion, while Stream/GlobalThreads work in parallel try { clientInstanceIds.setAdminInstanceId(adminClient.clientInstanceId(timeout)); remainingTime.update(time.milliseconds()); } catch (final IllegalStateException telemetryDisabledError) { // swallow log.debug("Telemetry is disabled on the admin client."); } catch (final TimeoutException timeoutException) { throw timeoutException; } catch (final Exception error) { throw new StreamsException("Could not retrieve admin client instance id.", error); } // (3) collect client instance ids from threads // (3a) collect consumers from StreamsThread for (final Map.Entry<String, KafkaFuture<Uuid>> consumerFuture : consumerFutures.entrySet()) { final Uuid instanceId = getOrThrowException( consumerFuture.getValue(), remainingTime.remainingMs(), () -> String.format( "Could not retrieve consumer instance id for %s.", consumerFuture.getKey() ) ); remainingTime.update(time.milliseconds()); // could be `null` if telemetry is disabled on the consumer itself if (instanceId != null) { clientInstanceIds.addConsumerInstanceId( consumerFuture.getKey(), instanceId ); } else { log.debug(String.format("Telemetry is disabled for %s.", consumerFuture.getKey())); } } // (3b) collect producers from StreamsThread for (final Map.Entry<String, KafkaFuture<Map<String, KafkaFuture<Uuid>>>> threadProducerFuture : producerFutures.entrySet()) { final Map<String, KafkaFuture<Uuid>> streamThreadProducerFutures = getOrThrowException( threadProducerFuture.getValue(), remainingTime.remainingMs(), () -> String.format( "Could not retrieve producer instance id for %s.", threadProducerFuture.getKey() ) ); remainingTime.update(time.milliseconds()); for (final Map.Entry<String, KafkaFuture<Uuid>> producerFuture : streamThreadProducerFutures.entrySet()) { final Uuid instanceId = getOrThrowException( producerFuture.getValue(), remainingTime.remainingMs(), () -> String.format( "Could not retrieve producer instance id for %s.", producerFuture.getKey() ) ); remainingTime.update(time.milliseconds()); // could be `null` if telemetry is disabled on the producer itself if (instanceId != null) { clientInstanceIds.addProducerInstanceId( producerFuture.getKey(), instanceId ); } else { log.debug(String.format("Telemetry is disabled for %s.", producerFuture.getKey())); } } } // (3c) collect from GlobalThread if (globalThreadFuture != null) { final Uuid instanceId = getOrThrowException( globalThreadFuture, remainingTime.remainingMs(), () -> "Could not retrieve global consumer client instance id." ); remainingTime.update(time.milliseconds()); // could be `null` if telemetry is disabled on the client itself if (instanceId != null) { clientInstanceIds.addConsumerInstanceId( globalStreamThread.getName(), instanceId ); } else { log.debug("Telemetry is disabled for the global consumer."); } } return clientInstanceIds; } private <T> T getOrThrowException( final KafkaFuture<T> future, final long timeoutMs, final Supplier<String> errorMessage) { final Throwable cause; try { return future.get(timeoutMs, TimeUnit.MILLISECONDS); } catch (final java.util.concurrent.TimeoutException timeout) { throw new TimeoutException(errorMessage.get(), timeout); } catch (final ExecutionException exception) { cause = exception.getCause(); if (cause instanceof TimeoutException) { throw (TimeoutException) cause; } } catch (final InterruptedException error) { cause = error; } throw new StreamsException(errorMessage.get(), cause); } /** * Returns runtime information about the local threads of this {@link KafkaStreams} instance. * * @return the set of {@link org.apache.kafka.streams.processor.ThreadMetadata}. * @deprecated since 3.0 use {@link #metadataForLocalThreads()} */ @Deprecated public Set<org.apache.kafka.streams.processor.ThreadMetadata> localThreadsMetadata() { return metadataForLocalThreads().stream().map(threadMetadata -> new org.apache.kafka.streams.processor.ThreadMetadata( threadMetadata.threadName(), threadMetadata.threadState(), threadMetadata.consumerClientId(), threadMetadata.restoreConsumerClientId(), threadMetadata.producerClientIds(), threadMetadata.adminClientId(), threadMetadata.activeTasks().stream().map(taskMetadata -> new org.apache.kafka.streams.processor.TaskMetadata( taskMetadata.taskId().toString(), taskMetadata.topicPartitions(), taskMetadata.committedOffsets(), taskMetadata.endOffsets(), taskMetadata.timeCurrentIdlingStarted()) ).collect(Collectors.toSet()), threadMetadata.standbyTasks().stream().map(taskMetadata -> new org.apache.kafka.streams.processor.TaskMetadata( taskMetadata.taskId().toString(), taskMetadata.topicPartitions(), taskMetadata.committedOffsets(), taskMetadata.endOffsets(), taskMetadata.timeCurrentIdlingStarted()) ).collect(Collectors.toSet()))) .collect(Collectors.toSet()); } /** * Returns runtime information about the local threads of this {@link KafkaStreams} instance. * * @return the set of {@link ThreadMetadata}. */ public Set<ThreadMetadata> metadataForLocalThreads() { final Set<ThreadMetadata> threadMetadata = new HashSet<>(); processStreamThread(thread -> { synchronized (thread.getStateLock()) { if (thread.state() != StreamThread.State.DEAD) { threadMetadata.add(thread.threadMetadata()); } } }); return threadMetadata; } /** * Returns {@link LagInfo}, for all store partitions (active or standby) local to this Streams instance. Note that the * values returned are just estimates and meant to be used for making soft decisions on whether the data in the store * partition is fresh enough for querying. * * <p>Note: Each invocation of this method issues a call to the Kafka brokers. Thus, it's advisable to limit the frequency * of invocation to once every few seconds. * * @return map of store names to another map of partition to {@link LagInfo}s * @throws StreamsException if the admin client request throws exception */ public Map<String, Map<Integer, LagInfo>> allLocalStorePartitionLags() { final List<Task> allTasks = new ArrayList<>(); processStreamThread(thread -> allTasks.addAll(thread.readyOnlyAllTasks())); return allLocalStorePartitionLags(allTasks); } protected Map<String, Map<Integer, LagInfo>> allLocalStorePartitionLags(final List<Task> tasksToCollectLagFor) { final Map<String, Map<Integer, LagInfo>> localStorePartitionLags = new TreeMap<>(); final Collection<TopicPartition> allPartitions = new LinkedList<>(); final Map<TopicPartition, Long> allChangelogPositions = new HashMap<>(); // Obtain the current positions, of all the active-restoring and standby tasks for (final Task task : tasksToCollectLagFor) { allPartitions.addAll(task.changelogPartitions()); // Note that not all changelog partitions, will have positions; since some may not have started allChangelogPositions.putAll(task.changelogOffsets()); } log.debug("Current changelog positions: {}", allChangelogPositions); final Map<TopicPartition, ListOffsetsResultInfo> allEndOffsets; allEndOffsets = fetchEndOffsets(allPartitions, adminClient); log.debug("Current end offsets :{}", allEndOffsets); for (final Map.Entry<TopicPartition, ListOffsetsResultInfo> entry : allEndOffsets.entrySet()) { // Avoiding an extra admin API lookup by computing lags for not-yet-started restorations // from zero instead of the real "earliest offset" for the changelog. // This will yield the correct relative order of lagginess for the tasks in the cluster, // but it is an over-estimate of how much work remains to restore the task from scratch. final long earliestOffset = 0L; final long changelogPosition = allChangelogPositions.getOrDefault(entry.getKey(), earliestOffset); final long latestOffset = entry.getValue().offset(); final LagInfo lagInfo = new LagInfo(changelogPosition == Task.LATEST_OFFSET ? latestOffset : changelogPosition, latestOffset); final String storeName = streamsMetadataState.getStoreForChangelogTopic(entry.getKey().topic()); localStorePartitionLags.computeIfAbsent(storeName, ignored -> new TreeMap<>()) .put(entry.getKey().partition(), lagInfo); } return Collections.unmodifiableMap(localStorePartitionLags); } /** * Run an interactive query against a state store. * <p> * This method allows callers outside of the Streams runtime to access the internal state of * stateful processors. See <a href="https://kafka.apache.org/documentation/streams/developer-guide/interactive-queries.html">IQ docs</a> * for more information. * <p> * NOTICE: This functionality is {@link Evolving} and subject to change in minor versions. * Once it is stabilized, this notice and the evolving annotation will be removed. * * @param <R> The result type specified by the query. * @throws StreamsNotStartedException If Streams has not yet been started. Just call {@link * KafkaStreams#start()} and then retry this call. * @throws StreamsStoppedException If Streams is in a terminal state like PENDING_SHUTDOWN, * NOT_RUNNING, PENDING_ERROR, or ERROR. The caller should * discover a new instance to query. * @throws UnknownStateStoreException If the specified store name does not exist in the * topology. */ @Evolving public <R> StateQueryResult<R> query(final StateQueryRequest<R> request) { final String storeName = request.getStoreName(); if (!topologyMetadata.hasStore(storeName)) { throw new UnknownStateStoreException( "Cannot get state store " + storeName + " because no such store is registered in the topology." ); } if (state().hasNotStarted()) { throw new StreamsNotStartedException( "KafkaStreams has not been started, you can retry after calling start()." ); } if (state().isShuttingDown() || state.hasCompletedShutdown()) { throw new StreamsStoppedException( "KafkaStreams has been stopped (" + state + ")." + " This instance can no longer serve queries." ); } final StateQueryResult<R> result = new StateQueryResult<>(); final Map<String, StateStore> globalStateStores = topologyMetadata.globalStateStores(); if (globalStateStores.containsKey(storeName)) { // See KAFKA-13523 result.setGlobalResult( QueryResult.forFailure( FailureReason.UNKNOWN_QUERY_TYPE, "Global stores do not yet support the KafkaStreams#query API. Use KafkaStreams#store instead." ) ); } else { for (final StreamThread thread : threads) { final Set<Task> tasks = thread.readyOnlyAllTasks(); for (final Task task : tasks) { final TaskId taskId = task.id(); final int partition = taskId.partition(); if (request.isAllPartitions() || request.getPartitions().contains(partition)) { final StateStore store = task.getStore(storeName); if (store != null) { final StreamThread.State state = thread.state(); final boolean active = task.isActive(); if (request.isRequireActive() && (state != StreamThread.State.RUNNING || !active)) { result.addResult( partition, QueryResult.forFailure( FailureReason.NOT_ACTIVE, "Query requires a running active task," + " but partition was in state " + state + " and was " + (active ? "active" : "not active") + "." ) ); } else { final QueryResult<R> r = store.query( request.getQuery(), request.isRequireActive() ? PositionBound.unbounded() : request.getPositionBound(), new QueryConfig(request.executionInfoEnabled()) ); result.addResult(partition, r); } // optimization: if we have handled all the requested partitions, // we can return right away. if (!request.isAllPartitions() && result.getPartitionResults().keySet().containsAll(request.getPartitions())) { return result; } } } } } } if (!request.isAllPartitions()) { for (final Integer partition : request.getPartitions()) { if (!result.getPartitionResults().containsKey(partition)) { result.addResult(partition, QueryResult.forFailure( FailureReason.NOT_PRESENT, "The requested partition was not present at the time of the query." )); } } } return result; } }
apache/kafka
streams/src/main/java/org/apache/kafka/streams/KafkaStreams.java
2,192
package com.taobao.arthas.core.util.affect; import static java.lang.System.currentTimeMillis; /** * 影响反馈 * Created by vlinux on 15/5/21. * @author diecui1202 on 2017/10/26 */ public class Affect { private final long start = currentTimeMillis(); /** * 影响耗时(ms) * * @return 获取耗时(ms) */ public long cost() { return currentTimeMillis() - start; } @Override public String toString() { return String.format("Affect cost in %s ms.", cost()); } }
alibaba/arthas
core/src/main/java/com/taobao/arthas/core/util/affect/Affect.java
2,193
package org.telegram.ui.Cells; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.BlendMode; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Outline; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.os.Build; import android.text.TextUtils; import android.view.View; import android.view.ViewOutlineProvider; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.DownloadController; import org.telegram.messenger.FileLoader; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.MediaController; import org.telegram.messenger.UserConfig; import org.telegram.tgnet.TLRPC; import org.telegram.ui.Components.BackgroundGradientDrawable; import org.telegram.ui.Components.BackupImageView; import org.telegram.ui.Components.MediaActionDrawable; import org.telegram.ui.Components.MotionBackgroundDrawable; import org.telegram.ui.Components.RadialProgress2; import java.io.File; public class PatternCell extends BackupImageView implements DownloadController.FileDownloadProgressListener { private final int SIZE = 100; private RectF rect = new RectF(); private RadialProgress2 radialProgress; private boolean wasSelected; private TLRPC.TL_wallPaper currentPattern; private int currentAccount = UserConfig.selectedAccount; private LinearGradient gradientShader; private int currentBackgroundColor; private int currentGradientColor1; private int currentGradientColor2; private int currentGradientColor3; private int currentGradientAngle; private Paint backgroundPaint; private MotionBackgroundDrawable backgroundDrawable; private int TAG; private PatternCellDelegate delegate; private int maxWallpaperSize; public interface PatternCellDelegate { TLRPC.TL_wallPaper getSelectedPattern(); int getBackgroundGradientColor1(); int getBackgroundGradientColor2(); int getBackgroundGradientColor3(); int getBackgroundGradientAngle(); int getBackgroundColor(); int getPatternColor(); int getCheckColor(); float getIntensity(); } public PatternCell(Context context, int maxSize, PatternCellDelegate patternCellDelegate) { super(context); setRoundRadius(AndroidUtilities.dp(6)); maxWallpaperSize = maxSize; delegate = patternCellDelegate; radialProgress = new RadialProgress2(this); radialProgress.setProgressRect(AndroidUtilities.dp(30), AndroidUtilities.dp(30), AndroidUtilities.dp(70), AndroidUtilities.dp(70)); backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); TAG = DownloadController.getInstance(currentAccount).generateObserverTag(); if (Build.VERSION.SDK_INT >= 21) { setOutlineProvider(new ViewOutlineProvider() { @Override public void getOutline(View view, Outline outline) { outline.setRoundRect(AndroidUtilities.dp(1), AndroidUtilities.dp(1), view.getMeasuredWidth() - AndroidUtilities.dp(1), view.getMeasuredHeight() - AndroidUtilities.dp(1), AndroidUtilities.dp(6)); } }); setClipToOutline(true); } } public void setPattern(TLRPC.TL_wallPaper wallPaper) { currentPattern = wallPaper; if (wallPaper != null) { TLRPC.PhotoSize thumb = FileLoader.getClosestPhotoSizeWithSize(wallPaper.document.thumbs, AndroidUtilities.dp(SIZE)); setImage(ImageLocation.getForDocument(thumb, wallPaper.document), SIZE + "_" + SIZE, null, null, "png", 0, 1, wallPaper); } else { setImageDrawable(null); } updateSelected(false); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); updateSelected(false); } public void updateSelected(boolean animated) { TLRPC.TL_wallPaper selectedPattern = delegate.getSelectedPattern(); boolean isSelected = currentPattern == null && selectedPattern == null || selectedPattern != null && currentPattern != null && currentPattern.id == selectedPattern.id; if (isSelected) { updateButtonState(selectedPattern, false, animated); } else { radialProgress.setIcon(MediaActionDrawable.ICON_NONE, false, animated); } invalidate(); } @Override public void invalidate() { super.invalidate(); } private void updateButtonState(Object image, boolean ifSame, boolean animated) { if (image instanceof TLRPC.TL_wallPaper || image instanceof MediaController.SearchImage) { File path; int size; String fileName; if (image instanceof TLRPC.TL_wallPaper) { TLRPC.TL_wallPaper wallPaper = (TLRPC.TL_wallPaper) image; fileName = FileLoader.getAttachFileName(wallPaper.document); if (TextUtils.isEmpty(fileName)) { return; } path = FileLoader.getInstance(currentAccount).getPathToAttach(wallPaper.document, true); } else { MediaController.SearchImage wallPaper = (MediaController.SearchImage) image; if (wallPaper.photo != null) { TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(wallPaper.photo.sizes, maxWallpaperSize, true); path = FileLoader.getInstance(currentAccount).getPathToAttach(photoSize, true); fileName = FileLoader.getAttachFileName(photoSize); } else { path = ImageLoader.getHttpFilePath(wallPaper.imageUrl, "jpg"); fileName = path.getName(); } if (TextUtils.isEmpty(fileName)) { return; } } if (path.exists()) { DownloadController.getInstance(currentAccount).removeLoadingFileObserver(this); radialProgress.setProgress(1, animated); radialProgress.setIcon(MediaActionDrawable.ICON_CHECK, ifSame, animated); } else { DownloadController.getInstance(currentAccount).addLoadingFileObserver(fileName, null, this); boolean isLoading = FileLoader.getInstance(currentAccount).isLoadingFile(fileName); Float progress = ImageLoader.getInstance().getFileProgress(fileName); if (progress != null) { radialProgress.setProgress(progress, animated); } else { radialProgress.setProgress(0, animated); } radialProgress.setIcon(MediaActionDrawable.ICON_EMPTY, ifSame, animated); } } else { radialProgress.setIcon(MediaActionDrawable.ICON_CHECK, ifSame, animated); } } @SuppressLint("DrawAllocation") @Override protected void onDraw(Canvas canvas) { float intensity = delegate.getIntensity(); //imageReceiver.setAlpha(Math.abs(intensity)); imageReceiver.setBlendMode(null); int backgroundColor = delegate.getBackgroundColor(); int backgroundGradientColor1 = delegate.getBackgroundGradientColor1(); int backgroundGradientColor2 = delegate.getBackgroundGradientColor2(); int backgroundGradientColor3 = delegate.getBackgroundGradientColor3(); int backgroundGradientAngle = delegate.getBackgroundGradientAngle(); int checkColor = delegate.getCheckColor(); if (backgroundGradientColor1 != 0) { if (gradientShader == null || backgroundColor != currentBackgroundColor || backgroundGradientColor1 != currentGradientColor1 || backgroundGradientColor2 != currentGradientColor2 || backgroundGradientColor3 != currentGradientColor3 || backgroundGradientAngle != currentGradientAngle) { currentBackgroundColor = backgroundColor; currentGradientColor1 = backgroundGradientColor1; currentGradientColor2 = backgroundGradientColor2; currentGradientColor3 = backgroundGradientColor3; currentGradientAngle = backgroundGradientAngle; if (backgroundGradientColor2 != 0) { gradientShader = null; if (backgroundDrawable != null) { backgroundDrawable.setColors(backgroundColor, backgroundGradientColor1, backgroundGradientColor2, backgroundGradientColor3, 0, false); } else { backgroundDrawable = new MotionBackgroundDrawable(backgroundColor, backgroundGradientColor1, backgroundGradientColor2, backgroundGradientColor3, true); backgroundDrawable.setRoundRadius(AndroidUtilities.dp(6)); backgroundDrawable.setParentView(this); } if (intensity < 0) { imageReceiver.setGradientBitmap(backgroundDrawable.getBitmap()); } else { imageReceiver.setGradientBitmap(null); if (Build.VERSION.SDK_INT >= 29) { imageReceiver.setBlendMode(BlendMode.SOFT_LIGHT); } else { imageReceiver.setColorFilter(new PorterDuffColorFilter(delegate.getPatternColor(), PorterDuff.Mode.SRC_IN)); } } } else { final Rect r = BackgroundGradientDrawable.getGradientPoints(currentGradientAngle, getMeasuredWidth(), getMeasuredHeight()); gradientShader = new LinearGradient(r.left, r.top, r.right, r.bottom, new int[]{backgroundColor, backgroundGradientColor1}, null, Shader.TileMode.CLAMP); backgroundDrawable = null; imageReceiver.setGradientBitmap(null); } } } else { gradientShader = null; backgroundDrawable = null; imageReceiver.setGradientBitmap(null); } if (backgroundDrawable != null) { backgroundDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight()); backgroundDrawable.draw(canvas); } else { backgroundPaint.setShader(gradientShader); if (gradientShader == null) { backgroundPaint.setColor(backgroundColor); } rect.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), backgroundPaint); } super.onDraw(canvas); if (radialProgress.getIcon() != MediaActionDrawable.ICON_NONE) { radialProgress.setColors(checkColor, checkColor, 0xffffffff, 0xffffffff); radialProgress.draw(canvas); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(AndroidUtilities.dp(SIZE), AndroidUtilities.dp(SIZE)); } @Override public void onFailedDownload(String fileName, boolean canceled) { TLRPC.TL_wallPaper selectedPattern = delegate.getSelectedPattern(); boolean isSelected = currentPattern == null && selectedPattern == null || selectedPattern != null && currentPattern != null && currentPattern.id == selectedPattern.id; if (isSelected) { if (canceled) { radialProgress.setIcon(MediaActionDrawable.ICON_NONE, false, true); } else { updateButtonState(currentPattern, true, canceled); } } } @Override public void onSuccessDownload(String fileName) { radialProgress.setProgress(1, true); TLRPC.TL_wallPaper selectedPattern = delegate.getSelectedPattern(); boolean isSelected = currentPattern == null && selectedPattern == null || selectedPattern != null && currentPattern != null && currentPattern.id == selectedPattern.id; if (isSelected) { updateButtonState(currentPattern, false, true); } } @Override public void onProgressDownload(String fileName, long downloadedSize, long totalSize) { radialProgress.setProgress(Math.min(1f, downloadedSize / (float) totalSize), true); TLRPC.TL_wallPaper selectedPattern = delegate.getSelectedPattern(); boolean isSelected = currentPattern == null && selectedPattern == null || selectedPattern != null && currentPattern != null && currentPattern.id == selectedPattern.id; if (isSelected && radialProgress.getIcon() != MediaActionDrawable.ICON_EMPTY) { updateButtonState(currentPattern, false, true); } } @Override public void onProgressUpload(String fileName, long uploadedSize, long totalSize, boolean isEncrypted) { } @Override public int getObserverTag() { return TAG; } }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/org/telegram/ui/Cells/PatternCell.java
2,194
package org.telegram.ui.Stories; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.GradientDrawable; import android.text.Layout; import android.text.SpannableStringBuilder; import android.text.StaticLayout; import android.text.TextPaint; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.animation.OvershootInterpolator; import android.widget.Scroller; import androidx.annotation.NonNull; import androidx.core.graphics.ColorUtils; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.R; import org.telegram.tgnet.tl.TL_stories; import org.telegram.ui.Components.ColoredImageSpan; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.StaticLayoutEx; import java.util.ArrayList; public abstract class SelfStoriesPreviewView extends View { public int imagesFromY; public int imagesFromW; public int imagesFromH; Scroller scroller; float scrollX; float minScroll; float maxScroll; int childPadding; private int viewH; private int viewW; private boolean isAttachedToWindow; private int scrollToPositionInLayout = -1; float topPadding; float progressToOpen; ArrayList<SelfStoryViewsView.StoryItemInternal> storyItems = new ArrayList<>(); ArrayList<ImageHolder> imageReceiversTmp = new ArrayList<>(); ArrayList<ImageHolder> lastDrawnImageReceivers = new ArrayList<>(); GradientDrawable gradientDrawable; GestureDetector gestureDetector = new GestureDetector(new GestureDetector.OnGestureListener() { @Override public boolean onDown(@NonNull MotionEvent e) { scroller.abortAnimation(); if (scrollAnimator != null) { scrollAnimator.removeAllListeners(); scrollAnimator.cancel(); scrollAnimator = null; } checkScroll = false; onDragging(); return true; } @Override public void onShowPress(@NonNull MotionEvent e) { } @Override public boolean onSingleTapUp(@NonNull MotionEvent e) { for (int i = 0; i < lastDrawnImageReceivers.size(); i++) { ImageHolder holder = lastDrawnImageReceivers.get(i); if (lastDrawnImageReceivers.get(i).receiver.getDrawRegion().contains(e.getX(), e.getY())) { if (lastClosestPosition != holder.position) { scrollToPosition(holder.position, true, false); } else { onCenteredImageTap(); } } } return false; } @Override public boolean onScroll(@NonNull MotionEvent e1, @NonNull MotionEvent e2, float distanceX, float distanceY) { scrollX += distanceX; if (scrollX < minScroll) { scrollX = minScroll; } if (scrollX > maxScroll) { scrollX = maxScroll; } invalidate(); return false; } @Override public void onLongPress(@NonNull MotionEvent e) { } @Override public boolean onFling(@NonNull MotionEvent e1, @NonNull MotionEvent e2, float velocityX, float velocityY) { scroller.fling((int) scrollX, 0, (int) -velocityX, 0, (int) minScroll, (int) maxScroll, 0, 0); invalidate(); return false; } }); private float textWidth; public void onCenteredImageTap() { } private int lastClosestPosition; public SelfStoriesPreviewView(Context context) { super(context); scroller = new Scroller(context, new OvershootInterpolator()); gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{Color.TRANSPARENT, ColorUtils.setAlphaComponent(Color.BLACK, 160)}); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); childPadding = AndroidUtilities.dp(8); viewH = (int) (AndroidUtilities.dp(180) / 1.2f); viewW = (int) ((viewH / 16f) * 9f); float textWidthLocal = viewW - AndroidUtilities.dp(8); topPadding = ((AndroidUtilities.dp(180) - viewH) / 2f) + AndroidUtilities.dp(20); updateScrollParams(); if (scrollToPositionInLayout >= 0 && getMeasuredWidth() > 0) { lastClosestPosition = -1; scrollToPosition(scrollToPositionInLayout, false, false); scrollToPositionInLayout = -1; } if (textWidth != textWidthLocal) { textWidth = textWidthLocal; for (int i = 0; i < lastDrawnImageReceivers.size(); i++) { lastDrawnImageReceivers.get(i).onBind(lastDrawnImageReceivers.get(i).position); } } } private void updateScrollParams() { minScroll = -(getMeasuredWidth() - viewW) / 2f; maxScroll = (viewW + childPadding) * storyItems.size() - childPadding - getMeasuredWidth() + (getMeasuredWidth() - viewW) / 2f; } boolean checkScroll; @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (scroller.computeScrollOffset()) { // if (Math.abs(scrollX - scroller.getCurrX()) < AndroidUtilities.dp(1)) { // scroller.abortAnimation(); // } else { scrollX = scroller.getCurrX(); // } invalidate(); checkScroll = true; } else if (checkScroll) { scrollToClosest(); } float cx = getMeasuredWidth() / 2f; imageReceiversTmp.clear(); imageReceiversTmp.addAll(lastDrawnImageReceivers); lastDrawnImageReceivers.clear(); int closestPositon = -1; float minDistance = Integer.MAX_VALUE; for (int i = 0; i < storyItems.size(); i++) { float x = -scrollX + (viewW + childPadding) * i; float viewCx = x + viewW / 2f; float distance = Math.abs(viewCx - cx); float s = 1f; float k = 0; if (distance < viewW) { k = 1f - Math.abs(viewCx - cx) / viewW; s = 1f + 0.2f * k; } if (closestPositon == -1 || distance < minDistance) { closestPositon = i; minDistance = distance; } if (viewCx - cx < 0) { x -= viewW * 0.1f * (1f - k); } else { x += viewW * 0.1f * (1f - k); } if (x > getMeasuredWidth() || x + viewW < 0) { continue; } ImageHolder holder = findOrCreateImageReceiver(i, imageReceiversTmp); float w = viewW * s; float h = viewH * s; float imageX = x - (w - viewW) / 2f; float imageY = topPadding - (h - viewH) / 2f; if (progressToOpen == 0 || i == lastClosestPosition) { holder.receiver.setImageCoords(imageX, imageY, w, h); } else { float fromX = (i - lastClosestPosition) * getMeasuredWidth(); float fromY = imagesFromY; float fromH = imagesFromH; float fromW = imagesFromW; holder.receiver.setImageCoords( AndroidUtilities.lerp(fromX, imageX, progressToOpen), AndroidUtilities.lerp(fromY, imageY, progressToOpen), AndroidUtilities.lerp(fromW, w, progressToOpen), AndroidUtilities.lerp(fromH, h, progressToOpen) ); } if (!(progressToOpen != 1f && i == lastClosestPosition)) { holder.receiver.draw(canvas); if (holder.layout != null) { float alpha = 0.7f + 0.3f * k;//k; gradientDrawable.setAlpha((int) (255 * alpha)); gradientDrawable.setBounds( (int) holder.receiver.getImageX(), (int) (holder.receiver.getImageY2() - AndroidUtilities.dp(24)), (int) holder.receiver.getImageX2(), (int) holder.receiver.getImageY2() + 2); gradientDrawable.draw(canvas); canvas.save(); canvas.translate(holder.receiver.getCenterX() - textWidth / 2f, holder.receiver.getImageY2() - AndroidUtilities.dp(8) - holder.layout.getHeight()); holder.paint.setAlpha((int) (255 * alpha)); holder.layout.draw(canvas); canvas.restore(); } } lastDrawnImageReceivers.add(holder); } if (scrollAnimator == null && lastClosestPosition != closestPositon) { lastClosestPosition = closestPositon; onClosestPositionChanged(lastClosestPosition); } for (int i = 0; i < imageReceiversTmp.size(); i++) { imageReceiversTmp.get(i).onDetach(); } imageReceiversTmp.clear(); } abstract void onDragging(); public void onClosestPositionChanged(int lastClosestPosition) { } private void scrollToClosest() { if (lastClosestPosition >= 0) { scrollToPosition(lastClosestPosition, true, true); } } private ImageHolder findOrCreateImageReceiver(int position, ArrayList<ImageHolder> imageReceivers) { for (int i = 0; i < imageReceivers.size(); i++) { if (imageReceivers.get(i).position == position) { return imageReceivers.remove(i); } } ImageHolder imageHolder = new ImageHolder(); imageHolder.onBind(position); imageHolder.position = position; return imageHolder; } ValueAnimator scrollAnimator; public void scrollToPosition(int p, boolean animated, boolean force) { if ((lastClosestPosition == p && !force) || getMeasuredHeight() <= 0) { return; } if (lastClosestPosition != p) { lastClosestPosition = p; onClosestPositionChanged(lastClosestPosition); } scroller.abortAnimation(); checkScroll = false; if (scrollAnimator != null) { scrollAnimator.removeAllListeners(); scrollAnimator.cancel(); scrollAnimator = null; } if (!animated) { scrollX = -getMeasuredWidth() / 2f + viewW / 2f + (viewW + childPadding) * p; invalidate(); } else { float newScroll = -getMeasuredWidth() / 2f + viewW / 2f + (viewW + childPadding) * p; if (newScroll == scrollX) { return; } scrollAnimator = ValueAnimator.ofFloat(scrollX, newScroll); scrollAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(@NonNull ValueAnimator animation) { scrollX = (float) animation.getAnimatedValue(); invalidate(); } }); scrollAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { scrollAnimator = null; } }); scrollAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); scrollAnimator.setDuration(200); scrollAnimator.start(); } } @Override public boolean onTouchEvent(MotionEvent event) { gestureDetector.onTouchEvent(event); if ((event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) && scroller.isFinished()) { scrollToClosest(); } return true; } public void setItems(ArrayList<SelfStoryViewsView.StoryItemInternal> storyItems, int position) { this.storyItems.clear(); this.storyItems.addAll(storyItems); updateScrollParams(); if (getMeasuredHeight() > 0) { scrollToPosition(position, false, false); } else { scrollToPositionInLayout = position; } for (int i = 0; i < lastDrawnImageReceivers.size(); i++) { lastDrawnImageReceivers.get(i).onBind(lastDrawnImageReceivers.get(i).position); } } public int getClosestPosition() { return lastClosestPosition; } public ImageHolder getCenteredImageReciever() { for (int i = 0; i < lastDrawnImageReceivers.size(); i++) { if (lastDrawnImageReceivers.get(i).position == lastClosestPosition) { return lastDrawnImageReceivers.get(i); } } return null; } public void abortScroll() { scroller.abortAnimation(); if (scrollAnimator != null) { scrollAnimator.cancel(); scrollAnimator = null; } scrollToPosition(lastClosestPosition, false, true); } public float getFinalHeight() { return AndroidUtilities.dp(180); } public void setProgressToOpen(float progressToOpen) { if (this.progressToOpen == progressToOpen) { return; } this.progressToOpen = progressToOpen; invalidate(); } public void scrollToPositionWithOffset(int position, float positionOffset) { scroller.abortAnimation(); if (Math.abs(positionOffset) > 1) { return; } if (scrollAnimator != null) { scrollAnimator.cancel(); scrollAnimator = null; } float fromScrollX = -getMeasuredWidth() / 2f + viewW / 2f + (viewW + childPadding) * position; float progress = positionOffset; float toScrollX; if (positionOffset > 0) { toScrollX = -getMeasuredWidth() / 2f + viewW / 2f + (viewW + childPadding) * (position + 1); } else { toScrollX = -getMeasuredWidth() / 2f + viewW / 2f + (viewW + childPadding) * (position - 1); progress = -positionOffset; } if (progress == 0) { scrollX = fromScrollX; } else { scrollX = AndroidUtilities.lerp(fromScrollX, toScrollX, progress); } checkScroll = false; invalidate(); } public class ImageHolder { ImageReceiver receiver = new ImageReceiver(SelfStoriesPreviewView.this); int position; StaticLayout layout; TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG); SelfStoryViewsView.StoryItemInternal storyItem; public ImageHolder() { receiver.setAllowLoadingOnAttachedOnly(true); receiver.setRoundRadius(AndroidUtilities.dp(6)); paint.setColor(Color.WHITE); paint.setTextSize(AndroidUtilities.dp(13)); } void onBind(int position) { if (position < 0 || position >= storyItems.size()) return; storyItem = storyItems.get(position); if (isAttachedToWindow) { receiver.onAttachedToWindow(); } if (storyItem.storyItem != null) { StoriesUtilities.setImage(receiver, storyItem.storyItem); } else { StoriesUtilities.setImage(receiver, storyItem.uploadingStory); } updateLayout(); } private void updateLayout() { SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); if (storyItem.storyItem != null) { formatCounterText(spannableStringBuilder, storyItem.storyItem.views, false); } if (spannableStringBuilder.length() == 0) { layout = null; } else { layout = StaticLayoutEx.createStaticLayout(spannableStringBuilder, paint, (int) (textWidth + 1), Layout.Alignment.ALIGN_CENTER, 1.0f, 0f, false, null, Integer.MAX_VALUE, 1); if (layout.getLineCount() > 1) { spannableStringBuilder = new SpannableStringBuilder(""); formatCounterText(spannableStringBuilder, storyItem.storyItem.views, true); layout = StaticLayoutEx.createStaticLayout(spannableStringBuilder, paint, (int) (textWidth + 1), Layout.Alignment.ALIGN_CENTER, 1.0f, 0f, false, null, Integer.MAX_VALUE, 2); } } } void onDetach() { receiver.onDetachedFromWindow(); } public void draw(Canvas canvas, float alpha, float scale, int x, int y, int width, int height) { receiver.setImageCoords(x, y, width, height); receiver.setAlpha(alpha); receiver.draw(canvas); receiver.setAlpha(1f); if (layout != null) { paint.setAlpha((int) (255 * alpha)); gradientDrawable.setAlpha((int) (255 * alpha)); gradientDrawable.setBounds( (int) receiver.getImageX(), (int) (receiver.getImageY2() - AndroidUtilities.dp(24) * scale), (int) receiver.getImageX2(), (int) receiver.getImageY2() + 2); gradientDrawable.draw(canvas); canvas.save(); canvas.scale(scale, scale, receiver.getCenterX(), receiver.getImageY2() - AndroidUtilities.dp(8) * scale); canvas.translate(receiver.getCenterX() - textWidth / 2f, receiver.getImageY2() - AndroidUtilities.dp(8) * scale - layout.getHeight()); layout.draw(canvas); canvas.restore(); } } public void update() { updateLayout(); } } private void formatCounterText(SpannableStringBuilder spannableStringBuilder, TL_stories.StoryViews storyViews, boolean twoLines) { int count = storyViews == null ? 0 : storyViews.views_count; if (count > 0) { spannableStringBuilder.append("d"); spannableStringBuilder.setSpan(new ColoredImageSpan(R.drawable.msg_views), spannableStringBuilder.length() - 1, spannableStringBuilder.length(), 0); spannableStringBuilder.append(" ").append( AndroidUtilities.formatWholeNumber(count, 0) ); if (storyViews != null && storyViews.reactions_count > 0) { spannableStringBuilder.append(twoLines ? "\n" : " "); spannableStringBuilder.append("d"); spannableStringBuilder.setSpan(new ColoredImageSpan(R.drawable.mini_like_filled), spannableStringBuilder.length() - 1, spannableStringBuilder.length(), 0); spannableStringBuilder.append(" ").append( AndroidUtilities.formatWholeNumber(storyViews.reactions_count, 0) ); } } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); isAttachedToWindow = true; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); isAttachedToWindow = false; for (int i = 0; i < lastDrawnImageReceivers.size(); i++) { lastDrawnImageReceivers.get(i).onDetach(); } lastDrawnImageReceivers.clear(); } public void update() { for (int i = 0; i < lastDrawnImageReceivers.size(); i++) { lastDrawnImageReceivers.get(i).update(); } } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Stories/SelfStoriesPreviewView.java
2,195
/* * Copyright (C) 2014 jsonwebtoken.io * * 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 io.jsonwebtoken; import java.util.Date; import java.util.Map; import java.util.Set; /** * A JWT <a href="https://www.rfc-editor.org/rfc/rfc7519.html#section-4">Claims set</a>. * * <p>This is an immutable JSON map with convenient type-safe getters for JWT standard claim names.</p> * * <p>Additionally, this interface also extends <code>Map&lt;String, Object&gt;</code>, so you can use standard * {@code Map} accessor/iterator methods as desired, for example:</p> * * <blockquote><pre> * claims.get("someKey");</pre></blockquote> * * <p>However, because {@code Claims} instances are immutable, calling any of the map mutation methods * (such as {@code Map.}{@link Map#put(Object, Object) put}, etc) will result in a runtime exception. The * {@code Map} interface is implemented specifically for the convenience of working with existing Map-based utilities * and APIs.</p> * * @since 0.1 */ public interface Claims extends Map<String, Object>, Identifiable { /** * JWT {@code Issuer} claims parameter name: <code>"iss"</code> */ String ISSUER = "iss"; /** * JWT {@code Subject} claims parameter name: <code>"sub"</code> */ String SUBJECT = "sub"; /** * JWT {@code Audience} claims parameter name: <code>"aud"</code> */ String AUDIENCE = "aud"; /** * JWT {@code Expiration} claims parameter name: <code>"exp"</code> */ String EXPIRATION = "exp"; /** * JWT {@code Not Before} claims parameter name: <code>"nbf"</code> */ String NOT_BEFORE = "nbf"; /** * JWT {@code Issued At} claims parameter name: <code>"iat"</code> */ String ISSUED_AT = "iat"; /** * JWT {@code JWT ID} claims parameter name: <code>"jti"</code> */ String ID = "jti"; /** * Returns the JWT <a href="https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.1"> * <code>iss</code></a> (issuer) value or {@code null} if not present. * * @return the JWT {@code iss} value or {@code null} if not present. */ String getIssuer(); /** * Returns the JWT <a href="https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.2"> * <code>sub</code></a> (subject) value or {@code null} if not present. * * @return the JWT {@code sub} value or {@code null} if not present. */ String getSubject(); /** * Returns the JWT <a href="https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.3"> * <code>aud</code></a> (audience) value or {@code null} if not present. * * @return the JWT {@code aud} value or {@code null} if not present. */ Set<String> getAudience(); /** * Returns the JWT <a href="https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.4"> * <code>exp</code></a> (expiration) timestamp or {@code null} if not present. * * <p>A JWT obtained after this timestamp should not be used.</p> * * @return the JWT {@code exp} value or {@code null} if not present. */ Date getExpiration(); /** * Returns the JWT <a href="https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.5"> * <code>nbf</code></a> (not before) timestamp or {@code null} if not present. * * <p>A JWT obtained before this timestamp should not be used.</p> * * @return the JWT {@code nbf} value or {@code null} if not present. */ Date getNotBefore(); /** * Returns the JWT <a href="https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.6"> * <code>iat</code></a> (issued at) timestamp or {@code null} if not present. * * <p>If present, this value is the timestamp when the JWT was created.</p> * * @return the JWT {@code iat} value or {@code null} if not present. */ Date getIssuedAt(); /** * Returns the JWTs <a href="https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.7"> * <code>jti</code></a> (JWT ID) value or {@code null} if not present. * * <p>This value is a CaSe-SenSiTiVe unique identifier for the JWT. If available, this value is expected to be * assigned in a manner that ensures that there is a negligible probability that the same value will be * accidentally * assigned to a different data object. The ID can be used to prevent the JWT from being replayed.</p> * * @return the JWT {@code jti} value or {@code null} if not present. */ @Override // just for JavaDoc specific to the JWT spec String getId(); /** * Returns the JWTs claim ({@code claimName}) value as a {@code requiredType} instance, or {@code null} if not * present. * * <p>JJWT only converts simple String, Date, Long, Integer, Short and Byte types automatically. Anything more * complex is expected to be already converted to your desired type by the JSON parser. You may specify a custom * JSON processor using the {@code JwtParserBuilder}'s * {@link JwtParserBuilder#json(io.jsonwebtoken.io.Deserializer) json(Deserializer)} method. See the JJWT * documentation on <a href="https://github.com/jwtk/jjwt#custom-json-processor">custom JSON processor</a>s for more * information. If using Jackson, you can specify custom claim POJO types as described in * <a href="https://github.com/jwtk/jjwt#json-jackson-custom-types">custom claim types</a>. * * @param claimName name of claim * @param requiredType the type of the value expected to be returned * @param <T> the type of the value expected to be returned * @return the JWT {@code claimName} value or {@code null} if not present. * @throws RequiredTypeException throw if the claim value is not null and not of type {@code requiredType} * @see <a href="https://github.com/jwtk/jjwt#json-support">JJWT JSON Support</a> */ <T> T get(String claimName, Class<T> requiredType); }
jwtk/jjwt
api/src/main/java/io/jsonwebtoken/Claims.java
2,196
/* * 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.kafka.common.config; import org.apache.kafka.common.config.ConfigDef.Range; public class SaslConfigs { private static final String OAUTHBEARER_NOTE = " Currently applies only to OAUTHBEARER."; /* * NOTE: DO NOT CHANGE EITHER CONFIG NAMES AS THESE ARE PART OF THE PUBLIC API AND CHANGE WILL BREAK USER CODE. */ /** SASL mechanism configuration - standard mechanism names are listed <a href="http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml">here</a>. */ public static final String SASL_MECHANISM = "sasl.mechanism"; public static final String SASL_MECHANISM_DOC = "SASL mechanism used for client connections. This may be any mechanism for which a security provider is available. GSSAPI is the default mechanism."; public static final String GSSAPI_MECHANISM = "GSSAPI"; public static final String DEFAULT_SASL_MECHANISM = GSSAPI_MECHANISM; public static final String SASL_JAAS_CONFIG = "sasl.jaas.config"; public static final String SASL_JAAS_CONFIG_DOC = "JAAS login context parameters for SASL connections in the format used by JAAS configuration files. " + "JAAS configuration file format is described <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/tutorials/LoginConfigFile.html\">here</a>. " + "The format for the value is: <code>loginModuleClass controlFlag (optionName=optionValue)*;</code>. For brokers, " + "the config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, " + "listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=com.example.ScramLoginModule required;"; public static final String SASL_CLIENT_CALLBACK_HANDLER_CLASS = "sasl.client.callback.handler.class"; public static final String SASL_CLIENT_CALLBACK_HANDLER_CLASS_DOC = "The fully qualified name of a SASL client callback handler class " + "that implements the AuthenticateCallbackHandler interface."; public static final String SASL_LOGIN_CALLBACK_HANDLER_CLASS = "sasl.login.callback.handler.class"; public static final String SASL_LOGIN_CALLBACK_HANDLER_CLASS_DOC = "The fully qualified name of a SASL login callback handler class " + "that implements the AuthenticateCallbackHandler interface. For brokers, login callback handler config must be prefixed with " + "listener prefix and SASL mechanism name in lower-case. For example, " + "listener.name.sasl_ssl.scram-sha-256.sasl.login.callback.handler.class=com.example.CustomScramLoginCallbackHandler"; public static final String SASL_LOGIN_CLASS = "sasl.login.class"; public static final String SASL_LOGIN_CLASS_DOC = "The fully qualified name of a class that implements the Login interface. " + "For brokers, login config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, " + "listener.name.sasl_ssl.scram-sha-256.sasl.login.class=com.example.CustomScramLogin"; public static final String SASL_KERBEROS_SERVICE_NAME = "sasl.kerberos.service.name"; public static final String SASL_KERBEROS_SERVICE_NAME_DOC = "The Kerberos principal name that Kafka runs as. " + "This can be defined either in Kafka's JAAS config or in Kafka's config."; public static final String SASL_KERBEROS_KINIT_CMD = "sasl.kerberos.kinit.cmd"; public static final String SASL_KERBEROS_KINIT_CMD_DOC = "Kerberos kinit command path."; public static final String DEFAULT_KERBEROS_KINIT_CMD = "/usr/bin/kinit"; public static final String SASL_KERBEROS_TICKET_RENEW_WINDOW_FACTOR = "sasl.kerberos.ticket.renew.window.factor"; public static final String SASL_KERBEROS_TICKET_RENEW_WINDOW_FACTOR_DOC = "Login thread will sleep until the specified window factor of time from last refresh" + " to ticket's expiry has been reached, at which time it will try to renew the ticket."; public static final double DEFAULT_KERBEROS_TICKET_RENEW_WINDOW_FACTOR = 0.80; public static final String SASL_KERBEROS_TICKET_RENEW_JITTER = "sasl.kerberos.ticket.renew.jitter"; public static final String SASL_KERBEROS_TICKET_RENEW_JITTER_DOC = "Percentage of random jitter added to the renewal time."; public static final double DEFAULT_KERBEROS_TICKET_RENEW_JITTER = 0.05; public static final String SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN = "sasl.kerberos.min.time.before.relogin"; public static final String SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN_DOC = "Login thread sleep time between refresh attempts."; public static final long DEFAULT_KERBEROS_MIN_TIME_BEFORE_RELOGIN = 1 * 60 * 1000L; public static final String SASL_LOGIN_REFRESH_WINDOW_FACTOR = "sasl.login.refresh.window.factor"; public static final String SASL_LOGIN_REFRESH_WINDOW_FACTOR_DOC = "Login refresh thread will sleep until the specified window factor relative to the" + " credential's lifetime has been reached, at which time it will try to refresh the credential." + " Legal values are between 0.5 (50%) and 1.0 (100%) inclusive; a default value of 0.8 (80%) is used" + " if no value is specified." + OAUTHBEARER_NOTE; public static final double DEFAULT_LOGIN_REFRESH_WINDOW_FACTOR = 0.80; public static final String SASL_LOGIN_REFRESH_WINDOW_JITTER = "sasl.login.refresh.window.jitter"; public static final String SASL_LOGIN_REFRESH_WINDOW_JITTER_DOC = "The maximum amount of random jitter relative to the credential's lifetime" + " that is added to the login refresh thread's sleep time. Legal values are between 0 and 0.25 (25%) inclusive;" + " a default value of 0.05 (5%) is used if no value is specified." + OAUTHBEARER_NOTE; public static final double DEFAULT_LOGIN_REFRESH_WINDOW_JITTER = 0.05; public static final String SASL_LOGIN_REFRESH_MIN_PERIOD_SECONDS = "sasl.login.refresh.min.period.seconds"; public static final String SASL_LOGIN_REFRESH_MIN_PERIOD_SECONDS_DOC = "The desired minimum time for the login refresh thread to wait before refreshing a credential," + " in seconds. Legal values are between 0 and 900 (15 minutes); a default value of 60 (1 minute) is used if no value is specified. This value and " + " sasl.login.refresh.buffer.seconds are both ignored if their sum exceeds the remaining lifetime of a credential." + OAUTHBEARER_NOTE; public static final short DEFAULT_LOGIN_REFRESH_MIN_PERIOD_SECONDS = 60; public static final String SASL_LOGIN_REFRESH_BUFFER_SECONDS = "sasl.login.refresh.buffer.seconds"; public static final String SASL_LOGIN_REFRESH_BUFFER_SECONDS_DOC = "The amount of buffer time before credential expiration to maintain when refreshing a credential," + " in seconds. If a refresh would otherwise occur closer to expiration than the number of buffer seconds then the refresh will be moved up to maintain" + " as much of the buffer time as possible. Legal values are between 0 and 3600 (1 hour); a default value of 300 (5 minutes) is used if no value is specified." + " This value and sasl.login.refresh.min.period.seconds are both ignored if their sum exceeds the remaining lifetime of a credential." + OAUTHBEARER_NOTE; public static final short DEFAULT_LOGIN_REFRESH_BUFFER_SECONDS = 300; public static final String SASL_LOGIN_CONNECT_TIMEOUT_MS = "sasl.login.connect.timeout.ms"; public static final String SASL_LOGIN_CONNECT_TIMEOUT_MS_DOC = "The (optional) value in milliseconds for the external authentication provider connection timeout." + OAUTHBEARER_NOTE; public static final String SASL_LOGIN_READ_TIMEOUT_MS = "sasl.login.read.timeout.ms"; public static final String SASL_LOGIN_READ_TIMEOUT_MS_DOC = "The (optional) value in milliseconds for the external authentication provider read timeout." + OAUTHBEARER_NOTE; private static final String LOGIN_EXPONENTIAL_BACKOFF_NOTE = " Login uses an exponential backoff algorithm with an initial wait based on the" + " sasl.login.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the" + " sasl.login.retry.backoff.max.ms setting." + OAUTHBEARER_NOTE; public static final String SASL_LOGIN_RETRY_BACKOFF_MAX_MS = "sasl.login.retry.backoff.max.ms"; public static final long DEFAULT_SASL_LOGIN_RETRY_BACKOFF_MAX_MS = 10000; public static final String SASL_LOGIN_RETRY_BACKOFF_MAX_MS_DOC = "The (optional) value in milliseconds for the maximum wait between login attempts to the" + " external authentication provider." + LOGIN_EXPONENTIAL_BACKOFF_NOTE; public static final String SASL_LOGIN_RETRY_BACKOFF_MS = "sasl.login.retry.backoff.ms"; public static final long DEFAULT_SASL_LOGIN_RETRY_BACKOFF_MS = 100; public static final String SASL_LOGIN_RETRY_BACKOFF_MS_DOC = "The (optional) value in milliseconds for the initial wait between login attempts to the external" + " authentication provider." + LOGIN_EXPONENTIAL_BACKOFF_NOTE; public static final String SASL_OAUTHBEARER_SCOPE_CLAIM_NAME = "sasl.oauthbearer.scope.claim.name"; public static final String DEFAULT_SASL_OAUTHBEARER_SCOPE_CLAIM_NAME = "scope"; public static final String SASL_OAUTHBEARER_SCOPE_CLAIM_NAME_DOC = "The OAuth claim for the scope is often named \"" + DEFAULT_SASL_OAUTHBEARER_SCOPE_CLAIM_NAME + "\", but this (optional)" + " setting can provide a different name to use for the scope included in the JWT payload's claims if the OAuth/OIDC provider uses a different" + " name for that claim."; public static final String SASL_OAUTHBEARER_SUB_CLAIM_NAME = "sasl.oauthbearer.sub.claim.name"; public static final String DEFAULT_SASL_OAUTHBEARER_SUB_CLAIM_NAME = "sub"; public static final String SASL_OAUTHBEARER_SUB_CLAIM_NAME_DOC = "The OAuth claim for the subject is often named \"" + DEFAULT_SASL_OAUTHBEARER_SUB_CLAIM_NAME + "\", but this (optional)" + " setting can provide a different name to use for the subject included in the JWT payload's claims if the OAuth/OIDC provider uses a different" + " name for that claim."; public static final String SASL_OAUTHBEARER_TOKEN_ENDPOINT_URL = "sasl.oauthbearer.token.endpoint.url"; public static final String SASL_OAUTHBEARER_TOKEN_ENDPOINT_URL_DOC = "The URL for the OAuth/OIDC identity provider. If the URL is HTTP(S)-based, it is the issuer's token" + " endpoint URL to which requests will be made to login based on the configuration in " + SASL_JAAS_CONFIG + ". If the URL is file-based, it" + " specifies a file containing an access token (in JWT serialized form) issued by the OAuth/OIDC identity provider to use for authorization."; public static final String SASL_OAUTHBEARER_JWKS_ENDPOINT_URL = "sasl.oauthbearer.jwks.endpoint.url"; public static final String SASL_OAUTHBEARER_JWKS_ENDPOINT_URL_DOC = "The OAuth/OIDC provider URL from which the provider's" + " <a href=\"https://datatracker.ietf.org/doc/html/rfc7517#section-5\">JWKS (JSON Web Key Set)</a> can be retrieved. The URL can be HTTP(S)-based or file-based." + " If the URL is HTTP(S)-based, the JWKS data will be retrieved from the OAuth/OIDC provider via the configured URL on broker startup. All then-current" + " keys will be cached on the broker for incoming requests. If an authentication request is received for a JWT that includes a \"kid\" header claim value that" + " isn't yet in the cache, the JWKS endpoint will be queried again on demand. However, the broker polls the URL every sasl.oauthbearer.jwks.endpoint.refresh.ms" + " milliseconds to refresh the cache with any forthcoming keys before any JWT requests that include them are received." + " If the URL is file-based, the broker will load the JWKS file from a configured location on startup. In the event that the JWT includes a \"kid\" header" + " value that isn't in the JWKS file, the broker will reject the JWT and authentication will fail."; public static final String SASL_OAUTHBEARER_JWKS_ENDPOINT_REFRESH_MS = "sasl.oauthbearer.jwks.endpoint.refresh.ms"; public static final long DEFAULT_SASL_OAUTHBEARER_JWKS_ENDPOINT_REFRESH_MS = 60 * 60 * 1000; public static final String SASL_OAUTHBEARER_JWKS_ENDPOINT_REFRESH_MS_DOC = "The (optional) value in milliseconds for the broker to wait between refreshing its JWKS (JSON Web Key Set)" + " cache that contains the keys to verify the signature of the JWT."; private static final String JWKS_EXPONENTIAL_BACKOFF_NOTE = " JWKS retrieval uses an exponential backoff algorithm with an initial wait based on the" + " sasl.oauthbearer.jwks.endpoint.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the" + " sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms setting."; public static final String SASL_OAUTHBEARER_JWKS_ENDPOINT_RETRY_BACKOFF_MAX_MS = "sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms"; public static final long DEFAULT_SASL_OAUTHBEARER_JWKS_ENDPOINT_RETRY_BACKOFF_MAX_MS = 10000; public static final String SASL_OAUTHBEARER_JWKS_ENDPOINT_RETRY_BACKOFF_MAX_MS_DOC = "The (optional) value in milliseconds for the maximum wait between attempts to retrieve the JWKS (JSON Web Key Set)" + " from the external authentication provider." + JWKS_EXPONENTIAL_BACKOFF_NOTE; public static final String SASL_OAUTHBEARER_JWKS_ENDPOINT_RETRY_BACKOFF_MS = "sasl.oauthbearer.jwks.endpoint.retry.backoff.ms"; public static final long DEFAULT_SASL_OAUTHBEARER_JWKS_ENDPOINT_RETRY_BACKOFF_MS = 100; public static final String SASL_OAUTHBEARER_JWKS_ENDPOINT_RETRY_BACKOFF_MS_DOC = "The (optional) value in milliseconds for the initial wait between JWKS (JSON Web Key Set) retrieval attempts from the external" + " authentication provider." + JWKS_EXPONENTIAL_BACKOFF_NOTE; public static final String SASL_OAUTHBEARER_CLOCK_SKEW_SECONDS = "sasl.oauthbearer.clock.skew.seconds"; public static final int DEFAULT_SASL_OAUTHBEARER_CLOCK_SKEW_SECONDS = 30; public static final String SASL_OAUTHBEARER_CLOCK_SKEW_SECONDS_DOC = "The (optional) value in seconds to allow for differences between the time of the OAuth/OIDC identity provider and" + " the broker."; public static final String SASL_OAUTHBEARER_EXPECTED_AUDIENCE = "sasl.oauthbearer.expected.audience"; public static final String SASL_OAUTHBEARER_EXPECTED_AUDIENCE_DOC = "The (optional) comma-delimited setting for the broker to use to verify that the JWT was issued for one of the" + " expected audiences. The JWT will be inspected for the standard OAuth \"aud\" claim and if this value is set, the broker will match the value from JWT's \"aud\" claim " + " to see if there is an exact match. If there is no match, the broker will reject the JWT and authentication will fail."; public static final String SASL_OAUTHBEARER_EXPECTED_ISSUER = "sasl.oauthbearer.expected.issuer"; public static final String SASL_OAUTHBEARER_EXPECTED_ISSUER_DOC = "The (optional) setting for the broker to use to verify that the JWT was created by the expected issuer. The JWT will" + " be inspected for the standard OAuth \"iss\" claim and if this value is set, the broker will match it exactly against what is in the JWT's \"iss\" claim. If there is no" + " match, the broker will reject the JWT and authentication will fail."; public static void addClientSaslSupport(ConfigDef config) { config.define(SaslConfigs.SASL_KERBEROS_SERVICE_NAME, ConfigDef.Type.STRING, null, ConfigDef.Importance.MEDIUM, SaslConfigs.SASL_KERBEROS_SERVICE_NAME_DOC) .define(SaslConfigs.SASL_KERBEROS_KINIT_CMD, ConfigDef.Type.STRING, SaslConfigs.DEFAULT_KERBEROS_KINIT_CMD, ConfigDef.Importance.LOW, SaslConfigs.SASL_KERBEROS_KINIT_CMD_DOC) .define(SaslConfigs.SASL_KERBEROS_TICKET_RENEW_WINDOW_FACTOR, ConfigDef.Type.DOUBLE, SaslConfigs.DEFAULT_KERBEROS_TICKET_RENEW_WINDOW_FACTOR, ConfigDef.Importance.LOW, SaslConfigs.SASL_KERBEROS_TICKET_RENEW_WINDOW_FACTOR_DOC) .define(SaslConfigs.SASL_KERBEROS_TICKET_RENEW_JITTER, ConfigDef.Type.DOUBLE, SaslConfigs.DEFAULT_KERBEROS_TICKET_RENEW_JITTER, ConfigDef.Importance.LOW, SaslConfigs.SASL_KERBEROS_TICKET_RENEW_JITTER_DOC) .define(SaslConfigs.SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN, ConfigDef.Type.LONG, SaslConfigs.DEFAULT_KERBEROS_MIN_TIME_BEFORE_RELOGIN, ConfigDef.Importance.LOW, SaslConfigs.SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN_DOC) .define(SaslConfigs.SASL_LOGIN_REFRESH_WINDOW_FACTOR, ConfigDef.Type.DOUBLE, SaslConfigs.DEFAULT_LOGIN_REFRESH_WINDOW_FACTOR, Range.between(0.5, 1.0), ConfigDef.Importance.LOW, SaslConfigs.SASL_LOGIN_REFRESH_WINDOW_FACTOR_DOC) .define(SaslConfigs.SASL_LOGIN_REFRESH_WINDOW_JITTER, ConfigDef.Type.DOUBLE, SaslConfigs.DEFAULT_LOGIN_REFRESH_WINDOW_JITTER, Range.between(0.0, 0.25), ConfigDef.Importance.LOW, SaslConfigs.SASL_LOGIN_REFRESH_WINDOW_JITTER_DOC) .define(SaslConfigs.SASL_LOGIN_REFRESH_MIN_PERIOD_SECONDS, ConfigDef.Type.SHORT, SaslConfigs.DEFAULT_LOGIN_REFRESH_MIN_PERIOD_SECONDS, Range.between(0, 900), ConfigDef.Importance.LOW, SaslConfigs.SASL_LOGIN_REFRESH_MIN_PERIOD_SECONDS_DOC) .define(SaslConfigs.SASL_LOGIN_REFRESH_BUFFER_SECONDS, ConfigDef.Type.SHORT, SaslConfigs.DEFAULT_LOGIN_REFRESH_BUFFER_SECONDS, Range.between(0, 3600), ConfigDef.Importance.LOW, SaslConfigs.SASL_LOGIN_REFRESH_BUFFER_SECONDS_DOC) .define(SaslConfigs.SASL_MECHANISM, ConfigDef.Type.STRING, SaslConfigs.DEFAULT_SASL_MECHANISM, ConfigDef.Importance.MEDIUM, SaslConfigs.SASL_MECHANISM_DOC) .define(SaslConfigs.SASL_JAAS_CONFIG, ConfigDef.Type.PASSWORD, null, ConfigDef.Importance.MEDIUM, SaslConfigs.SASL_JAAS_CONFIG_DOC) .define(SaslConfigs.SASL_CLIENT_CALLBACK_HANDLER_CLASS, ConfigDef.Type.CLASS, null, ConfigDef.Importance.MEDIUM, SaslConfigs.SASL_CLIENT_CALLBACK_HANDLER_CLASS_DOC) .define(SaslConfigs.SASL_LOGIN_CALLBACK_HANDLER_CLASS, ConfigDef.Type.CLASS, null, ConfigDef.Importance.MEDIUM, SaslConfigs.SASL_LOGIN_CALLBACK_HANDLER_CLASS_DOC) .define(SaslConfigs.SASL_LOGIN_CLASS, ConfigDef.Type.CLASS, null, ConfigDef.Importance.MEDIUM, SaslConfigs.SASL_LOGIN_CLASS_DOC) .define(SaslConfigs.SASL_LOGIN_CONNECT_TIMEOUT_MS, ConfigDef.Type.INT, null, ConfigDef.Importance.LOW, SASL_LOGIN_CONNECT_TIMEOUT_MS_DOC) .define(SaslConfigs.SASL_LOGIN_READ_TIMEOUT_MS, ConfigDef.Type.INT, null, ConfigDef.Importance.LOW, SASL_LOGIN_READ_TIMEOUT_MS_DOC) .define(SaslConfigs.SASL_LOGIN_RETRY_BACKOFF_MAX_MS, ConfigDef.Type.LONG, DEFAULT_SASL_LOGIN_RETRY_BACKOFF_MAX_MS, ConfigDef.Importance.LOW, SASL_LOGIN_RETRY_BACKOFF_MAX_MS_DOC) .define(SaslConfigs.SASL_LOGIN_RETRY_BACKOFF_MS, ConfigDef.Type.LONG, DEFAULT_SASL_LOGIN_RETRY_BACKOFF_MS, ConfigDef.Importance.LOW, SASL_LOGIN_RETRY_BACKOFF_MS_DOC) .define(SaslConfigs.SASL_OAUTHBEARER_SCOPE_CLAIM_NAME, ConfigDef.Type.STRING, DEFAULT_SASL_OAUTHBEARER_SCOPE_CLAIM_NAME, ConfigDef.Importance.LOW, SASL_OAUTHBEARER_SCOPE_CLAIM_NAME_DOC) .define(SaslConfigs.SASL_OAUTHBEARER_SUB_CLAIM_NAME, ConfigDef.Type.STRING, DEFAULT_SASL_OAUTHBEARER_SUB_CLAIM_NAME, ConfigDef.Importance.LOW, SASL_OAUTHBEARER_SUB_CLAIM_NAME_DOC) .define(SaslConfigs.SASL_OAUTHBEARER_TOKEN_ENDPOINT_URL, ConfigDef.Type.STRING, null, ConfigDef.Importance.MEDIUM, SASL_OAUTHBEARER_TOKEN_ENDPOINT_URL_DOC) .define(SaslConfigs.SASL_OAUTHBEARER_JWKS_ENDPOINT_URL, ConfigDef.Type.STRING, null, ConfigDef.Importance.MEDIUM, SASL_OAUTHBEARER_JWKS_ENDPOINT_URL_DOC) .define(SaslConfigs.SASL_OAUTHBEARER_JWKS_ENDPOINT_REFRESH_MS, ConfigDef.Type.LONG, DEFAULT_SASL_OAUTHBEARER_JWKS_ENDPOINT_REFRESH_MS, ConfigDef.Importance.LOW, SASL_OAUTHBEARER_JWKS_ENDPOINT_REFRESH_MS_DOC) .define(SaslConfigs.SASL_OAUTHBEARER_JWKS_ENDPOINT_RETRY_BACKOFF_MAX_MS, ConfigDef.Type.LONG, DEFAULT_SASL_OAUTHBEARER_JWKS_ENDPOINT_RETRY_BACKOFF_MAX_MS, ConfigDef.Importance.LOW, SASL_OAUTHBEARER_JWKS_ENDPOINT_RETRY_BACKOFF_MAX_MS_DOC) .define(SaslConfigs.SASL_OAUTHBEARER_JWKS_ENDPOINT_RETRY_BACKOFF_MS, ConfigDef.Type.LONG, DEFAULT_SASL_OAUTHBEARER_JWKS_ENDPOINT_RETRY_BACKOFF_MS, ConfigDef.Importance.LOW, SASL_OAUTHBEARER_JWKS_ENDPOINT_RETRY_BACKOFF_MS_DOC) .define(SaslConfigs.SASL_OAUTHBEARER_CLOCK_SKEW_SECONDS, ConfigDef.Type.INT, DEFAULT_SASL_OAUTHBEARER_CLOCK_SKEW_SECONDS, ConfigDef.Importance.LOW, SASL_OAUTHBEARER_CLOCK_SKEW_SECONDS_DOC) .define(SaslConfigs.SASL_OAUTHBEARER_EXPECTED_AUDIENCE, ConfigDef.Type.LIST, null, ConfigDef.Importance.LOW, SASL_OAUTHBEARER_EXPECTED_AUDIENCE_DOC) .define(SaslConfigs.SASL_OAUTHBEARER_EXPECTED_ISSUER, ConfigDef.Type.STRING, null, ConfigDef.Importance.LOW, SASL_OAUTHBEARER_EXPECTED_ISSUER_DOC); } }
apache/kafka
clients/src/main/java/org/apache/kafka/common/config/SaslConfigs.java
2,197
/* * 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.cassandra.config; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.function.Supplier; import javax.annotation.Nullable; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.audit.AuditLogOptions; import org.apache.cassandra.db.ConsistencyLevel; import org.apache.cassandra.fql.FullQueryLoggerOptions; import org.apache.cassandra.index.internal.CassandraIndex; import org.apache.cassandra.io.compress.BufferType; import org.apache.cassandra.io.sstable.format.big.BigFormat; import org.apache.cassandra.service.StartupChecks.StartupCheckType; import org.apache.cassandra.utils.StorageCompatibilityMode; import static org.apache.cassandra.config.CassandraRelevantProperties.AUTOCOMPACTION_ON_STARTUP_ENABLED; import static org.apache.cassandra.config.CassandraRelevantProperties.FILE_CACHE_ENABLED; import static org.apache.cassandra.config.CassandraRelevantProperties.SKIP_PAXOS_REPAIR_ON_TOPOLOGY_CHANGE; import static org.apache.cassandra.config.CassandraRelevantProperties.SKIP_PAXOS_REPAIR_ON_TOPOLOGY_CHANGE_KEYSPACES; /** * A class that contains configuration properties for the cassandra node it runs within. * <p> * Properties declared as volatile can be mutated via JMX. */ public class Config { private static final Logger logger = LoggerFactory.getLogger(Config.class); public static Set<String> splitCommaDelimited(String src) { if (src == null) return ImmutableSet.of(); String[] split = src.split(",\\s*"); ImmutableSet.Builder<String> builder = ImmutableSet.builder(); for (String s : split) { s = s.trim(); if (!s.isEmpty()) builder.add(s); } return builder.build(); } /* * Prefix for Java properties for internal Cassandra configuration options */ public static final String PROPERTY_PREFIX = "cassandra."; public String cluster_name = "Test Cluster"; public ParameterizedClass authenticator; public String authorizer; public String role_manager; public ParameterizedClass crypto_provider; public String network_authorizer; public ParameterizedClass cidr_authorizer; @Replaces(oldName = "permissions_validity_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public volatile DurationSpec.IntMillisecondsBound permissions_validity = new DurationSpec.IntMillisecondsBound("2s"); public volatile int permissions_cache_max_entries = 1000; @Replaces(oldName = "permissions_update_interval_in_ms", converter = Converters.MILLIS_CUSTOM_DURATION, deprecated = true) public volatile DurationSpec.IntMillisecondsBound permissions_update_interval = null; public volatile boolean permissions_cache_active_update = false; @Replaces(oldName = "roles_validity_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public volatile DurationSpec.IntMillisecondsBound roles_validity = new DurationSpec.IntMillisecondsBound("2s"); public volatile int roles_cache_max_entries = 1000; @Replaces(oldName = "roles_update_interval_in_ms", converter = Converters.MILLIS_CUSTOM_DURATION, deprecated = true) public volatile DurationSpec.IntMillisecondsBound roles_update_interval = null; public volatile boolean roles_cache_active_update = false; @Replaces(oldName = "credentials_validity_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public volatile DurationSpec.IntMillisecondsBound credentials_validity = new DurationSpec.IntMillisecondsBound("2s"); public volatile int credentials_cache_max_entries = 1000; @Replaces(oldName = "credentials_update_interval_in_ms", converter = Converters.MILLIS_CUSTOM_DURATION, deprecated = true) public volatile DurationSpec.IntMillisecondsBound credentials_update_interval = null; public volatile boolean credentials_cache_active_update = false; /* Hashing strategy Random or OPHF */ public String partitioner; public boolean auto_bootstrap = true; public volatile boolean hinted_handoff_enabled = true; public Set<String> hinted_handoff_disabled_datacenters = Sets.newConcurrentHashSet(); @Replaces(oldName = "max_hint_window_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public volatile DurationSpec.IntMillisecondsBound max_hint_window = new DurationSpec.IntMillisecondsBound("3h"); public String hints_directory; public boolean hint_window_persistent_enabled = true; public volatile boolean force_new_prepared_statement_behaviour = false; public ParameterizedClass seed_provider; public DiskAccessMode disk_access_mode = DiskAccessMode.mmap_index_only; public DiskFailurePolicy disk_failure_policy = DiskFailurePolicy.ignore; public CommitFailurePolicy commit_failure_policy = CommitFailurePolicy.stop; public volatile boolean use_deterministic_table_id = false; /* initial token in the ring */ public String initial_token; public Integer num_tokens; /** Triggers automatic allocation of tokens if set, using the replication strategy of the referenced keyspace */ public String allocate_tokens_for_keyspace = null; /** Triggers automatic allocation of tokens if set, based on the provided replica count for a datacenter */ public Integer allocate_tokens_for_local_replication_factor = null; @Replaces(oldName = "native_transport_idle_timeout_in_ms", converter = Converters.MILLIS_DURATION_LONG, deprecated = true) public DurationSpec.LongMillisecondsBound native_transport_idle_timeout = new DurationSpec.LongMillisecondsBound("0ms"); @Replaces(oldName = "request_timeout_in_ms", converter = Converters.MILLIS_DURATION_LONG, deprecated = true) public volatile DurationSpec.LongMillisecondsBound request_timeout = new DurationSpec.LongMillisecondsBound("10000ms"); @Replaces(oldName = "read_request_timeout_in_ms", converter = Converters.MILLIS_DURATION_LONG, deprecated = true) public volatile DurationSpec.LongMillisecondsBound read_request_timeout = new DurationSpec.LongMillisecondsBound("5000ms"); @Replaces(oldName = "range_request_timeout_in_ms", converter = Converters.MILLIS_DURATION_LONG, deprecated = true) public volatile DurationSpec.LongMillisecondsBound range_request_timeout = new DurationSpec.LongMillisecondsBound("10000ms"); @Replaces(oldName = "write_request_timeout_in_ms", converter = Converters.MILLIS_DURATION_LONG, deprecated = true) public volatile DurationSpec.LongMillisecondsBound write_request_timeout = new DurationSpec.LongMillisecondsBound("2000ms"); @Replaces(oldName = "counter_write_request_timeout_in_ms", converter = Converters.MILLIS_DURATION_LONG, deprecated = true) public volatile DurationSpec.LongMillisecondsBound counter_write_request_timeout = new DurationSpec.LongMillisecondsBound("5000ms"); @Replaces(oldName = "cas_contention_timeout_in_ms", converter = Converters.MILLIS_DURATION_LONG, deprecated = true) public volatile DurationSpec.LongMillisecondsBound cas_contention_timeout = new DurationSpec.LongMillisecondsBound("1800ms"); @Replaces(oldName = "truncate_request_timeout_in_ms", converter = Converters.MILLIS_DURATION_LONG, deprecated = true) public volatile DurationSpec.LongMillisecondsBound truncate_request_timeout = new DurationSpec.LongMillisecondsBound("60000ms"); @Replaces(oldName = "repair_request_timeout_in_ms", converter = Converters.MILLIS_DURATION_LONG, deprecated = true) public volatile DurationSpec.LongMillisecondsBound repair_request_timeout = new DurationSpec.LongMillisecondsBound("120000ms"); public Integer streaming_connections_per_host = 1; @Replaces(oldName = "streaming_keep_alive_period_in_secs", converter = Converters.SECONDS_DURATION, deprecated = true) public DurationSpec.IntSecondsBound streaming_keep_alive_period = new DurationSpec.IntSecondsBound("300s"); @Replaces(oldName = "cross_node_timeout", converter = Converters.IDENTITY, deprecated = true) public boolean internode_timeout = true; @Replaces(oldName = "slow_query_log_timeout_in_ms", converter = Converters.MILLIS_DURATION_LONG, deprecated = true) public volatile DurationSpec.LongMillisecondsBound slow_query_log_timeout = new DurationSpec.LongMillisecondsBound("500ms"); public volatile DurationSpec.LongMillisecondsBound stream_transfer_task_timeout = new DurationSpec.LongMillisecondsBound("12h"); public volatile DurationSpec.LongMillisecondsBound cms_await_timeout = new DurationSpec.LongMillisecondsBound("120000ms"); public volatile int cms_default_max_retries = 10; public volatile DurationSpec.IntMillisecondsBound cms_default_retry_backoff = new DurationSpec.IntMillisecondsBound("50ms"); /** * How often we should snapshot the cluster metadata. */ public volatile int metadata_snapshot_frequency = 100; public volatile double phi_convict_threshold = 8.0; public int concurrent_reads = 32; public int concurrent_writes = 32; public int concurrent_counter_writes = 32; public int concurrent_materialized_view_writes = 32; public int available_processors = -1; public int memtable_flush_writers = 0; @Replaces(oldName = "memtable_heap_space_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public DataStorageSpec.IntMebibytesBound memtable_heap_space; @Replaces(oldName = "memtable_offheap_space_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public DataStorageSpec.IntMebibytesBound memtable_offheap_space; public Float memtable_cleanup_threshold = null; public static class MemtableOptions { public LinkedHashMap<String, InheritingClass> configurations; // order must be preserved public MemtableOptions() { } } public MemtableOptions memtable; // Limit the maximum depth of repair session merkle trees /** @deprecated See */ @Deprecated(since = "4.0") public volatile Integer repair_session_max_tree_depth = null; @Replaces(oldName = "repair_session_space_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public volatile DataStorageSpec.IntMebibytesBound repair_session_space = null; public volatile int concurrent_merkle_tree_requests = 0; public volatile boolean use_offheap_merkle_trees = true; public int storage_port = 7000; public int ssl_storage_port = 7001; public String listen_address; public String listen_interface; public boolean listen_interface_prefer_ipv6 = false; public String broadcast_address; public boolean listen_on_broadcast_address = false; public ParameterizedClass internode_authenticator; public boolean traverse_auth_from_root = false; /* * RPC address and interface refer to the address/interface used for the native protocol used to communicate with * clients. It's still called RPC in some places even though Thrift RPC is gone. If you see references to native * address or native port it's derived from the RPC address configuration. * * native_transport_port is the port that is paired with RPC address to bind on. */ public String rpc_address; public String rpc_interface; public boolean rpc_interface_prefer_ipv6 = false; public String broadcast_rpc_address; public boolean rpc_keepalive = true; @Replaces(oldName = "internode_max_message_size_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated=true) public DataStorageSpec.IntBytesBound internode_max_message_size; @Replaces(oldName = "internode_socket_send_buffer_size_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true) @Replaces(oldName = "internode_send_buff_size_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntBytesBound internode_socket_send_buffer_size = new DataStorageSpec.IntBytesBound("0B"); @Replaces(oldName = "internode_socket_receive_buffer_size_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true) @Replaces(oldName = "internode_recv_buff_size_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntBytesBound internode_socket_receive_buffer_size = new DataStorageSpec.IntBytesBound("0B"); // TODO: derive defaults from system memory settings? @Replaces(oldName = "internode_application_send_queue_capacity_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntBytesBound internode_application_send_queue_capacity = new DataStorageSpec.IntBytesBound("4MiB"); @Replaces(oldName = "internode_application_send_queue_reserve_endpoint_capacity_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntBytesBound internode_application_send_queue_reserve_endpoint_capacity = new DataStorageSpec.IntBytesBound("128MiB"); @Replaces(oldName = "internode_application_send_queue_reserve_global_capacity_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntBytesBound internode_application_send_queue_reserve_global_capacity = new DataStorageSpec.IntBytesBound("512MiB"); @Replaces(oldName = "internode_application_receive_queue_capacity_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntBytesBound internode_application_receive_queue_capacity = new DataStorageSpec.IntBytesBound("4MiB"); @Replaces(oldName = "internode_application_receive_queue_reserve_endpoint_capacity_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntBytesBound internode_application_receive_queue_reserve_endpoint_capacity = new DataStorageSpec.IntBytesBound("128MiB"); @Replaces(oldName = "internode_application_receive_queue_reserve_global_capacity_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntBytesBound internode_application_receive_queue_reserve_global_capacity = new DataStorageSpec.IntBytesBound("512MiB"); // Defensive settings for protecting Cassandra from true network partitions. See (CASSANDRA-14358) for details. // The amount of time to wait for internode tcp connections to establish. @Replaces(oldName = "internode_tcp_connect_timeout_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public volatile DurationSpec.IntMillisecondsBound internode_tcp_connect_timeout = new DurationSpec.IntMillisecondsBound("2s"); // The amount of time unacknowledged data is allowed on a connection before we throw out the connection // Note this is only supported on Linux + epoll, and it appears to behave oddly above a setting of 30000 // (it takes much longer than 30s) as of Linux 4.12. If you want something that high set this to 0 // (which picks up the OS default) and configure the net.ipv4.tcp_retries2 sysctl to be ~8. @Replaces(oldName = "internode_tcp_user_timeout_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public volatile DurationSpec.IntMillisecondsBound internode_tcp_user_timeout = new DurationSpec.IntMillisecondsBound("30s"); // Similar to internode_tcp_user_timeout but used specifically for streaming connection. // The default is 5 minutes. Increase it or set it to 0 in order to increase the timeout. @Replaces(oldName = "internode_streaming_tcp_user_timeout_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public volatile DurationSpec.IntMillisecondsBound internode_streaming_tcp_user_timeout = new DurationSpec.IntMillisecondsBound("300s"); // 5 minutes public boolean start_native_transport = true; public int native_transport_port = 9042; public int native_transport_max_threads = 128; @Replaces(oldName = "native_transport_max_frame_size_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public DataStorageSpec.IntMebibytesBound native_transport_max_frame_size = new DataStorageSpec.IntMebibytesBound("16MiB"); /** do bcrypt hashing in a limited pool to prevent cpu load spikes; note: any value < 1 will be set to 1 on init **/ public int native_transport_max_auth_threads = 4; public volatile long native_transport_max_concurrent_connections = -1L; public volatile long native_transport_max_concurrent_connections_per_ip = -1L; public boolean native_transport_flush_in_batches_legacy = false; public volatile boolean native_transport_allow_older_protocols = true; // Below 2 parameters were fixed in 4.0 + to get default value when ==-1 (old name and value format) or ==null(new name and value format), // not <=0 as it is in previous versions. Throwing config exceptions on < -1 @Replaces(oldName = "native_transport_max_concurrent_requests_in_bytes_per_ip", converter = Converters.BYTES_CUSTOM_DATASTORAGE, deprecated = true) public volatile DataStorageSpec.LongBytesBound native_transport_max_request_data_in_flight_per_ip = null; @Replaces(oldName = "native_transport_max_concurrent_requests_in_bytes", converter = Converters.BYTES_CUSTOM_DATASTORAGE, deprecated = true) public volatile DataStorageSpec.LongBytesBound native_transport_max_request_data_in_flight = null; public volatile boolean native_transport_rate_limiting_enabled = false; public volatile int native_transport_max_requests_per_second = 1000000; @Replaces(oldName = "native_transport_receive_queue_capacity_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntBytesBound native_transport_receive_queue_capacity = new DataStorageSpec.IntBytesBound("1MiB"); /** * Max size of values in SSTables, in MebiBytes. * Default is the same as the native protocol frame limit: 256MiB. * See AbstractType for how it is used. */ @Replaces(oldName = "max_value_size_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public DataStorageSpec.IntMebibytesBound max_value_size = new DataStorageSpec.IntMebibytesBound("256MiB"); public boolean snapshot_before_compaction = false; public boolean auto_snapshot = true; /** * When auto_snapshot is true and this property * is set, snapshots created by truncation or * drop use this TTL. */ public String auto_snapshot_ttl; public volatile long snapshot_links_per_second = 0; /* if the size of columns or super-columns are more than this, indexing will kick in */ @Replaces(oldName = "column_index_size_in_kb", converter = Converters.KIBIBYTES_DATASTORAGE, deprecated = true) public volatile DataStorageSpec.IntKibibytesBound column_index_size; @Replaces(oldName = "column_index_cache_size_in_kb", converter = Converters.KIBIBYTES_DATASTORAGE, deprecated = true) public volatile DataStorageSpec.IntKibibytesBound column_index_cache_size = new DataStorageSpec.IntKibibytesBound("2KiB"); @Replaces(oldName = "batch_size_warn_threshold_in_kb", converter = Converters.KIBIBYTES_DATASTORAGE, deprecated = true) public volatile DataStorageSpec.IntKibibytesBound batch_size_warn_threshold = new DataStorageSpec.IntKibibytesBound("5KiB"); @Replaces(oldName = "batch_size_fail_threshold_in_kb", converter = Converters.KIBIBYTES_DATASTORAGE, deprecated = true) public volatile DataStorageSpec.IntKibibytesBound batch_size_fail_threshold = new DataStorageSpec.IntKibibytesBound("50KiB"); public Integer unlogged_batch_across_partitions_warn_threshold = 10; public volatile Integer concurrent_compactors; @Replaces(oldName = "compaction_throughput_mb_per_sec", converter = Converters.MEBIBYTES_PER_SECOND_DATA_RATE, deprecated = true) public volatile DataRateSpec.LongBytesPerSecondBound compaction_throughput = new DataRateSpec.LongBytesPerSecondBound("64MiB/s"); @Replaces(oldName = "min_free_space_per_drive_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public DataStorageSpec.IntMebibytesBound min_free_space_per_drive = new DataStorageSpec.IntMebibytesBound("50MiB"); // fraction of free disk space available for compaction after min free space is subtracted public volatile Double max_space_usable_for_compactions_in_percentage = .95; public volatile int concurrent_materialized_view_builders = 1; public volatile int reject_repair_compaction_threshold = Integer.MAX_VALUE; // The number of executors to use for building secondary indexes public volatile int concurrent_index_builders = 2; /** * @deprecated retry support removed on CASSANDRA-10992 */ /** @deprecated See CASSANDRA-17378 */ @Deprecated(since = "4.1") public int max_streaming_retries = 3; @Replaces(oldName = "stream_throughput_outbound_megabits_per_sec", converter = Converters.MEGABITS_TO_BYTES_PER_SECOND_DATA_RATE, deprecated = true) public volatile DataRateSpec.LongBytesPerSecondBound stream_throughput_outbound = new DataRateSpec.LongBytesPerSecondBound("24MiB/s"); @Replaces(oldName = "inter_dc_stream_throughput_outbound_megabits_per_sec", converter = Converters.MEGABITS_TO_BYTES_PER_SECOND_DATA_RATE, deprecated = true) public volatile DataRateSpec.LongBytesPerSecondBound inter_dc_stream_throughput_outbound = new DataRateSpec.LongBytesPerSecondBound("24MiB/s"); public volatile DataRateSpec.LongBytesPerSecondBound entire_sstable_stream_throughput_outbound = new DataRateSpec.LongBytesPerSecondBound("24MiB/s"); public volatile DataRateSpec.LongBytesPerSecondBound entire_sstable_inter_dc_stream_throughput_outbound = new DataRateSpec.LongBytesPerSecondBound("24MiB/s"); public String[] data_file_directories = new String[0]; public static class SSTableConfig { public String selected_format = BigFormat.NAME; public Map<String, Map<String, String>> format = new HashMap<>(); } public final SSTableConfig sstable = new SSTableConfig(); /** * The directory to use for storing the system keyspaces data. * If unspecified the data will be stored in the first of the data_file_directories. */ public String local_system_data_file_directory; public String saved_caches_directory; // Commit Log public String commitlog_directory; @Replaces(oldName = "commitlog_total_space_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public DataStorageSpec.IntMebibytesBound commitlog_total_space; public CommitLogSync commitlog_sync; @Replaces(oldName = "commitlog_sync_group_window_in_ms", converter = Converters.MILLIS_DURATION_DOUBLE, deprecated = true) public DurationSpec.IntMillisecondsBound commitlog_sync_group_window = new DurationSpec.IntMillisecondsBound("0ms"); @Replaces(oldName = "commitlog_sync_period_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public DurationSpec.IntMillisecondsBound commitlog_sync_period = new DurationSpec.IntMillisecondsBound("0ms"); @Replaces(oldName = "commitlog_segment_size_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public DataStorageSpec.IntMebibytesBound commitlog_segment_size = new DataStorageSpec.IntMebibytesBound("32MiB"); public ParameterizedClass commitlog_compression; public FlushCompression flush_compression = FlushCompression.fast; public int commitlog_max_compression_buffers_in_pool = 3; public DiskAccessMode commitlog_disk_access_mode = DiskAccessMode.legacy; @Replaces(oldName = "periodic_commitlog_sync_lag_block_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public DurationSpec.IntMillisecondsBound periodic_commitlog_sync_lag_block; public TransparentDataEncryptionOptions transparent_data_encryption_options = new TransparentDataEncryptionOptions(); @Replaces(oldName = "max_mutation_size_in_kb", converter = Converters.KIBIBYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntKibibytesBound max_mutation_size; // Change-data-capture logs public boolean cdc_enabled = false; // When true, new CDC mutations are rejected/blocked when reaching max CDC storage. // When false, new CDC mutations can always be added. But it will remove the oldest CDC commit log segment on full. public volatile boolean cdc_block_writes = true; // When true, CDC data in SSTable go through commit logs during internodes streaming, e.g. repair // When false, it behaves the same as normal streaming. public volatile boolean cdc_on_repair_enabled = true; public String cdc_raw_directory; @Replaces(oldName = "cdc_total_space_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public DataStorageSpec.IntMebibytesBound cdc_total_space = new DataStorageSpec.IntMebibytesBound("0MiB"); @Replaces(oldName = "cdc_free_space_check_interval_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public DurationSpec.IntMillisecondsBound cdc_free_space_check_interval = new DurationSpec.IntMillisecondsBound("250ms"); public String endpoint_snitch; public boolean dynamic_snitch = true; @Replaces(oldName = "dynamic_snitch_update_interval_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public DurationSpec.IntMillisecondsBound dynamic_snitch_update_interval = new DurationSpec.IntMillisecondsBound("100ms"); @Replaces(oldName = "dynamic_snitch_reset_interval_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public DurationSpec.IntMillisecondsBound dynamic_snitch_reset_interval = new DurationSpec.IntMillisecondsBound("10m"); public double dynamic_snitch_badness_threshold = 1.0; public String failure_detector = "FailureDetector"; public EncryptionOptions.ServerEncryptionOptions server_encryption_options = new EncryptionOptions.ServerEncryptionOptions(); public EncryptionOptions client_encryption_options = new EncryptionOptions(); public InternodeCompression internode_compression = InternodeCompression.none; @Replaces(oldName = "hinted_handoff_throttle_in_kb", converter = Converters.KIBIBYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntKibibytesBound hinted_handoff_throttle = new DataStorageSpec.IntKibibytesBound("1024KiB"); @Replaces(oldName = "batchlog_replay_throttle_in_kb", converter = Converters.KIBIBYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntKibibytesBound batchlog_replay_throttle = new DataStorageSpec.IntKibibytesBound("1024KiB"); public int max_hints_delivery_threads = 2; @Replaces(oldName = "hints_flush_period_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public DurationSpec.IntMillisecondsBound hints_flush_period = new DurationSpec.IntMillisecondsBound("10s"); @Replaces(oldName = "max_hints_file_size_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public DataStorageSpec.IntMebibytesBound max_hints_file_size = new DataStorageSpec.IntMebibytesBound("128MiB"); public volatile DataStorageSpec.LongBytesBound max_hints_size_per_host = new DataStorageSpec.LongBytesBound("0B"); // 0 means disabled public ParameterizedClass hints_compression; public volatile boolean auto_hints_cleanup_enabled = false; public volatile boolean transfer_hints_on_decommission = true; public volatile boolean incremental_backups = false; public boolean trickle_fsync = false; @Replaces(oldName = "trickle_fsync_interval_in_kb", converter = Converters.KIBIBYTES_DATASTORAGE, deprecated = true) public DataStorageSpec.IntKibibytesBound trickle_fsync_interval = new DataStorageSpec.IntKibibytesBound("10240KiB"); @Nullable @Replaces(oldName = "sstable_preemptive_open_interval_in_mb", converter = Converters.NEGATIVE_MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public volatile DataStorageSpec.IntMebibytesBound sstable_preemptive_open_interval = new DataStorageSpec.IntMebibytesBound("50MiB"); public volatile boolean key_cache_migrate_during_compaction = true; public volatile int key_cache_keys_to_save = Integer.MAX_VALUE; @Replaces(oldName = "key_cache_size_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_LONG, deprecated = true) public DataStorageSpec.LongMebibytesBound key_cache_size = null; @Replaces(oldName = "key_cache_save_period", converter = Converters.SECONDS_CUSTOM_DURATION) public volatile DurationSpec.IntSecondsBound key_cache_save_period = new DurationSpec.IntSecondsBound("4h"); public String row_cache_class_name = "org.apache.cassandra.cache.OHCProvider"; @Replaces(oldName = "row_cache_size_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_LONG, deprecated = true) public DataStorageSpec.LongMebibytesBound row_cache_size = new DataStorageSpec.LongMebibytesBound("0MiB"); @Replaces(oldName = "row_cache_save_period", converter = Converters.SECONDS_CUSTOM_DURATION) public volatile DurationSpec.IntSecondsBound row_cache_save_period = new DurationSpec.IntSecondsBound("0s"); public volatile int row_cache_keys_to_save = Integer.MAX_VALUE; @Replaces(oldName = "counter_cache_size_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_LONG, deprecated = true) public DataStorageSpec.LongMebibytesBound counter_cache_size = null; @Replaces(oldName = "counter_cache_save_period", converter = Converters.SECONDS_CUSTOM_DURATION) public volatile DurationSpec.IntSecondsBound counter_cache_save_period = new DurationSpec.IntSecondsBound("7200s"); public volatile int counter_cache_keys_to_save = Integer.MAX_VALUE; public DataStorageSpec.LongMebibytesBound paxos_cache_size = null; @Replaces(oldName = "cache_load_timeout_seconds", converter = Converters.NEGATIVE_SECONDS_DURATION, deprecated = true) public DurationSpec.IntSecondsBound cache_load_timeout = new DurationSpec.IntSecondsBound("30s"); private static boolean isClientMode = false; private static Supplier<Config> overrideLoadConfig = null; @Replaces(oldName = "networking_cache_size_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public DataStorageSpec.IntMebibytesBound networking_cache_size; @Replaces(oldName = "file_cache_size_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_INT, deprecated = true) public DataStorageSpec.IntMebibytesBound file_cache_size; public boolean file_cache_enabled = FILE_CACHE_ENABLED.getBoolean(); /** * Because of the current {@link org.apache.cassandra.utils.memory.BufferPool} slab sizes of 64 KiB, we * store in the file cache buffers that divide 64 KiB, so we need to round the buffer sizes to powers of two. * This boolean controls weather they are rounded up or down. Set it to true to round up to the * next power of two, set it to false to round down to the previous power of two. Note that buffer sizes are * already rounded to 4 KiB and capped between 4 KiB minimum and 64 kb maximum by the {@link DiskOptimizationStrategy}. * By default, this boolean is set to round down when {@link #disk_optimization_strategy} is {@code ssd}, * and to round up when it is {@code spinning}. */ public Boolean file_cache_round_up; /** @deprecated See CASSANDRA-15358 */ @Deprecated(since = "4.0") public boolean buffer_pool_use_heap_if_exhausted; public DiskOptimizationStrategy disk_optimization_strategy = DiskOptimizationStrategy.ssd; public double disk_optimization_estimate_percentile = 0.95; public double disk_optimization_page_cross_chance = 0.1; public boolean inter_dc_tcp_nodelay = true; public MemtableAllocationType memtable_allocation_type = MemtableAllocationType.heap_buffers; public volatile boolean read_thresholds_enabled = false; public volatile DataStorageSpec.LongBytesBound coordinator_read_size_warn_threshold = null; public volatile DataStorageSpec.LongBytesBound coordinator_read_size_fail_threshold = null; public volatile DataStorageSpec.LongBytesBound local_read_size_warn_threshold = null; public volatile DataStorageSpec.LongBytesBound local_read_size_fail_threshold = null; public volatile DataStorageSpec.LongBytesBound row_index_read_size_warn_threshold = null; public volatile DataStorageSpec.LongBytesBound row_index_read_size_fail_threshold = null; public volatile int tombstone_warn_threshold = 1000; public volatile int tombstone_failure_threshold = 100000; public final ReplicaFilteringProtectionOptions replica_filtering_protection = new ReplicaFilteringProtectionOptions(); @Replaces(oldName = "index_summary_capacity_in_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_LONG, deprecated = true) public volatile DataStorageSpec.LongMebibytesBound index_summary_capacity; @Nullable @Replaces(oldName = "index_summary_resize_interval_in_minutes", converter = Converters.MINUTES_CUSTOM_DURATION, deprecated = true) public volatile DurationSpec.IntMinutesBound index_summary_resize_interval = new DurationSpec.IntMinutesBound("60m"); @Replaces(oldName = "gc_log_threshold_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public volatile DurationSpec.IntMillisecondsBound gc_log_threshold = new DurationSpec.IntMillisecondsBound("200ms"); @Replaces(oldName = "gc_warn_threshold_in_ms", converter = Converters.MILLIS_DURATION_INT, deprecated = true) public volatile DurationSpec.IntMillisecondsBound gc_warn_threshold = new DurationSpec.IntMillisecondsBound("1s"); // TTL for different types of trace events. @Replaces(oldName = "tracetype_query_ttl", converter = Converters.SECONDS_DURATION, deprecated=true) public DurationSpec.IntSecondsBound trace_type_query_ttl = new DurationSpec.IntSecondsBound("1d"); @Replaces(oldName = "tracetype_repair_ttl", converter = Converters.SECONDS_DURATION, deprecated=true) public DurationSpec.IntSecondsBound trace_type_repair_ttl = new DurationSpec.IntSecondsBound("7d"); /** * Maintain statistics on whether writes achieve the ideal consistency level * before expiring and becoming hints */ public volatile ConsistencyLevel ideal_consistency_level = null; /** @deprecated See CASSANDRA-17404 */ @Deprecated(since = "4.1") public int windows_timer_interval = 0; @Deprecated(since = "4.0") public String otc_coalescing_strategy = "DISABLED"; @Deprecated(since = "4.0") public static final int otc_coalescing_window_us_default = 200; @Deprecated(since = "4.0") public int otc_coalescing_window_us = otc_coalescing_window_us_default; @Deprecated(since = "4.0") public int otc_coalescing_enough_coalesced_messages = 8; @Deprecated(since = "4.0") public static final int otc_backlog_expiration_interval_ms_default = 200; @Deprecated(since = "4.0") public volatile int otc_backlog_expiration_interval_ms = otc_backlog_expiration_interval_ms_default; /** * Size of the CQL prepared statements cache in MiB. * Defaults to 1/256th of the heap size or 10MiB, whichever is greater. */ @Replaces(oldName = "prepared_statements_cache_size_mb", converter = Converters.MEBIBYTES_DATA_STORAGE_LONG, deprecated = true) public DataStorageSpec.LongMebibytesBound prepared_statements_cache_size = null; @Replaces(oldName = "enable_user_defined_functions", converter = Converters.IDENTITY, deprecated = true) public boolean user_defined_functions_enabled = false; /** @deprecated See CASSANDRA-18252 */ @Deprecated(since = "5.0") @Replaces(oldName = "enable_scripted_user_defined_functions", converter = Converters.IDENTITY, deprecated = true) public boolean scripted_user_defined_functions_enabled = false; @Replaces(oldName = "enable_materialized_views", converter = Converters.IDENTITY, deprecated = true) public boolean materialized_views_enabled = false; @Replaces(oldName = "enable_transient_replication", converter = Converters.IDENTITY, deprecated = true) public boolean transient_replication_enabled = false; @Replaces(oldName = "enable_sasi_indexes", converter = Converters.IDENTITY, deprecated = true) public boolean sasi_indexes_enabled = false; @Replaces(oldName = "enable_drop_compact_storage", converter = Converters.IDENTITY, deprecated = true) public volatile boolean drop_compact_storage_enabled = false; public volatile boolean use_statements_enabled = true; /** * Optionally disable asynchronous UDF execution. * Disabling asynchronous UDF execution also implicitly disables the security-manager! * By default, async UDF execution is enabled to be able to detect UDFs that run too long / forever and be * able to fail fast - i.e. stop the Cassandra daemon, which is currently the only appropriate approach to * "tell" a user that there's something really wrong with the UDF. * When you disable async UDF execution, users MUST pay attention to read-timeouts since these may indicate * UDFs that run too long or forever - and this can destabilize the cluster. * * This requires allow_insecure_udfs to be true */ // Below parameter is not presented in cassandra.yaml but to be on the safe side that no one was directly using it // I still added backward compatibility (CASSANDRA-15234) @Replaces(oldName = "enable_user_defined_functions_threads", converter = Converters.IDENTITY, deprecated = true) public boolean user_defined_functions_threads_enabled = true; /** * Set this to true to allow running insecure UDFs. */ public boolean allow_insecure_udfs = false; /** * Set this to allow UDFs accessing java.lang.System.* methods, which basically allows UDFs to execute any arbitrary code on the system. */ public boolean allow_extra_insecure_udfs = false; public boolean dynamic_data_masking_enabled = false; /** * Time in milliseconds after a warning will be emitted to the log and to the client that a UDF runs too long. * (Only valid, if user_defined_functions_threads_enabled==true) */ @Replaces(oldName = "user_defined_function_warn_timeout", converter = Converters.MILLIS_DURATION_LONG, deprecated = true) public DurationSpec.LongMillisecondsBound user_defined_functions_warn_timeout = new DurationSpec.LongMillisecondsBound("500ms"); /** * Time in milliseconds after a fatal UDF run-time situation is detected and action according to * user_function_timeout_policy will take place. * (Only valid, if user_defined_functions_threads_enabled==true) */ @Replaces(oldName = "user_defined_function_fail_timeout", converter = Converters.MILLIS_DURATION_LONG, deprecated = true) public DurationSpec.LongMillisecondsBound user_defined_functions_fail_timeout = new DurationSpec.LongMillisecondsBound("1500ms"); /** * Defines what to do when a UDF ran longer than user_defined_functions_fail_timeout. * Possible options are: * - 'die' - i.e. it is able to emit a warning to the client before the Cassandra Daemon will shut down. * - 'die_immediate' - shut down C* daemon immediately (effectively prevent the chance that the client will receive a warning). * - 'ignore' - just log - the most dangerous option. * (Only valid, if user_defined_functions_threads_enabled==true) */ public UserFunctionTimeoutPolicy user_function_timeout_policy = UserFunctionTimeoutPolicy.die; /** @deprecated See CASSANDRA-15375 */ @Deprecated(since = "4.0") public volatile boolean back_pressure_enabled = false; /** @deprecated See CASSANDRA-15375 */ @Deprecated(since = "4.0") public volatile ParameterizedClass back_pressure_strategy; public volatile int concurrent_validations; public RepairCommandPoolFullStrategy repair_command_pool_full_strategy = RepairCommandPoolFullStrategy.queue; public int repair_command_pool_size = concurrent_validations; /** * When a node first starts up it intially considers all other peers as DOWN and is disconnected from all of them. * To be useful as a coordinator (and not introduce latency penalties on restart) this node must have successfully * opened all three internode TCP connections (gossip, small, and large messages) before advertising to clients. * Due to this, by default, Casssandra will prime these internode TCP connections and wait for all but a single * node to be DOWN/disconnected in the local datacenter before offering itself as a coordinator, subject to a * timeout. See CASSANDRA-13993 and CASSANDRA-14297 for more details. * * We provide two tunables to control this behavior as some users may want to block until all datacenters are * available (global QUORUM/EACH_QUORUM), some users may not want to block at all (clients that already work * around the problem), and some users may want to prime the connections but not delay startup. * * block_for_peers_timeout_in_secs: controls how long this node will wait to connect to peers. To completely disable * any startup connectivity checks set this to -1. To trigger the internode connections but immediately continue * startup, set this to to 0. The default is 10 seconds. * * block_for_peers_in_remote_dcs: controls if this node will consider remote datacenters to wait for. The default * is to _not_ wait on remote datacenters. */ public int block_for_peers_timeout_in_secs = 10; public boolean block_for_peers_in_remote_dcs = false; public volatile boolean automatic_sstable_upgrade = false; public volatile int max_concurrent_automatic_sstable_upgrades = 1; public boolean stream_entire_sstables = true; public volatile boolean skip_stream_disk_space_check = false; public volatile AuditLogOptions audit_logging_options = new AuditLogOptions(); public volatile FullQueryLoggerOptions full_query_logging_options = new FullQueryLoggerOptions(); public CorruptedTombstoneStrategy corrupted_tombstone_strategy = CorruptedTombstoneStrategy.disabled; public volatile boolean diagnostic_events_enabled = false; // Default keyspace replication factors allow validation of newly created keyspaces // and good defaults if no replication factor is provided by the user public volatile int default_keyspace_rf = 1; /** * flags for enabling tracking repaired state of data during reads * separate flags for range & single partition reads as single partition reads are only tracked * when CL > 1 and a digest mismatch occurs. Currently, range queries don't use digests so if * enabled for range reads, all such reads will include repaired data tracking. As this adds * some overhead, operators may wish to disable it whilst still enabling it for partition reads */ public volatile boolean repaired_data_tracking_for_range_reads_enabled = false; public volatile boolean repaired_data_tracking_for_partition_reads_enabled = false; /* If true, unconfirmed mismatches (those which cannot be considered conclusive proof of out of * sync repaired data due to the presence of pending repair sessions, or unrepaired partition * deletes) will increment a metric, distinct from confirmed mismatches. If false, unconfirmed * mismatches are simply ignored by the coordinator. * This is purely to allow operators to avoid potential signal:noise issues as these types of * mismatches are considerably less actionable than their confirmed counterparts. Setting this * to true only disables the incrementing of the counters when an unconfirmed mismatch is found * and has no other effect on the collection or processing of the repaired data. */ public volatile boolean report_unconfirmed_repaired_data_mismatches = false; /* * If true, when a repaired data mismatch is detected at read time or during a preview repair, * a snapshot request will be issued to each particpating replica. These are limited at the replica level * so that only a single snapshot per-table per-day can be taken via this method. */ public volatile boolean snapshot_on_repaired_data_mismatch = false; /** * Number of seconds to set nowInSec into the future when performing validation previews against repaired data * this (attempts) to prevent a race where validations on different machines are started on different sides of * a tombstone being compacted away */ @Replaces(oldName = "validation_preview_purge_head_start_in_sec", converter = Converters.NEGATIVE_SECONDS_DURATION, deprecated = true) public volatile DurationSpec.IntSecondsBound validation_preview_purge_head_start = new DurationSpec.IntSecondsBound("3600s"); public boolean auth_cache_warming_enabled = false; // Using String instead of ConsistencyLevel here to keep static initialization from cascading and starting // threads during tool usage mode. See CASSANDRA-12988 and DatabaseDescriptorRefTest for details public volatile String auth_read_consistency_level = "LOCAL_QUORUM"; public volatile String auth_write_consistency_level = "EACH_QUORUM"; /** This feature allows denying access to operations on certain key partitions, intended for use by operators to * provide another tool to manage cluster health vs application access. See CASSANDRA-12106 and CEP-13 for more details. */ public volatile boolean partition_denylist_enabled = false; public volatile boolean denylist_writes_enabled = true; public volatile boolean denylist_reads_enabled = true; public volatile boolean denylist_range_reads_enabled = true; public DurationSpec.IntSecondsBound denylist_refresh = new DurationSpec.IntSecondsBound("600s"); public DurationSpec.IntSecondsBound denylist_initial_load_retry = new DurationSpec.IntSecondsBound("5s"); /** We cap the number of denylisted keys allowed per table to keep things from growing unbounded. Operators will * receive warnings and only denylist_max_keys_per_table in natural query ordering will be processed on overflow. */ public volatile int denylist_max_keys_per_table = 1000; /** We cap the total number of denylisted keys allowed in the cluster to keep things from growing unbounded. * Operators will receive warnings on initial cache load that there are too many keys and be directed to trim * down the entries to within the configured limits. */ public volatile int denylist_max_keys_total = 10000; /** Since the denylist in many ways serves to protect the health of the cluster from partitions operators have identified * as being in a bad state, we usually want more robustness than just CL.ONE on operations to/from these tables to * ensure that these safeguards are in place. That said, we allow users to configure this if they're so inclined. */ public ConsistencyLevel denylist_consistency_level = ConsistencyLevel.QUORUM; /** * The intial capacity for creating RangeTombstoneList. */ public volatile int initial_range_tombstone_list_allocation_size = 1; /** * The growth factor to enlarge a RangeTombstoneList. */ public volatile double range_tombstone_list_growth_factor = 1.5; public StorageAttachedIndexOptions sai_options = new StorageAttachedIndexOptions(); /** * @deprecated migrate to {@link DatabaseDescriptor#isClientInitialized()} See CASSANDRA-12550 */ @Deprecated(since = "3.10") public static boolean isClientMode() { return isClientMode; } /** * If true, when rows with duplicate clustering keys are detected during a read or compaction * a snapshot will be taken. In the read case, each a snapshot request will be issued to each * replica involved in the query, for compaction the snapshot will be created locally. * These are limited at the replica level so that only a single snapshot per-day can be taken * via this method. * * This requires check_for_duplicate_rows_during_reads and/or check_for_duplicate_rows_during_compaction * below to be enabled */ public volatile boolean snapshot_on_duplicate_row_detection = false; /** * If these are enabled duplicate keys will get logged, and if snapshot_on_duplicate_row_detection * is enabled, the table will get snapshotted for offline investigation */ public volatile boolean check_for_duplicate_rows_during_reads = true; public volatile boolean check_for_duplicate_rows_during_compaction = true; public boolean autocompaction_on_startup_enabled = AUTOCOMPACTION_ON_STARTUP_ENABLED.getBoolean(); // see CASSANDRA-3200 / CASSANDRA-16274 public volatile boolean auto_optimise_inc_repair_streams = false; public volatile boolean auto_optimise_full_repair_streams = false; public volatile boolean auto_optimise_preview_repair_streams = false; // see CASSANDRA-17048 and the comment in cassandra.yaml public boolean uuid_sstable_identifiers_enabled = false; /** * Client mode means that the process is a pure client, that uses C* code base but does * not read or write local C* database files. * * @deprecated migrate to {@link DatabaseDescriptor#clientInitialization(boolean)} See CASSANDRA-12550 */ @Deprecated(since = "3.10") public static void setClientMode(boolean clientMode) { isClientMode = clientMode; } public volatile int consecutive_message_errors_threshold = 1; public volatile SubnetGroups client_error_reporting_exclusions = new SubnetGroups(); public volatile SubnetGroups internode_error_reporting_exclusions = new SubnetGroups(); @Replaces(oldName = "keyspace_count_warn_threshold", converter = Converters.KEYSPACE_COUNT_THRESHOLD_TO_GUARDRAIL, deprecated = true) public volatile int keyspaces_warn_threshold = -1; public volatile int keyspaces_fail_threshold = -1; @Replaces(oldName = "table_count_warn_threshold", converter = Converters.TABLE_COUNT_THRESHOLD_TO_GUARDRAIL, deprecated = true) public volatile int tables_warn_threshold = -1; public volatile int tables_fail_threshold = -1; public volatile int columns_per_table_warn_threshold = -1; public volatile int columns_per_table_fail_threshold = -1; public volatile int secondary_indexes_per_table_warn_threshold = -1; public volatile int secondary_indexes_per_table_fail_threshold = -1; public volatile int materialized_views_per_table_warn_threshold = -1; public volatile int materialized_views_per_table_fail_threshold = -1; public volatile int page_size_warn_threshold = -1; public volatile int page_size_fail_threshold = -1; public volatile int partition_keys_in_select_warn_threshold = -1; public volatile int partition_keys_in_select_fail_threshold = -1; public volatile int in_select_cartesian_product_warn_threshold = -1; public volatile int in_select_cartesian_product_fail_threshold = -1; public volatile Set<String> table_properties_warned = Collections.emptySet(); public volatile Set<String> table_properties_ignored = Collections.emptySet(); public volatile Set<String> table_properties_disallowed = Collections.emptySet(); public volatile Set<ConsistencyLevel> read_consistency_levels_warned = Collections.emptySet(); public volatile Set<ConsistencyLevel> read_consistency_levels_disallowed = Collections.emptySet(); public volatile Set<ConsistencyLevel> write_consistency_levels_warned = Collections.emptySet(); public volatile Set<ConsistencyLevel> write_consistency_levels_disallowed = Collections.emptySet(); public volatile boolean user_timestamps_enabled = true; public volatile boolean alter_table_enabled = true; public volatile boolean group_by_enabled = true; public volatile boolean bulk_load_enabled = true; public volatile boolean drop_truncate_table_enabled = true; public volatile boolean drop_keyspace_enabled = true; public volatile boolean secondary_indexes_enabled = true; public volatile String default_secondary_index = CassandraIndex.NAME; public volatile boolean default_secondary_index_enabled = true; public volatile boolean uncompressed_tables_enabled = true; public volatile boolean compact_tables_enabled = true; public volatile boolean read_before_write_list_operations_enabled = true; public volatile boolean allow_filtering_enabled = true; public volatile boolean simplestrategy_enabled = true; @Replaces(oldName = "compaction_large_partition_warning_threshold_mb", converter = Converters.LONG_BYTES_DATASTORAGE_MEBIBYTES_INT, deprecated = true) @Replaces(oldName = "compaction_large_partition_warning_threshold", converter = Converters.LONG_BYTES_DATASTORAGE_MEBIBYTES_DATASTORAGE, deprecated = true) public volatile DataStorageSpec.LongBytesBound partition_size_warn_threshold = null; public volatile DataStorageSpec.LongBytesBound partition_size_fail_threshold = null; @Replaces(oldName = "compaction_tombstone_warning_threshold", converter = Converters.INTEGER_PRIMITIVE_LONG, deprecated = true) public volatile long partition_tombstones_warn_threshold = -1; public volatile long partition_tombstones_fail_threshold = -1; public volatile DataStorageSpec.LongBytesBound column_value_size_warn_threshold = null; public volatile DataStorageSpec.LongBytesBound column_value_size_fail_threshold = null; public volatile DataStorageSpec.LongBytesBound collection_size_warn_threshold = null; public volatile DataStorageSpec.LongBytesBound collection_size_fail_threshold = null; public volatile int items_per_collection_warn_threshold = -1; public volatile int items_per_collection_fail_threshold = -1; public volatile int fields_per_udt_warn_threshold = -1; public volatile int fields_per_udt_fail_threshold = -1; public volatile int vector_dimensions_warn_threshold = -1; public volatile int vector_dimensions_fail_threshold = -1; public volatile int data_disk_usage_percentage_warn_threshold = -1; public volatile int data_disk_usage_percentage_fail_threshold = -1; public volatile DataStorageSpec.LongBytesBound data_disk_usage_max_disk_size = null; public volatile int minimum_replication_factor_warn_threshold = -1; public volatile int minimum_replication_factor_fail_threshold = -1; public volatile int maximum_replication_factor_warn_threshold = -1; public volatile int maximum_replication_factor_fail_threshold = -1; public volatile boolean zero_ttl_on_twcs_warned = true; public volatile boolean zero_ttl_on_twcs_enabled = true; public volatile boolean non_partition_restricted_index_query_enabled = true; public volatile boolean intersect_filtering_query_warned = true; public volatile boolean intersect_filtering_query_enabled = true; public volatile int sai_sstable_indexes_per_query_warn_threshold = 32; public volatile int sai_sstable_indexes_per_query_fail_threshold = -1; public volatile DataStorageSpec.LongBytesBound sai_string_term_size_warn_threshold = new DataStorageSpec.LongBytesBound("1KiB"); public volatile DataStorageSpec.LongBytesBound sai_string_term_size_fail_threshold = new DataStorageSpec.LongBytesBound("8KiB"); public volatile DataStorageSpec.LongBytesBound sai_frozen_term_size_warn_threshold = new DataStorageSpec.LongBytesBound("1KiB"); public volatile DataStorageSpec.LongBytesBound sai_frozen_term_size_fail_threshold = new DataStorageSpec.LongBytesBound("8KiB"); public volatile DataStorageSpec.LongBytesBound sai_vector_term_size_warn_threshold = new DataStorageSpec.LongBytesBound("16KiB"); public volatile DataStorageSpec.LongBytesBound sai_vector_term_size_fail_threshold = new DataStorageSpec.LongBytesBound("32KiB"); public volatile DurationSpec.LongNanosecondsBound streaming_state_expires = new DurationSpec.LongNanosecondsBound("3d"); public volatile DataStorageSpec.LongBytesBound streaming_state_size = new DataStorageSpec.LongBytesBound("40MiB"); public volatile boolean streaming_stats_enabled = true; public volatile DurationSpec.IntSecondsBound streaming_slow_events_log_timeout = new DurationSpec.IntSecondsBound("10s"); /** The configuration of startup checks. */ public volatile Map<StartupCheckType, Map<String, Object>> startup_checks = new HashMap<>(); public volatile DurationSpec.LongNanosecondsBound repair_state_expires = new DurationSpec.LongNanosecondsBound("3d"); public volatile int repair_state_size = 100_000; /** The configuration of timestamp bounds */ public volatile DurationSpec.LongMicrosecondsBound maximum_timestamp_warn_threshold = null; public volatile DurationSpec.LongMicrosecondsBound maximum_timestamp_fail_threshold = null; public volatile DurationSpec.LongMicrosecondsBound minimum_timestamp_warn_threshold = null; public volatile DurationSpec.LongMicrosecondsBound minimum_timestamp_fail_threshold = null; /** * The variants of paxos implementation and semantics supported by Cassandra. */ public enum PaxosVariant { /** * v1 Paxos lacks most optimisations. Expect 4RTs for a write and 2RTs for a read. * * With legacy semantics for read/read and rejected write linearizability, i.e. not guaranteed. */ v1_without_linearizable_reads_or_rejected_writes, /** * v1 Paxos lacks most optimisations. Expect 4RTs for a write and 3RTs for a read. */ v1, /** * v2 Paxos. With PaxosStatePurging.repaired safe to use ANY Commit consistency. * Expect 2RTs for a write and 1RT for a read. * * With legacy semantics for read/read linearizability, i.e. not guaranteed. */ v2_without_linearizable_reads, /** * v2 Paxos. With PaxosStatePurging.repaired safe to use ANY Commit consistency. * Expect 2RTs for a write and 1RT for a read. * * With legacy semantics for read/read and rejected write linearizability, i.e. not guaranteed. */ v2_without_linearizable_reads_or_rejected_writes, /** * v2 Paxos. With PaxosStatePurging.repaired safe to use ANY Commit consistency. * Expect 2RTs for a write, and either 1RT or 2RT for a read. */ v2 } /** * Select the kind of paxos state purging to use. Migration to repaired is recommended, but requires that * regular paxos repairs are performed (which by default run as part of incremental repair). * * Once migrated from legacy it is unsafe to return to legacy, but gc_grace mode may be used in its place * and performs a very similar cleanup process. * * Should only be modified once paxos_variant = v2. */ public enum PaxosStatePurging { /** * system.paxos records are written and garbage collected with TTLs. Unsafe to use with Commit consistency ANY. * Once migrated from, cannot be migrated back to safely. Must use gc_grace or repaired instead, as TTLs * will not have been set. */ legacy, /** * Functionally similar to legacy, but the gc_grace expiry is applied at compaction and read time rather than * using TTLs, so may be safely enabled at any point. */ gc_grace, /** * Clears system.paxos records only once they are known to be persisted to a quorum of replica's base tables * through the use of paxos repair. Requires that regular paxos repairs are performed on the cluster * (which by default are included in incremental repairs if paxos_variant = v2). * * This setting permits the use of Commit consistency ANY or LOCAL_QUORUM without any loss of durability or consistency, * saving 1 RT. */ repaired; public static PaxosStatePurging fromBoolean(boolean enabled) { return enabled ? repaired : gc_grace; } } /** * See {@link PaxosVariant}. Defaults to v1, recommend upgrading to v2 at earliest opportunity. */ public volatile PaxosVariant paxos_variant = PaxosVariant.v1; /** * If true, paxos topology change repair will not run on a topology change - this option should only be used in * rare operation circumstances e.g. where for some reason the repair is impossible to perform (e.g. too few replicas) * and an unsafe topology change must be made */ public volatile boolean skip_paxos_repair_on_topology_change = SKIP_PAXOS_REPAIR_ON_TOPOLOGY_CHANGE.getBoolean(); /** * A safety margin when purging paxos state information that has been safely replicated to a quorum. * Data for transactions initiated within this grace period will not be expunged. */ public volatile DurationSpec.LongSecondsBound paxos_purge_grace_period = new DurationSpec.LongSecondsBound("60s"); /** * A safety mechanism for detecting incorrect paxos state, that may be down either to a bug or incorrect usage of LWTs * (most likely due to unsafe mixing of SERIAL and LOCAL_SERIAL operations), and rejecting */ public enum PaxosOnLinearizabilityViolation { // reject an operation when a linearizability violation is detected. // note this does not guarantee a violation has been averted, // as it may be a prior operation that invalidated the state. fail, // log any detected linearizability violation log, // ignore any detected linearizability violation ignore } /** * See {@link PaxosOnLinearizabilityViolation}. * * Default is to ignore, as applications may readily mix SERIAL and LOCAL_SERIAL and this is the most likely source * of linearizability violations. this facility should be activated only for debugging Cassandra or by power users * who are investigating their own application behaviour. */ public volatile PaxosOnLinearizabilityViolation paxos_on_linearizability_violations = PaxosOnLinearizabilityViolation.ignore; /** * See {@link PaxosStatePurging} default is legacy. */ public volatile PaxosStatePurging paxos_state_purging; /** * Enable/disable paxos repair. This is a global flag that not only determines default behaviour but overrides * explicit paxos repair requests, paxos repair on topology changes and paxos auto repairs. */ public volatile boolean paxos_repair_enabled = true; /** * If true, paxos topology change repair only requires a global quorum of live nodes. If false, * it requires a global quorum as well as a local quorum for each dc (EACH_QUORUM), with the * exception explained in paxos_topology_repair_strict_each_quorum */ public boolean paxos_topology_repair_no_dc_checks = false; /** * If true, a quorum will be required for the global and local quorum checks. If false, we will * accept a quorum OR n - 1 live nodes. This is to allow for topologies like 2:2:2, where paxos queries * always use SERIAL, and a single node down in a dc should not preclude a paxos repair */ public boolean paxos_topology_repair_strict_each_quorum = false; /** * If necessary for operational purposes, permit certain keyspaces to be ignored for paxos topology repairs */ public volatile Set<String> skip_paxos_repair_on_topology_change_keyspaces = splitCommaDelimited(SKIP_PAXOS_REPAIR_ON_TOPOLOGY_CHANGE_KEYSPACES.getString()); /** * See {@link org.apache.cassandra.service.paxos.ContentionStrategy} */ public String paxos_contention_wait_randomizer; /** * See {@link org.apache.cassandra.service.paxos.ContentionStrategy} */ public String paxos_contention_min_wait; /** * See {@link org.apache.cassandra.service.paxos.ContentionStrategy} */ public String paxos_contention_max_wait; /** * See {@link org.apache.cassandra.service.paxos.ContentionStrategy} */ public String paxos_contention_min_delta; /** * The number of keys we may simultaneously attempt to finish incomplete paxos operations for. */ public volatile int paxos_repair_parallelism = -1; public volatile boolean sstable_read_rate_persistence_enabled = false; public volatile boolean client_request_size_metrics_enabled = true; public volatile int max_top_size_partition_count = 10; public volatile int max_top_tombstone_partition_count = 10; public volatile DataStorageSpec.LongBytesBound min_tracked_partition_size = new DataStorageSpec.LongBytesBound("1MiB"); public volatile long min_tracked_partition_tombstone_count = 5000; public volatile boolean top_partitions_enabled = true; public final RepairConfig repair = new RepairConfig(); /** * Default compaction configuration, used if a table does not specify any. */ public ParameterizedClass default_compaction = null; public static Supplier<Config> getOverrideLoadConfig() { return overrideLoadConfig; } public static void setOverrideLoadConfig(Supplier<Config> loadConfig) { overrideLoadConfig = loadConfig; } public enum CommitLogSync { periodic, batch, group } public enum FlushCompression { none, fast, table } public enum InternodeCompression { all, none, dc } public enum DiskAccessMode { auto, mmap, mmap_index_only, standard, legacy, /** * Direct-I/O is enabled for commitlog disk only. * When adding support for direct IO, update {@link org.apache.cassandra.service.StartupChecks#checkKernelBug1057843} */ direct } public enum MemtableAllocationType { unslabbed_heap_buffers, unslabbed_heap_buffers_logged, heap_buffers, offheap_buffers, offheap_objects; public BufferType toBufferType() { switch (this) { case unslabbed_heap_buffers: case heap_buffers: return BufferType.ON_HEAP; case offheap_buffers: case offheap_objects: return BufferType.OFF_HEAP; default: throw new AssertionError(); } } } public enum DiskFailurePolicy { best_effort, stop, ignore, stop_paranoid, die } public enum CommitFailurePolicy { stop, stop_commit, ignore, die, } public enum UserFunctionTimeoutPolicy { ignore, die, die_immediate } public enum DiskOptimizationStrategy { ssd, spinning } public enum RepairCommandPoolFullStrategy { queue, reject } public enum CorruptedTombstoneStrategy { disabled, warn, exception } private static final Set<String> SENSITIVE_KEYS = new HashSet<String>() {{ add("client_encryption_options"); add("server_encryption_options"); }}; public static void log(Config config) { Map<String, String> configMap = new TreeMap<>(); for (Field field : Config.class.getFields()) { // ignore the constants if (Modifier.isFinal(field.getModifiers())) continue; String name = field.getName(); if (SENSITIVE_KEYS.contains(name)) { configMap.put(name, "<REDACTED>"); continue; } String value; try { // Field.get() can throw NPE if the value of the field is null value = field.get(config).toString(); } catch (NullPointerException | IllegalAccessException npe) { value = "null"; } configMap.put(name, value); } logger.info("Node configuration:[{}]", Joiner.on("; ").join(configMap.entrySet())); } public volatile boolean dump_heap_on_uncaught_exception = false; public String heap_dump_path = "heapdump"; public double severity_during_decommission = 0; // TODO Revisit MessagingService::current_version public StorageCompatibilityMode storage_compatibility_mode; /** * For the purposes of progress barrier we only support ALL, EACH_QUORUM, QUORUM, LOCAL_QUORUM, ANY, and ONE. * * We will still try all consistency levels above the lowest acceptable, and only fall back to it if we can not * collect enough nodes. */ public volatile ConsistencyLevel progress_barrier_min_consistency_level = ConsistencyLevel.EACH_QUORUM; public volatile ConsistencyLevel progress_barrier_default_consistency_level = ConsistencyLevel.EACH_QUORUM; public volatile DurationSpec.LongMillisecondsBound progress_barrier_timeout = new DurationSpec.LongMillisecondsBound("3600000ms"); public volatile DurationSpec.LongMillisecondsBound progress_barrier_backoff = new DurationSpec.LongMillisecondsBound("1000ms"); public volatile DurationSpec.LongSecondsBound discovery_timeout = new DurationSpec.LongSecondsBound("30s"); public boolean unsafe_tcm_mode = false; public enum TriggersPolicy { // Execute triggers enabled, // Don't execute triggers when executing queries disabled, // Throw an exception when attempting to execute a trigger forbidden } public TriggersPolicy triggers_policy = TriggersPolicy.enabled; }
apache/cassandra
src/java/org/apache/cassandra/config/Config.java
2,198
import com.rabbitmq.client.Channel; import com.rabbitmq.client.ConfirmCallback; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.time.Duration; import java.util.UUID; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.function.BooleanSupplier; public class PublisherConfirms { static final int MESSAGE_COUNT = 50_000; static Connection createConnection() throws Exception { ConnectionFactory cf = new ConnectionFactory(); cf.setHost("localhost"); cf.setUsername("guest"); cf.setPassword("guest"); return cf.newConnection(); } public static void main(String[] args) throws Exception { publishMessagesIndividually(); publishMessagesInBatch(); handlePublishConfirmsAsynchronously(); } static void publishMessagesIndividually() throws Exception { try (Connection connection = createConnection()) { Channel ch = connection.createChannel(); String queue = UUID.randomUUID().toString(); ch.queueDeclare(queue, false, false, true, null); ch.confirmSelect(); long start = System.nanoTime(); for (int i = 0; i < MESSAGE_COUNT; i++) { String body = String.valueOf(i); ch.basicPublish("", queue, null, body.getBytes()); ch.waitForConfirmsOrDie(5_000); } long end = System.nanoTime(); System.out.format("Published %,d messages individually in %,d ms%n", MESSAGE_COUNT, Duration.ofNanos(end - start).toMillis()); } } static void publishMessagesInBatch() throws Exception { try (Connection connection = createConnection()) { Channel ch = connection.createChannel(); String queue = UUID.randomUUID().toString(); ch.queueDeclare(queue, false, false, true, null); ch.confirmSelect(); int batchSize = 100; int outstandingMessageCount = 0; long start = System.nanoTime(); for (int i = 0; i < MESSAGE_COUNT; i++) { String body = String.valueOf(i); ch.basicPublish("", queue, null, body.getBytes()); outstandingMessageCount++; if (outstandingMessageCount == batchSize) { ch.waitForConfirmsOrDie(5_000); outstandingMessageCount = 0; } } if (outstandingMessageCount > 0) { ch.waitForConfirmsOrDie(5_000); } long end = System.nanoTime(); System.out.format("Published %,d messages in batch in %,d ms%n", MESSAGE_COUNT, Duration.ofNanos(end - start).toMillis()); } } static void handlePublishConfirmsAsynchronously() throws Exception { try (Connection connection = createConnection()) { Channel ch = connection.createChannel(); String queue = UUID.randomUUID().toString(); ch.queueDeclare(queue, false, false, true, null); ch.confirmSelect(); ConcurrentNavigableMap<Long, String> outstandingConfirms = new ConcurrentSkipListMap<>(); ConfirmCallback cleanOutstandingConfirms = (sequenceNumber, multiple) -> { if (multiple) { ConcurrentNavigableMap<Long, String> confirmed = outstandingConfirms.headMap( sequenceNumber, true ); confirmed.clear(); } else { outstandingConfirms.remove(sequenceNumber); } }; ch.addConfirmListener(cleanOutstandingConfirms, (sequenceNumber, multiple) -> { String body = outstandingConfirms.get(sequenceNumber); System.err.format( "Message with body %s has been nack-ed. Sequence number: %d, multiple: %b%n", body, sequenceNumber, multiple ); cleanOutstandingConfirms.handle(sequenceNumber, multiple); }); long start = System.nanoTime(); for (int i = 0; i < MESSAGE_COUNT; i++) { String body = String.valueOf(i); outstandingConfirms.put(ch.getNextPublishSeqNo(), body); ch.basicPublish("", queue, null, body.getBytes()); } if (!waitUntil(Duration.ofSeconds(60), () -> outstandingConfirms.isEmpty())) { throw new IllegalStateException("All messages could not be confirmed in 60 seconds"); } long end = System.nanoTime(); System.out.format("Published %,d messages and handled confirms asynchronously in %,d ms%n", MESSAGE_COUNT, Duration.ofNanos(end - start).toMillis()); } } static boolean waitUntil(Duration timeout, BooleanSupplier condition) throws InterruptedException { int waited = 0; while (!condition.getAsBoolean() && waited < timeout.toMillis()) { Thread.sleep(100L); waited += 100; } return condition.getAsBoolean(); } }
rabbitmq/rabbitmq-tutorials
java/PublisherConfirms.java
2,199
/* * 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.content.Context; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.AnimatedFloat; import org.telegram.ui.Components.AvatarDrawable; import org.telegram.ui.Components.BackupImageView; import org.telegram.ui.Components.CombinedDrawable; import org.telegram.ui.Components.DotDividerSpan; import org.telegram.ui.Components.FlickerLoadingView; import org.telegram.ui.Components.LayoutHelper; public class SessionCell extends FrameLayout { private int currentType; private TextView nameTextView; private TextView onlineTextView; private TextView detailTextView; private TextView detailExTextView; private BackupImageView placeholderImageView; private BackupImageView imageView; private AvatarDrawable avatarDrawable; private boolean needDivider; private boolean showStub; private AnimatedFloat showStubValue = new AnimatedFloat(this); FlickerLoadingView globalGradient; LinearLayout linearLayout; private int currentAccount = UserConfig.selectedAccount; public SessionCell(Context context, int type) { super(context); linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.setWeightSum(1); currentType = type; if (type == 1) { addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 30, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 15 : 49), 11, (LocaleController.isRTL ? 49 : 15), 0)); avatarDrawable = new AvatarDrawable(); avatarDrawable.setTextSize(AndroidUtilities.dp(10)); imageView = new BackupImageView(context); imageView.setRoundRadius(AndroidUtilities.dp(10)); addView(imageView, LayoutHelper.createFrame(20, 20, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 0 : 21), 13, (LocaleController.isRTL ? 21 : 0), 0)); } else { placeholderImageView = new BackupImageView(context); placeholderImageView.setRoundRadius(AndroidUtilities.dp(10)); addView(placeholderImageView, LayoutHelper.createFrame(42, 42, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 0 : 16), 9, (LocaleController.isRTL ? 16 : 0), 0)); imageView = new BackupImageView(context); imageView.setRoundRadius(AndroidUtilities.dp(10)); addView(imageView, LayoutHelper.createFrame(42, 42, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 0 : 16), 9, (LocaleController.isRTL ? 16 : 0), 0)); addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 30, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 15 : 72), 6.333f, (LocaleController.isRTL ? 72 : 15), 0)); } nameTextView = new TextView(context); nameTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, type == 0 ? 15 : 16); nameTextView.setLines(1); nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); nameTextView.setMaxLines(1); nameTextView.setSingleLine(true); nameTextView.setEllipsize(TextUtils.TruncateAt.END); nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); onlineTextView = new TextView(context); onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, type == 0 ? 12 : 13); onlineTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP); if (LocaleController.isRTL) { linearLayout.addView(onlineTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 2, 0, 0)); linearLayout.addView(nameTextView, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, Gravity.RIGHT | Gravity.TOP, 10, 0, 0, 0)); } else { linearLayout.addView(nameTextView, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, Gravity.LEFT | Gravity.TOP, 0, 0, 10, 0)); linearLayout.addView(onlineTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.TOP, 0, 2, 0, 0)); } int leftMargin; int rightMargin; if (LocaleController.isRTL) { rightMargin = type == 0 ? 72 : 21; leftMargin = 21; } else { leftMargin = type == 0 ? 72 : 21; rightMargin = 21; } detailTextView = new TextView(context); detailTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); detailTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, type == 0 ? 13 : 14); detailTextView.setLines(1); detailTextView.setMaxLines(1); detailTextView.setSingleLine(true); detailTextView.setEllipsize(TextUtils.TruncateAt.END); detailTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); addView(detailTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, leftMargin, type == 0 ? 28 : 36, rightMargin, 0)); detailExTextView = new TextView(context); detailExTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3)); detailExTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, type == 0 ? 13 : 14); detailExTextView.setLines(1); detailExTextView.setMaxLines(1); detailExTextView.setSingleLine(true); detailExTextView.setEllipsize(TextUtils.TruncateAt.END); detailExTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); addView(detailExTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, leftMargin, type == 0 ? 46 : 59, rightMargin, 0)); } private void setContentAlpha(float alpha) { if (detailExTextView != null) { detailExTextView.setAlpha(alpha); } if (detailTextView != null) { detailTextView.setAlpha(alpha); } if (nameTextView != null) { nameTextView.setAlpha(alpha); } if (onlineTextView != null) { onlineTextView.setAlpha(alpha); } if (imageView != null) { imageView.setAlpha(alpha); } if (placeholderImageView != null) { placeholderImageView.setAlpha(1f - alpha); } if (linearLayout != null) { linearLayout.setAlpha(alpha); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(currentType == 0 ? 70 : 90) + (needDivider ? 1 : 0), MeasureSpec.EXACTLY)); } public void setSession(TLObject object, boolean divider) { needDivider = divider; if (object instanceof TLRPC.TL_authorization) { TLRPC.TL_authorization session = (TLRPC.TL_authorization) object; imageView.setImageDrawable(createDrawable(session)); StringBuilder stringBuilder = new StringBuilder(); if (session.device_model.length() != 0) { stringBuilder.append(session.device_model); } if (stringBuilder.length() == 0) { if (session.platform.length() != 0) { stringBuilder.append(session.platform); } if (session.system_version.length() != 0) { if (session.platform.length() != 0) { stringBuilder.append(" "); } stringBuilder.append(session.system_version); } } nameTextView.setText(stringBuilder); String timeText; if ((session.flags & 1) != 0) { setTag(Theme.key_windowBackgroundWhiteValueText); timeText = LocaleController.getString("Online", R.string.Online); } else { setTag(Theme.key_windowBackgroundWhiteGrayText3); timeText = LocaleController.stringForMessageListDate(session.date_active); } SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); if (session.country.length() != 0) { spannableStringBuilder.append(session.country); } if (spannableStringBuilder.length() != 0) { DotDividerSpan dotDividerSpan = new DotDividerSpan(); dotDividerSpan.setTopPadding(AndroidUtilities.dp(1.5f)); spannableStringBuilder.append(" . ").setSpan(dotDividerSpan, spannableStringBuilder.length() - 2, spannableStringBuilder.length() - 1, 0); } spannableStringBuilder.append(timeText); detailExTextView.setText(spannableStringBuilder); stringBuilder = new StringBuilder(); stringBuilder.append(session.app_name); stringBuilder.append(" ").append(session.app_version); detailTextView.setText(stringBuilder); } else if (object instanceof TLRPC.TL_webAuthorization) { TLRPC.TL_webAuthorization session = (TLRPC.TL_webAuthorization) object; TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(session.bot_id); nameTextView.setText(session.domain); String name; if (user != null) { avatarDrawable.setInfo(currentAccount, user); name = UserObject.getFirstName(user); imageView.setForUserOrChat(user, avatarDrawable); } else { name = ""; } setTag(Theme.key_windowBackgroundWhiteGrayText3); onlineTextView.setText(LocaleController.stringForMessageListDate(session.date_active)); onlineTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3)); StringBuilder stringBuilder = new StringBuilder(); if (session.ip.length() != 0) { stringBuilder.append(session.ip); } if (session.region.length() != 0) { if (stringBuilder.length() != 0) { stringBuilder.append(" "); } stringBuilder.append("— "); stringBuilder.append(session.region); } detailExTextView.setText(stringBuilder); stringBuilder = new StringBuilder(); if (!TextUtils.isEmpty(name)) { stringBuilder.append(name); } if (session.browser.length() != 0 ) { if (stringBuilder.length() != 0) { stringBuilder.append(", "); } stringBuilder.append(session.browser); } if (session.platform.length() != 0) { if (stringBuilder.length() != 0) { stringBuilder.append(", "); } stringBuilder.append(session.platform); } detailTextView.setText(stringBuilder); } if (showStub) { showStub = false; invalidate(); } } public static Drawable createDrawable(TLRPC.TL_authorization session) { String platform = session.platform.toLowerCase(); if (platform.isEmpty()) { platform = session.system_version.toLowerCase(); } String deviceModel = session.device_model.toLowerCase(); int iconId; int colorKey, colorKey2; if (deviceModel.contains("safari")) { iconId = R.drawable.device_web_safari; colorKey = Theme.key_avatar_backgroundPink; colorKey2 = Theme.key_avatar_background2Pink; } else if (deviceModel.contains("edge")) { iconId = R.drawable.device_web_edge; colorKey = Theme.key_avatar_backgroundPink; colorKey2 = Theme.key_avatar_background2Pink; } else if (deviceModel.contains("chrome")) { iconId = R.drawable.device_web_chrome; colorKey = Theme.key_avatar_backgroundPink; colorKey2 = Theme.key_avatar_background2Pink; } else if (deviceModel.contains("opera")) { iconId = R.drawable.device_web_opera; colorKey = Theme.key_avatar_backgroundPink; colorKey2 = Theme.key_avatar_background2Pink; } else if (deviceModel.contains("firefox")) { iconId = R.drawable.device_web_firefox; colorKey = Theme.key_avatar_backgroundPink; colorKey2 = Theme.key_avatar_background2Pink; } else if (deviceModel.contains("vivaldi")) { iconId = R.drawable.device_web_other; colorKey = Theme.key_avatar_backgroundPink; colorKey2 = Theme.key_avatar_background2Pink; } else if (platform.contains("ios")) { iconId = deviceModel.contains("ipad") ? R.drawable.device_tablet_ios : R.drawable.device_phone_ios; colorKey = Theme.key_avatar_backgroundBlue; colorKey2 = Theme.key_avatar_background2Blue; } else if (platform.contains("windows")) { iconId = R.drawable.device_desktop_win; colorKey = Theme.key_avatar_backgroundCyan; colorKey2 = Theme.key_avatar_background2Cyan; } else if (platform.contains("macos")) { iconId = R.drawable.device_desktop_osx; colorKey = Theme.key_avatar_backgroundCyan; colorKey2 = Theme.key_avatar_background2Cyan; } else if (platform.contains("android")) { iconId = deviceModel.contains("tab") ? R.drawable.device_tablet_android : R.drawable.device_phone_android; colorKey = Theme.key_avatar_backgroundGreen; colorKey2 = Theme.key_avatar_background2Green; } else { if (session.app_name.toLowerCase().contains("desktop")) { iconId = R.drawable.device_desktop_other; colorKey = Theme.key_avatar_backgroundCyan; colorKey2 = Theme.key_avatar_background2Cyan; } else { iconId = R.drawable.device_web_other; colorKey = Theme.key_avatar_backgroundPink; colorKey2 = Theme.key_avatar_background2Pink; } } Drawable iconDrawable = ContextCompat.getDrawable(ApplicationLoader.applicationContext, iconId).mutate(); iconDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_avatar_text), PorterDuff.Mode.SRC_IN)); Drawable bgDrawable = new CircleGradientDrawable(AndroidUtilities.dp(42), Theme.getColor(colorKey), Theme.getColor(colorKey2)); CombinedDrawable combinedDrawable = new CombinedDrawable(bgDrawable, iconDrawable); return combinedDrawable; } public static class CircleGradientDrawable extends Drawable { private Paint paint; private int size, colorTop, colorBottom; public CircleGradientDrawable(int size, int colorTop, int colorBottom) { this.size = size; this.colorTop = colorTop; this.colorBottom = colorBottom; paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setShader(new LinearGradient(0, 0, 0, size, new int[] {colorTop, colorBottom}, new float[] {0, 1}, Shader.TileMode.CLAMP)); } @Override public void draw(@NonNull Canvas canvas) { canvas.drawCircle(getBounds().centerX(), getBounds().centerY(), Math.min(getBounds().width(), getBounds().height()) / 2f, paint); } @Override public void setAlpha(int i) { paint.setAlpha(i); } @Override public void setColorFilter(@Nullable ColorFilter colorFilter) {} @Override public int getOpacity() { return PixelFormat.TRANSPARENT; } @Override public int getIntrinsicHeight() { return size; } @Override public int getIntrinsicWidth() { return size; } } @Override protected void onDraw(Canvas canvas) { float stubAlpha = showStubValue.set(showStub ? 1 : 0); setContentAlpha(1f - stubAlpha); if (stubAlpha > 0 && globalGradient != null) { if (stubAlpha < 1f) { AndroidUtilities.rectTmp.set(0, 0, getWidth(), getHeight()); canvas.saveLayerAlpha(AndroidUtilities.rectTmp, (int) (255 * stubAlpha), Canvas.ALL_SAVE_FLAG); } globalGradient.updateColors(); globalGradient.updateGradient(); if (getParent() != null) { View parent = (View) getParent(); globalGradient.setParentSize(parent.getMeasuredWidth(), parent.getMeasuredHeight(), -getX()); } float y = linearLayout.getTop() + nameTextView.getTop() + AndroidUtilities.dp(12); float x = linearLayout.getX(); AndroidUtilities.rectTmp.set(x, y - AndroidUtilities.dp(4), x + getMeasuredWidth() * 0.2f, y + AndroidUtilities.dp(4)); canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(4), AndroidUtilities.dp(4), globalGradient.getPaint()); y = linearLayout.getTop() + detailTextView.getTop() - AndroidUtilities.dp(1); x = linearLayout.getX(); AndroidUtilities.rectTmp.set(x, y - AndroidUtilities.dp(4), x + getMeasuredWidth() * 0.4f, y + AndroidUtilities.dp(4)); canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(4), AndroidUtilities.dp(4), globalGradient.getPaint()); y = linearLayout.getTop() + detailExTextView.getTop() - AndroidUtilities.dp(1); x = linearLayout.getX(); AndroidUtilities.rectTmp.set(x, y - AndroidUtilities.dp(4), x + getMeasuredWidth() * 0.3f, y + AndroidUtilities.dp(4)); canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(4), AndroidUtilities.dp(4), globalGradient.getPaint()); invalidate(); if (stubAlpha < 1f) { canvas.restore(); } } if (needDivider) { int margin = currentType == 1 ? 49 : 72; canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(margin), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(margin) : 0), getMeasuredHeight() - 1, Theme.dividerPaint); } } public void showStub(FlickerLoadingView globalGradient) { this.globalGradient = globalGradient; showStub = true; Drawable iconDrawable = ContextCompat.getDrawable(ApplicationLoader.applicationContext, AndroidUtilities.isTablet() ? R.drawable.device_tablet_android : R.drawable.device_phone_android).mutate(); iconDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_avatar_text), PorterDuff.Mode.SRC_IN)); CombinedDrawable combinedDrawable = new CombinedDrawable(Theme.createCircleDrawable(AndroidUtilities.dp(42), Theme.getColor(Theme.key_avatar_backgroundGreen)), iconDrawable); if (placeholderImageView != null) { placeholderImageView.setImageDrawable(combinedDrawable); } else { imageView.setImageDrawable(combinedDrawable); } invalidate(); } public boolean isStub() { return showStub; } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/ui/Cells/SessionCell.java
2,200
package org.telegram.ui.Components; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import org.telegram.messenger.LiteMode; import org.telegram.messenger.SharedConfig; import java.util.Random; public class BlobDrawable { public static float MAX_SPEED = 8.2f; public static float MIN_SPEED = 0.8f; public static float AMPLITUDE_SPEED = 0.33f; public static float SCALE_BIG = 0.807f; public static float SCALE_SMALL = 0.704f; public static float SCALE_BIG_MIN = 0.878f; public static float SCALE_SMALL_MIN = 0.926f; public static float FORM_BIG_MAX = 0.6f; public static float FORM_SMALL_MAX = 0.6f; public static float GLOBAL_SCALE = 1f; public static float FORM_BUTTON_MAX = 0f; public static float GRADIENT_SPEED_MIN = 0.5f; public static float GRADIENT_SPEED_MAX = 0.01f; public static float LIGHT_GRADIENT_SIZE = 0.5f; public float minRadius; public float maxRadius; private Path path = new Path(); public Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); protected float[] radius; protected float[] angle; protected float[] radiusNext; protected float[] angleNext; protected float[] progress; protected float[] speed; private float[] pointStart = new float[4]; private float[] pointEnd = new float[4]; protected final Random random = new Random(); protected final float N; private final float L; public float cubicBezierK = 1f; private final Matrix m = new Matrix(); protected final int liteFlag; public BlobDrawable(int n) { this(n, LiteMode.FLAG_CALLS_ANIMATIONS); } public BlobDrawable(int n, int liteFlag) { N = n; L = (float) ((4.0 / 3.0) * Math.tan(Math.PI / (2 * N))); radius = new float[n]; angle = new float[n]; radiusNext = new float[n]; angleNext = new float[n]; progress = new float[n]; speed = new float[n]; for (int i = 0; i < N; i++) { generateBlob(radius, angle, i); generateBlob(radiusNext, angleNext, i); progress[i] = 0; } this.liteFlag = liteFlag; } protected void generateBlob(float[] radius, float[] angle, int i) { float angleDif = 360f / N * 0.05f; float radDif = maxRadius - minRadius; radius[i] = minRadius + Math.abs(((random.nextInt() % 100f) / 100f)) * radDif; angle[i] = 360f / N * i + ((random.nextInt() % 100f) / 100f) * angleDif; speed[i] = (float) (0.017 + 0.003 * (Math.abs(random.nextInt() % 100f) / 100f)); } public void update(float amplitude, float speedScale) { if (!LiteMode.isEnabled(liteFlag)) { return; } for (int i = 0; i < N; i++) { progress[i] += (speed[i] * MIN_SPEED) + amplitude * speed[i] * MAX_SPEED * speedScale; if (progress[i] >= 1f) { progress[i] = 0; radius[i] = radiusNext[i]; angle[i] = angleNext[i]; generateBlob(radiusNext, angleNext, i); } } } public void draw(float cX, float cY, Canvas canvas, Paint paint) { if (!LiteMode.isEnabled(liteFlag)) { return; } path.reset(); for (int i = 0; i < N; i++) { float progress = this.progress[i]; int nextIndex = i + 1 < N ? i + 1 : 0; float progressNext = this.progress[nextIndex]; float r1 = radius[i] * (1f - progress) + radiusNext[i] * progress; float r2 = radius[nextIndex] * (1f - progressNext) + radiusNext[nextIndex] * progressNext; float angle1 = angle[i] * (1f - progress) + angleNext[i] * progress; float angle2 = angle[nextIndex] * (1f - progressNext) + angleNext[nextIndex] * progressNext; float l = L * (Math.min(r1, r2) + (Math.max(r1, r2) - Math.min(r1, r2)) / 2f) * cubicBezierK; m.reset(); m.setRotate(angle1, cX, cY); pointStart[0] = cX; pointStart[1] = cY - r1; pointStart[2] = cX + l; pointStart[3] = cY - r1; m.mapPoints(pointStart); pointEnd[0] = cX; pointEnd[1] = cY - r2; pointEnd[2] = cX - l; pointEnd[3] = cY - r2; m.reset(); m.setRotate(angle2, cX, cY); m.mapPoints(pointEnd); if (i == 0) { path.moveTo(pointStart[0], pointStart[1]); } path.cubicTo( pointStart[2], pointStart[3], pointEnd[2], pointEnd[3], pointEnd[0], pointEnd[1] ); } canvas.save(); canvas.drawPath(path, paint); canvas.restore(); } public void generateBlob() { for (int i = 0; i < N; i++) { generateBlob(radius, angle, i); generateBlob(radiusNext, angleNext, i); progress[i] = 0; } } private float animateToAmplitude; public float amplitude; private float animateAmplitudeDiff; private final static float ANIMATION_SPEED_WAVE_HUGE = 0.65f; private final static float ANIMATION_SPEED_WAVE_SMALL = 0.45f; private final static float animationSpeed = 1f - ANIMATION_SPEED_WAVE_HUGE; private final static float animationSpeedTiny = 1f - ANIMATION_SPEED_WAVE_SMALL; public void setValue(float value) { amplitude = value; } public void setValue(float value, boolean isBig) { animateToAmplitude = value; if (!LiteMode.isEnabled(liteFlag)) { return; } if (isBig) { if (animateToAmplitude > amplitude) { animateAmplitudeDiff = (animateToAmplitude - amplitude) / (100f + 300f * animationSpeed); } else { animateAmplitudeDiff = (animateToAmplitude - amplitude) / (100 + 500f * animationSpeed); } } else { if (animateToAmplitude > amplitude) { animateAmplitudeDiff = (animateToAmplitude - amplitude) / (100f + 400f * animationSpeedTiny); } else { animateAmplitudeDiff = (animateToAmplitude - amplitude) / (100f + 500f * animationSpeedTiny); } } } public void updateAmplitude(long dt) { if (animateToAmplitude != amplitude) { amplitude += animateAmplitudeDiff * dt; if (animateAmplitudeDiff > 0) { if (amplitude > animateToAmplitude) { amplitude = animateToAmplitude; } } else { if (amplitude < animateToAmplitude) { amplitude = animateToAmplitude; } } } } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/ui/Components/BlobDrawable.java