update to 10.12.0 (4710)

This commit is contained in:
dkaraush 2024-05-02 20:38:57 +04:00
parent a906f12aae
commit d494ea8cb5
294 changed files with 20468 additions and 4408 deletions

View file

@ -48,6 +48,7 @@ dependencies {
implementation 'com.google.guava:guava:31.1-android' implementation 'com.google.guava:guava:31.1-android'
implementation 'com.google.android.gms:play-services-mlkit-subject-segmentation:16.0.0-beta1' implementation 'com.google.android.gms:play-services-mlkit-subject-segmentation:16.0.0-beta1'
implementation 'com.google.android.gms:play-services-mlkit-image-labeling:16.0.8'
constraints { constraints {
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0") { implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0") {
because("kotlin-stdlib-jdk7 is now a part of kotlin-stdlib") because("kotlin-stdlib-jdk7 is now a part of kotlin-stdlib")

View file

@ -182,9 +182,34 @@ JNIEXPORT jlong Java_org_telegram_ui_Components_RLottieDrawable_getFramesCount(J
delete info; delete info;
return 0; return 0;
} }
long frameCount = info->animation->totalFrame(); long framesCount = info->animation->totalFrame();
delete info; delete info;
return (jlong) frameCount; return (jlong) framesCount;
}
JNIEXPORT jdouble Java_org_telegram_ui_Components_RLottieDrawable_getDuration(JNIEnv *env, jclass clazz, jstring src, jstring json) {
auto info = new LottieInfo();
char const *srcString = env->GetStringUTFChars(src, nullptr);
info->path = srcString;
if (json != nullptr) {
char const *jsonString = env->GetStringUTFChars(json, nullptr);
if (jsonString) {
info->animation = rlottie::Animation::loadFromData(jsonString, info->path, nullptr, FitzModifier::None);
env->ReleaseStringUTFChars(json, jsonString);
}
} else {
info->animation = rlottie::Animation::loadFromFile(info->path, nullptr, FitzModifier::None);
}
if (srcString) {
env->ReleaseStringUTFChars(src, srcString);
}
if (info->animation == nullptr) {
delete info;
return 0;
}
double duration = info->animation->duration();
delete info;
return (jdouble) duration;
} }
JNIEXPORT jlong Java_org_telegram_ui_Components_RLottieDrawable_createWithJson(JNIEnv *env, jclass clazz, jstring json, jstring name, jintArray data, jintArray colorReplacement) { JNIEXPORT jlong Java_org_telegram_ui_Components_RLottieDrawable_createWithJson(JNIEnv *env, jclass clazz, jstring json, jstring name, jintArray data, jintArray colorReplacement) {

View file

@ -70,8 +70,9 @@ JNIEXPORT jlong JNICALL Java_org_telegram_messenger_video_WebmEncoder_createEnco
ctx->codec_ctx->time_base = (AVRational){ 1, fps }; ctx->codec_ctx->time_base = (AVRational){ 1, fps };
ctx->codec_ctx->framerate = (AVRational){ fps, 1 }; ctx->codec_ctx->framerate = (AVRational){ fps, 1 };
ctx->codec_ctx->bit_rate = bitrate; ctx->codec_ctx->bit_rate = bitrate;
ctx->codec_ctx->gop_size = 10; ctx->codec_ctx->rc_min_rate = bitrate / 8;
ctx->codec_ctx->max_b_frames = 1; ctx->codec_ctx->rc_max_rate = bitrate;
// ctx->codec_ctx->rc_buffer_size = 2 * bitrate;
if (ctx->fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) { if (ctx->fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) {
ctx->codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; ctx->codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
@ -185,6 +186,9 @@ JNIEXPORT jboolean JNICALL Java_org_telegram_messenger_video_WebmEncoder_writeFr
pkt.stream_index = ctx->video_stream->index; pkt.stream_index = ctx->video_stream->index;
ret = av_interleaved_write_frame(ctx->fmt_ctx, &pkt); ret = av_interleaved_write_frame(ctx->fmt_ctx, &pkt);
if (ret < 0) {
LOGE("vp9: failed to av_interleaved_write_frame %d", ret);
}
av_packet_unref(&pkt); av_packet_unref(&pkt);
} }
@ -200,13 +204,16 @@ JNIEXPORT void JNICALL Java_org_telegram_messenger_video_WebmEncoder_stop(
return; return;
} }
avcodec_send_frame(ctx->codec_ctx, NULL); int ret;
ret = avcodec_send_frame(ctx->codec_ctx, NULL);
if (ret < 0) {
LOGE("vp9: failed to avcodec_send_frame %d", ret);
}
AVPacket pkt; AVPacket pkt;
av_init_packet(&pkt); av_init_packet(&pkt);
pkt.data = NULL; pkt.data = NULL;
pkt.size = 0; pkt.size = 0;
int ret;
while (1) { while (1) {
ret = avcodec_receive_packet(ctx->codec_ctx, &pkt); ret = avcodec_receive_packet(ctx->codec_ctx, &pkt);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
@ -220,10 +227,16 @@ JNIEXPORT void JNICALL Java_org_telegram_messenger_video_WebmEncoder_stop(
pkt.stream_index = ctx->video_stream->index; pkt.stream_index = ctx->video_stream->index;
ret = av_interleaved_write_frame(ctx->fmt_ctx, &pkt); ret = av_interleaved_write_frame(ctx->fmt_ctx, &pkt);
if (ret < 0) {
LOGE("vp9: failed to av_interleaved_write_frame %d", ret);
}
av_packet_unref(&pkt); av_packet_unref(&pkt);
} }
av_write_trailer(ctx->fmt_ctx); ret = av_write_trailer(ctx->fmt_ctx);
if (ret < 0) {
LOGE("vp9: failed to av_write_trailer %d", ret);
}
if (ctx->frame) { if (ctx->frame) {
av_frame_free(&ctx->frame); av_frame_free(&ctx->frame);

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

View file

@ -27,102 +27,82 @@ uniform float time;
uniform mat4 world; uniform mat4 world;
void main() { void main() {
vec3 vLightPosition2 = vec3(-400, 40, 400);
vec3 vLightPosition3 = vec3(0, 200, 400);
vec3 vLightPosition4 = vec3(0, 0, 100);
vec3 vLightPositionNormal = vec3(100, -200, 400);
vec3 vNormalW = normalize(vec3(world * vec4(vNormal, 0.0)));
vec3 vTextureNormal = normalize(texture2D(u_NormalMap, vUV + vec2(-f_xOffset, f_xOffset)).xyz * 2.0 - 1.0);
vec3 finalNormal = normalize(vNormalW + vTextureNormal);
vec3 color = texture2D(u_Texture, vUV).xyz;
vec3 viewDirectionW = normalize(cameraPosition - modelViewVertex);
float border = 0.0;
if (modelIndex == 0) {
border = 1.0;
} else if (modelIndex == 2) {
border = texture2D(u_Texture, vUV).a;
}
float modelDiffuse = 0.1;
if (!night && modelIndex != 1) {
modelDiffuse = 0.01;
}
float diffuse = max(dot(vNormalW, viewDirectionW), (1.0 - modelDiffuse));
vec2 uv = vUV; vec2 uv = vUV;
if (modelIndex == 2) { if (modelIndex == 2) {
uv *= 2.0; uv *= 2.0;
uv = fract(uv); uv = fract(uv);
if (vUV.x > .5) { }
uv.x = 1.0 - uv.x; uv.x = 1.0 - uv.x;
}
}
float mixValue = clamp(distance(uv.xy, vec2(0.0)), 0.0, 1.0);
vec4 gradientColorFinal = vec4(mix(gradientColor1, gradientColor2, mixValue), 1.0);
float modelNormalSpec = normalSpec, modelSpec1 = 0.0, modelSpec2 = 0.05; float diagonal = ((uv.x + uv.y) / 2.0 - .15) / .6;
vec3 baseColor;
if (modelIndex == 0) {
baseColor = mix(
vec3(0.95686, 0.47451, 0.93725),
vec3(0.46274, 0.49411, 0.9960),
diagonal
);
} else if (modelIndex == 3) {
baseColor = mix(
vec3(0.95686, 0.47451, 0.93725),
vec3(0.46274, 0.49411, 0.9960),
diagonal
);
baseColor = mix(baseColor, vec3(1.0), .3);
} else if (modelIndex == 1) {
baseColor = mix(
vec3(0.67059, 0.25490, 0.80000),
vec3(0.39608, 0.18824, 0.98039),
diagonal
);
} else {
baseColor = mix(
vec3(0.91373, 0.62353, 0.99608),
vec3(0.67451, 0.58824, 1.00000),
clamp((uv.y - .2) / .6, 0.0, 1.0)
);
float darken = 1. - length(modelViewVertex - vec3(30., -75., 50.)) / 200.; baseColor = mix(baseColor, vec3(1.0), .1 + .45 * texture2D(u_Texture, vUV).a);
if (border > 0.) {
modelNormalSpec += border;
modelSpec1 += border;
modelSpec2 += border;
}
vec3 angleW = normalize(viewDirectionW + vLightPosition2);
float specComp2 = max(0., dot(finalNormal, angleW));
specComp2 = pow(specComp2, max(1., 128.)) * modelSpec1;
angleW = normalize(viewDirectionW + vLightPosition4);
float specComp3 = max(0., dot(finalNormal, angleW));
specComp3 = pow(specComp3, max(1., 30.)) * modelSpec2;
angleW = normalize(viewDirectionW + vLightPositionNormal);
float normalSpecComp = max(0., dot(finalNormal, angleW));
normalSpecComp = pow(normalSpecComp, max(1., 128.)) * modelNormalSpec;
angleW = normalize(viewDirectionW + vLightPosition2);
float normalSpecComp2 = max(0., dot(finalNormal, angleW));
normalSpecComp2 = pow(normalSpecComp2, max(1., 128.)) * modelNormalSpec;
vec4 normalSpecFinal = vec4(normalSpecColor, 0.0) * normalSpecComp2;
vec4 specFinal = vec4(color, 0.0) * (specComp2 + specComp3);
// float snap = fract((-gl_FragCoord.x / resolution.x + gl_FragCoord.y / resolution.y) / 20.0 + .2 * time) > .9 ? 1. : 0.;
vec4 fragColor = gradientColorFinal + specFinal;
vec4 backgroundColor = texture2D(u_BackgroundTexture, vec2(gradientPosition.x + (gl_FragCoord.x / resolution.x) * gradientPosition.y, gradientPosition.z + (1.0 - (gl_FragCoord.y / resolution.y)) * gradientPosition.w));
vec4 color4 = mix(backgroundColor, fragColor, diffuse);
if (night) { if (night) {
angleW = normalize(viewDirectionW + vLightPosition2); baseColor = mix(baseColor, vec3(.0), .06);
float normalSpecComp = max(0., dot(finalNormal, angleW));
normalSpecComp = pow(normalSpecComp, max(1., 128.));
if (normalSpecComp > .2 && modelIndex != 0) {
color4.rgb += vec3(.5) * max(0., vTextureNormal.x) * normalSpecComp;
}
if (modelIndex == 1) {
color4.rgb *= .9;
} else {
color4.rgb += vec3(1.0) * .17;
}
} else {
if (modelIndex == 1) {
if (darken > .5) {
color4.rgb *= vec3(0.78039, 0.77254, 0.95294);
} else {
color4.rgb *= vec3(0.83921, 0.83529, 0.96862);
}
} else {
if (darken > .5) {
color4.rgb *= vec3(.945098, .94117, 1.0);
color4.rgb += vec3(.06) * border;
} }
} }
vec3 pos = modelViewVertex / 100.0 + .5;
vec3 norm = normalize(vec3(world * vec4(vNormal, 0.0)));
vec3 flecksLightPos = vec3(.5, .5, .5);
vec3 flecksLightDir = normalize(flecksLightPos - pos);
vec3 flecksReflectDir = reflect(-flecksLightDir, norm);
float flecksSpec = pow(max(dot(normalize(vec3(0.0) - pos), flecksReflectDir), 0.0), 8.0);
vec3 flecksNormal = normalize(texture2D(u_NormalMap, uv * 1.3 + vec2(.02, .06) * time).xyz * 2.0 - 1.0);
float flecks = max(flecksNormal.x, flecksNormal.y) * flecksSpec;
norm += flecksSpec * flecksNormal;
norm = normalize(norm);
vec3 lightPos = vec3(-3., -3., 20.);
vec3 lightDir = normalize(lightPos - pos);
float diffuse = max(dot(norm, lightDir), 0.0);
float spec = 0.0;
lightPos = vec3(-3., -3., .5);
spec += 2.0 * pow(max(dot(normalize(vec3(0.0) - pos), reflect(-normalize(lightPos - pos), norm)), 0.0), 2.0);
lightPos = vec3(-3., .5, 30.);
spec += (modelIndex == 1 ? 1.5 : 0.5) * pow(max(dot(normalize(vec3(0.0) - pos), reflect(-normalize(lightPos - pos), norm)), 0.0), 32.0);
// lightPos = vec3(3., .5, .5);
// spec += pow(max(dot(normalize(vec3(0.0) - pos), reflect(-normalize(lightPos - pos), norm)), 0.0), 32.0);
if (modelIndex != 0) {
spec *= .25;
} }
gl_FragColor = color4 * f_alpha;
vec3 color = baseColor;
color *= .94 + .22 * diffuse;
color = mix(color, vec3(1.0), spec);
// color = mix(color, vec3(1.0), 0.35 * flecks);
gl_FragColor = vec4(color, 1.0);
} }

View file

@ -207,7 +207,13 @@ import java.util.Hashtable;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -265,9 +271,11 @@ public class AndroidUtilities {
public static final RectF rectTmp = new RectF(); public static final RectF rectTmp = new RectF();
public static final Rect rectTmp2 = new Rect(); public static final Rect rectTmp2 = new Rect();
public static final int[] pointTmp2 = new int[2];
public static Pattern WEB_URL = null; public static Pattern WEB_URL = null;
public static Pattern BAD_CHARS_PATTERN = null; public static Pattern BAD_CHARS_PATTERN = null;
public static Pattern LONG_BAD_CHARS_PATTERN = null;
public static Pattern BAD_CHARS_MESSAGE_PATTERN = null; public static Pattern BAD_CHARS_MESSAGE_PATTERN = null;
public static Pattern BAD_CHARS_MESSAGE_LONG_PATTERN = null; public static Pattern BAD_CHARS_MESSAGE_LONG_PATTERN = null;
private static Pattern singleTagPatter = null; private static Pattern singleTagPatter = null;
@ -276,6 +284,7 @@ public class AndroidUtilities {
try { try {
final String GOOD_IRI_CHAR = "a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF"; final String GOOD_IRI_CHAR = "a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF";
BAD_CHARS_PATTERN = Pattern.compile("[\u2500-\u25ff]"); BAD_CHARS_PATTERN = Pattern.compile("[\u2500-\u25ff]");
LONG_BAD_CHARS_PATTERN = Pattern.compile("[\u4e00-\u9fff]");
BAD_CHARS_MESSAGE_LONG_PATTERN = Pattern.compile("[\u0300-\u036f\u2066-\u2067]+"); BAD_CHARS_MESSAGE_LONG_PATTERN = Pattern.compile("[\u0300-\u036f\u2066-\u2067]+");
BAD_CHARS_MESSAGE_PATTERN = Pattern.compile("[\u2066-\u2067]+"); BAD_CHARS_MESSAGE_PATTERN = Pattern.compile("[\u2066-\u2067]+");
final Pattern IP_ADDRESS = Pattern.compile( final Pattern IP_ADDRESS = Pattern.compile(
@ -565,9 +574,13 @@ public class AndroidUtilities {
} }
public static CharSequence replaceArrows(CharSequence text, boolean link) { public static CharSequence replaceArrows(CharSequence text, boolean link) {
return replaceArrows(text, link, dp(8f / 3f), 0);
}
public static CharSequence replaceArrows(CharSequence text, boolean link, float translateX, float translateY) {
ColoredImageSpan span = new ColoredImageSpan(R.drawable.msg_mini_forumarrow, DynamicDrawableSpan.ALIGN_BOTTOM); ColoredImageSpan span = new ColoredImageSpan(R.drawable.msg_mini_forumarrow, DynamicDrawableSpan.ALIGN_BOTTOM);
span.setScale(.88f, .88f); span.setScale(.88f, .88f);
span.translate(-dp(8f / 3f), 0); span.translate(-translateX, translateY);
span.spaceScaleX = .8f; span.spaceScaleX = .8f;
if (link) { if (link) {
span.useLinkPaintColor = link; span.useLinkPaintColor = link;
@ -581,6 +594,23 @@ public class AndroidUtilities {
rightArrow.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); rightArrow.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text = AndroidUtilities.replaceMultipleCharSequence(">", text, rightArrow); text = AndroidUtilities.replaceMultipleCharSequence(">", text, rightArrow);
span = new ColoredImageSpan(R.drawable.msg_mini_forumarrow, DynamicDrawableSpan.ALIGN_BOTTOM);
span.setScale(.88f, .88f);
span.translate(translateX, translateY);
span.rotate(180f);
span.spaceScaleX = .8f;
if (link) {
span.useLinkPaintColor = link;
}
// SpannableString leftArrow = new SpannableString("< ");
// leftArrow.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// text = AndroidUtilities.replaceMultipleCharSequence("< ", text, leftArrow);
SpannableString leftArrow = new SpannableString("<");
leftArrow.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text = AndroidUtilities.replaceMultipleCharSequence("<", text, leftArrow);
return text; return text;
} }
@ -938,14 +968,56 @@ public class AndroidUtilities {
return true; return true;
}; };
@Deprecated // use addLinksSafe
public static boolean addLinks(Spannable text, int mask) { public static boolean addLinks(Spannable text, int mask) {
return addLinks(text, mask, false); return addLinks(text, mask, false);
} }
@Deprecated // use addLinksSafe
public static boolean addLinks(Spannable text, int mask, boolean internalOnly) { public static boolean addLinks(Spannable text, int mask, boolean internalOnly) {
return addLinks(text, mask, internalOnly, true); return addLinks(text, mask, internalOnly, true);
} }
public static boolean addLinksSafe(Spannable text, int mask, boolean internalOnly, boolean removeOldReplacements) {
SpannableStringBuilder newText = new SpannableStringBuilder(text);
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Boolean> task = () -> {
try {
return addLinks(newText, mask, internalOnly, removeOldReplacements);
} catch (Exception e) {
FileLog.e(e);
return false;
}
};
boolean success = false;
Future<Boolean> future = null;
try {
future = executor.submit(task);
success = future.get(200, TimeUnit.MILLISECONDS);
} catch (TimeoutException ex) {
if (future != null) {
future.cancel(true);
}
} catch (Exception ex) {
FileLog.e(ex);
} finally {
executor.shutdownNow();
}
if (success && text != null) {
URLSpan[] oldSpans = text.getSpans(0, text.length(), URLSpan.class);
for (int i = 0; i < oldSpans.length; ++i) {
text.removeSpan(oldSpans[i]);
}
URLSpan[] newSpans = newText.getSpans(0, newText.length(), URLSpan.class);
for (int i = 0; i < newSpans.length; ++i) {
text.setSpan(newSpans[i], newText.getSpanStart(newSpans[i]), newText.getSpanEnd(newSpans[i]), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return true;
}
return false;
}
@Deprecated // use addLinksSafe
public static boolean addLinks(Spannable text, int mask, boolean internalOnly, boolean removeOldReplacements) { public static boolean addLinks(Spannable text, int mask, boolean internalOnly, boolean removeOldReplacements) {
if (text == null || containsUnsupportedCharacters(text.toString()) || mask == 0) { if (text == null || containsUnsupportedCharacters(text.toString()) || mask == 0) {
return false; return false;

View file

@ -51,12 +51,8 @@ public class AnimatedFileDrawableStream implements FileLoadOperationStream {
debugCanceledCount++; debugCanceledCount++;
if (!debugReportSend && debugCanceledCount > 200) { if (!debugReportSend && debugCanceledCount > 200) {
debugReportSend = true; debugReportSend = true;
if (BuildVars.DEBUG_PRIVATE_VERSION) {
throw new RuntimeException("infinity stream reading!!!");
} else {
FileLog.e(new RuntimeException("infinity stream reading!!!")); FileLog.e(new RuntimeException("infinity stream reading!!!"));
} }
}
return 0; return 0;
} }
} }

View file

@ -120,4 +120,9 @@ public class AuthTokensHelper {
preferences.edit().putString("log_out_token_" + count, Utilities.bytesToHex(data.toByteArray())).putInt("count", count + 1).apply(); preferences.edit().putString("log_out_token_" + count, Utilities.bytesToHex(data.toByteArray())).putInt("count", count + 1).apply();
BackupAgent.requestBackup(ApplicationLoader.applicationContext); BackupAgent.requestBackup(ApplicationLoader.applicationContext);
} }
public static void clearLogInTokens() {
ApplicationLoader.applicationContext.getSharedPreferences("saved_tokens_login", Context.MODE_PRIVATE).edit().clear().apply();
ApplicationLoader.applicationContext.getSharedPreferences("saved_tokens", Context.MODE_PRIVATE).edit().clear().apply();
}
} }

View file

@ -1592,6 +1592,51 @@ public class ChatObject {
return chat != null && (getBannedRight(chat.banned_rights, action) || getBannedRight(chat.default_banned_rights, action)); return chat != null && (getBannedRight(chat.banned_rights, action) || getBannedRight(chat.default_banned_rights, action));
} }
public static boolean canUserDoAdminAction(TLRPC.TL_chatAdminRights admin_rights, int action) {
if (admin_rights != null) {
boolean value;
switch (action) {
case ACTION_PIN:
value = admin_rights.pin_messages;
break;
case ACTION_MANAGE_TOPICS:
value = admin_rights.manage_topics;
break;
case ACTION_CHANGE_INFO:
value = admin_rights.change_info;
break;
case ACTION_INVITE:
value = admin_rights.invite_users;
break;
case ACTION_ADD_ADMINS:
value = admin_rights.add_admins;
break;
case ACTION_POST:
value = admin_rights.post_messages;
break;
case ACTION_EDIT_MESSAGES:
value = admin_rights.edit_messages;
break;
case ACTION_DELETE_MESSAGES:
value = admin_rights.delete_messages;
break;
case ACTION_BLOCK_USERS:
value = admin_rights.ban_users;
break;
case ACTION_MANAGE_CALLS:
value = admin_rights.manage_call;
break;
default:
value = false;
break;
}
if (value) {
return true;
}
}
return false;
}
public static boolean canUserDoAdminAction(TLRPC.Chat chat, int action) { public static boolean canUserDoAdminAction(TLRPC.Chat chat, int action) {
if (chat == null) { if (chat == null) {
return false; return false;
@ -1643,6 +1688,43 @@ public class ChatObject {
return false; return false;
} }
public static boolean canUserDoAction(TLRPC.Chat chat, TLRPC.ChannelParticipant participant, int action) {
if (chat == null) {
return true;
}
if (participant == null) {
return false;
}
if (canUserDoAdminAction(participant.admin_rights, action)) {
return true;
}
if (getBannedRight(participant.banned_rights, action)) {
return false;
}
if (isBannableAction(action)) {
if (participant.admin_rights != null && !isAdminAction(action)) {
return true;
}
if (chat.default_banned_rights == null && (
chat instanceof TLRPC.TL_chat_layer92 ||
chat instanceof TLRPC.TL_chat_old ||
chat instanceof TLRPC.TL_chat_old2 ||
chat instanceof TLRPC.TL_channel_layer92 ||
chat instanceof TLRPC.TL_channel_layer77 ||
chat instanceof TLRPC.TL_channel_layer72 ||
chat instanceof TLRPC.TL_channel_layer67 ||
chat instanceof TLRPC.TL_channel_layer48 ||
chat instanceof TLRPC.TL_channel_old)) {
return true;
}
if (chat.default_banned_rights == null || getBannedRight(chat.default_banned_rights, action)) {
return false;
}
return true;
}
return false;
}
public static boolean canUserDoAction(TLRPC.Chat chat, int action) { public static boolean canUserDoAction(TLRPC.Chat chat, int action) {
if (chat == null) { if (chat == null) {
return true; return true;

View file

@ -233,9 +233,9 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media;
if (Build.VERSION.SDK_INT >= 18) { if (Build.VERSION.SDK_INT >= 18) {
innerMessage = String.format("\uD83D\uDCCA \u2068%s\u2069", mediaPoll.poll.question); innerMessage = String.format("\uD83D\uDCCA \u2068%s\u2069", mediaPoll.poll.question.text);
} else { } else {
innerMessage = String.format("\uD83D\uDCCA %s", mediaPoll.poll.question); innerMessage = String.format("\uD83D\uDCCA %s", mediaPoll.poll.question.text);
} }
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) { } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
if (Build.VERSION.SDK_INT >= 18) { if (Build.VERSION.SDK_INT >= 18) {
@ -297,7 +297,7 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
} else { } else {
if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media;
messageString = "\uD83D\uDCCA " + mediaPoll.poll.question; messageString = "\uD83D\uDCCA " + mediaPoll.poll.question.text;
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) { } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
messageString = "\uD83C\uDFAE " + message.messageOwner.media.game.title; messageString = "\uD83C\uDFAE " + message.messageOwner.media.game.title;
} else if (message.type == MessageObject.TYPE_MUSIC) { } else if (message.type == MessageObject.TYPE_MUSIC) {

View file

@ -1497,6 +1497,13 @@ public class DatabaseMigrationHelper {
version = 152; version = 152;
} }
if (version == 152) {
database.executeFast("ALTER TABLE profile_stories ADD COLUMN pin INTEGER default 0;").stepThis().dispose();
database.executeFast("PRAGMA user_version = 153").stepThis().dispose();
version = 153;
}
return version; return version;
} }

View file

@ -45,18 +45,34 @@ public class DocumentObject {
} }
} }
public static boolean containsPhotoSizeType(ArrayList<TLRPC.PhotoSize> sizes, String type) {
if (type == null)
return false;
for (int a = 0, N = sizes.size(); a < N; a++) {
TLRPC.PhotoSize photoSize = sizes.get(a);
if (type.equalsIgnoreCase(photoSize.type))
return true;
}
return false;
}
public static SvgHelper.SvgDrawable getSvgThumb(ArrayList<TLRPC.PhotoSize> sizes, int colorKey, float alpha) { public static SvgHelper.SvgDrawable getSvgThumb(ArrayList<TLRPC.PhotoSize> sizes, int colorKey, float alpha) {
int w = 0; return getSvgThumb(sizes, colorKey, alpha, false);
int h = 0; }
public static SvgHelper.SvgDrawable getSvgThumb(ArrayList<TLRPC.PhotoSize> sizes, int colorKey, float alpha, boolean usePhotoSize) {
int w = 512;
int h = 512;
TLRPC.TL_photoPathSize photoPathSize = null; TLRPC.TL_photoPathSize photoPathSize = null;
for (int a = 0, N = sizes.size(); a < N; a++) { for (int a = 0, N = sizes.size(); a < N; a++) {
TLRPC.PhotoSize photoSize = sizes.get(a); TLRPC.PhotoSize photoSize = sizes.get(a);
if (photoSize instanceof TLRPC.TL_photoPathSize) { if (photoSize instanceof TLRPC.TL_photoPathSize) {
photoPathSize = (TLRPC.TL_photoPathSize) photoSize; photoPathSize = (TLRPC.TL_photoPathSize) photoSize;
} else if (photoSize instanceof TLRPC.TL_photoSize) { } else if (photoSize instanceof TLRPC.TL_photoSize && usePhotoSize) {
w = photoSize.w; w = photoSize.w;
h = photoSize.h; h = photoSize.h;
} }
}
if (photoPathSize != null && w != 0 && h != 0) { if (photoPathSize != null && w != 0 && h != 0) {
SvgHelper.SvgDrawable pathThumb = SvgHelper.getDrawableByPath(photoPathSize.svgPath, w, h); SvgHelper.SvgDrawable pathThumb = SvgHelper.getDrawableByPath(photoPathSize.svgPath, w, h);
if (pathThumb != null) { if (pathThumb != null) {
@ -64,7 +80,6 @@ public class DocumentObject {
} }
return pathThumb; return pathThumb;
} }
}
return null; return null;
} }

View file

@ -38,6 +38,7 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Objects;
public class Emoji { public class Emoji {
@ -796,6 +797,14 @@ public class Emoji {
} }
super.updateDrawState(ds); super.updateDrawState(ds);
} }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EmojiSpan emojiSpan = (EmojiSpan) o;
return Float.compare(scale, emojiSpan.scale) == 0 && size == emojiSpan.size && Objects.equals(emoji, emojiSpan.emoji);
}
} }
public static void addRecentEmoji(String code) { public static void addRecentEmoji(String code) {

View file

@ -867,6 +867,9 @@ public class FileLoadOperation {
startDownloadRequest(-1); startDownloadRequest(-1);
nextPartWasPreloaded = false; nextPartWasPreloaded = false;
} }
if (notLoadedBytesRanges != null) {
notifyStreamListeners();
}
}); });
} else if (alreadyStarted) { } else if (alreadyStarted) {
Utilities.stageQueue.postRunnable(() -> { Utilities.stageQueue.postRunnable(() -> {

View file

@ -91,7 +91,7 @@ public class FileRefController extends BaseController {
} else if (parentObject instanceof MessageObject) { } else if (parentObject instanceof MessageObject) {
MessageObject messageObject = (MessageObject) parentObject; MessageObject messageObject = (MessageObject) parentObject;
long channelId = messageObject.getChannelId(); long channelId = messageObject.getChannelId();
return "message" + messageObject.getRealId() + "_" + channelId + "_" + messageObject.scheduled; return "message" + messageObject.getRealId() + "_" + channelId + "_" + messageObject.scheduled + "_" + messageObject.getQuickReplyId();
} else if (parentObject instanceof TLRPC.Message) { } else if (parentObject instanceof TLRPC.Message) {
TLRPC.Message message = (TLRPC.Message) parentObject; TLRPC.Message message = (TLRPC.Message) parentObject;
long channelId = message.peer_id != null ? message.peer_id.channel_id : 0; long channelId = message.peer_id != null ? message.peer_id.channel_id : 0;
@ -210,6 +210,11 @@ public class FileRefController extends BaseController {
locationKey = "file_" + req.id.id; locationKey = "file_" + req.id.id;
location = new TLRPC.TL_inputDocumentFileLocation(); location = new TLRPC.TL_inputDocumentFileLocation();
location.id = req.id.id; location.id = req.id.id;
} else if (args[0] instanceof TLRPC.TL_stickers_addStickerToSet) {
TLRPC.TL_stickers_addStickerToSet req = (TLRPC.TL_stickers_addStickerToSet) args[0];
locationKey = "file_" + req.sticker.document.id;
location = new TLRPC.TL_inputDocumentFileLocation();
location.id = req.sticker.document.id;
} else if (args[0] instanceof TLRPC.TL_messages_faveSticker) { } else if (args[0] instanceof TLRPC.TL_messages_faveSticker) {
TLRPC.TL_messages_faveSticker req = (TLRPC.TL_messages_faveSticker) args[0]; TLRPC.TL_messages_faveSticker req = (TLRPC.TL_messages_faveSticker) args[0];
locationKey = "file_" + req.id.id; locationKey = "file_" + req.id.id;
@ -390,6 +395,12 @@ public class FileRefController extends BaseController {
req.peer = getMessagesController().getInputPeer(messageObject.getDialogId()); req.peer = getMessagesController().getInputPeer(messageObject.getDialogId());
req.id.add(messageObject.getRealId()); req.id.add(messageObject.getRealId());
getConnectionsManager().sendRequest(req, (response, error) -> onRequestComplete(locationKey, parentKey, response, error, true, false)); getConnectionsManager().sendRequest(req, (response, error) -> onRequestComplete(locationKey, parentKey, response, error, true, false));
} else if (messageObject.isQuickReply()) {
TLRPC.TL_messages_getQuickReplyMessages req = new TLRPC.TL_messages_getQuickReplyMessages();
req.shortcut_id = messageObject.getQuickReplyId();
req.flags |= 1;
req.id.add(messageObject.getRealId());
getConnectionsManager().sendRequest(req, (response, error) -> onRequestComplete(locationKey, parentKey, response, error, true, false));
} else if (channelId != 0) { } else if (channelId != 0) {
TLRPC.TL_channels_getMessages req = new TLRPC.TL_channels_getMessages(); TLRPC.TL_channels_getMessages req = new TLRPC.TL_channels_getMessages();
req.channel = getMessagesController().getInputChannel(channelId); req.channel = getMessagesController().getInputChannel(channelId);
@ -638,6 +649,15 @@ public class FileRefController extends BaseController {
req.id.file_reference = file_reference; req.id.file_reference = file_reference;
getConnectionsManager().sendRequest(req, (response, error) -> { getConnectionsManager().sendRequest(req, (response, error) -> {
});
} else if (requester.args[0] instanceof TLRPC.TL_stickers_addStickerToSet) {
TLRPC.TL_stickers_addStickerToSet req = (TLRPC.TL_stickers_addStickerToSet) requester.args[0];
if (fromCache && isSameReference(req.sticker.document.file_reference, file_reference)) {
return false;
}
req.sticker.document.file_reference = file_reference;
getConnectionsManager().sendRequest(req, (response, error) -> {
}); });
} else if (requester.args[0] instanceof TLRPC.TL_messages_faveSticker) { } else if (requester.args[0] instanceof TLRPC.TL_messages_faveSticker) {
TLRPC.TL_messages_faveSticker req = (TLRPC.TL_messages_faveSticker) requester.args[0]; TLRPC.TL_messages_faveSticker req = (TLRPC.TL_messages_faveSticker) requester.args[0];
@ -717,6 +737,9 @@ public class FileRefController extends BaseController {
} else if (args[0] instanceof TLRPC.TL_messages_saveRecentSticker) { } else if (args[0] instanceof TLRPC.TL_messages_saveRecentSticker) {
TLRPC.TL_messages_saveRecentSticker req = (TLRPC.TL_messages_saveRecentSticker) args[0]; TLRPC.TL_messages_saveRecentSticker req = (TLRPC.TL_messages_saveRecentSticker) args[0];
//do nothing //do nothing
} else if (args[0] instanceof TLRPC.TL_stickers_addStickerToSet) {
TLRPC.TL_stickers_addStickerToSet req = (TLRPC.TL_stickers_addStickerToSet) args[0];
//do nothing
} else if (args[0] instanceof TLRPC.TL_messages_faveSticker) { } else if (args[0] instanceof TLRPC.TL_messages_faveSticker) {
TLRPC.TL_messages_faveSticker req = (TLRPC.TL_messages_faveSticker) args[0]; TLRPC.TL_messages_faveSticker req = (TLRPC.TL_messages_faveSticker) args[0];
//do nothing //do nothing
@ -779,11 +802,10 @@ public class FileRefController extends BaseController {
continue; continue;
} }
if (error != null && BuildVars.LOGS_ENABLED) { if (error != null && BuildVars.LOGS_ENABLED) {
if (requester.args[1] instanceof FileLoadOperation) { if (requester.args.length > 1 && requester.args[1] instanceof FileLoadOperation) {
FileLoadOperation operation = (FileLoadOperation) requester.args[1]; FileLoadOperation operation = (FileLoadOperation) requester.args[1];
FileLog.e("debug_loading: " + operation.getCacheFileFinal().getName() + " can't update file reference: " + error.code + " " + error.text); FileLog.e("debug_loading: " + operation.getCacheFileFinal().getName() + " can't update file reference: " + error.code + " " + error.text);
} }
} }
if (requester.location instanceof TLRPC.TL_inputFileLocation || requester.location instanceof TLRPC.TL_inputPeerPhotoFileLocation) { if (requester.location instanceof TLRPC.TL_inputFileLocation || requester.location instanceof TLRPC.TL_inputPeerPhotoFileLocation) {
locationReplacement = new TLRPC.InputFileLocation[1]; locationReplacement = new TLRPC.InputFileLocation[1];

View file

@ -3584,6 +3584,8 @@ public class ImageLoader {
} }
url = url + docExt; url = url + docExt;
saveImageToCache = !MessageObject.isVideoDocument(object.document) && !MessageObject.isGifDocument(object.document) && !MessageObject.isRoundVideoDocument(object.document) && !MessageObject.canPreviewDocument(object.document); saveImageToCache = !MessageObject.isVideoDocument(object.document) && !MessageObject.isGifDocument(object.document) && !MessageObject.isRoundVideoDocument(object.document) && !MessageObject.canPreviewDocument(object.document);
} else if (parentObject instanceof TLRPC.StickerSet) {
url = url + "." + ext;
} }
if (a == 0) { if (a == 0) {
imageKey = key; imageKey = key;

View file

@ -297,6 +297,22 @@ public class ImageLocation {
return imageLocation; return imageLocation;
} }
public static ImageLocation getForStickerSet(TLRPC.StickerSet set) {
if (set == null) return null;
TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(set.thumbs, 90);
if (photoSize == null) return null;
TLRPC.InputStickerSet inputStickerSet;
if (set.access_hash != 0) {
inputStickerSet = new TLRPC.TL_inputStickerSetID();
inputStickerSet.id = set.id;
inputStickerSet.access_hash = set.access_hash;
} else {
inputStickerSet = new TLRPC.TL_inputStickerSetShortName();
inputStickerSet.short_name = set.short_name;
}
return getForPhoto(photoSize.location, photoSize.size, null, null, null, TYPE_SMALL, photoSize.location.dc_id, inputStickerSet, photoSize.type);
}
private static ImageLocation getForPhoto(TLRPC.FileLocation location, int size, TLRPC.Photo photo, TLRPC.Document document, TLRPC.InputPeer photoPeer, int photoPeerType, int dc_id, TLRPC.InputStickerSet stickerSet, String thumbSize) { private static ImageLocation getForPhoto(TLRPC.FileLocation location, int size, TLRPC.Photo photo, TLRPC.Document document, TLRPC.InputPeer photoPeer, int photoPeerType, int dc_id, TLRPC.InputStickerSet stickerSet, String thumbSize) {
if (location == null || photo == null && photoPeer == null && stickerSet == null && document == null) { if (location == null || photo == null && photoPeer == null && stickerSet == null && document == null) {
return null; return null;

View file

@ -1647,6 +1647,9 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
if (drawable instanceof SvgHelper.SvgDrawable) { if (drawable instanceof SvgHelper.SvgDrawable) {
svgDrawable = (SvgHelper.SvgDrawable) drawable; svgDrawable = (SvgHelper.SvgDrawable) drawable;
svgDrawable.setParent(this); 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) { if (colorFilter != null && drawable != null) {
drawable.setColorFilter(colorFilter); drawable.setColorFilter(colorFilter);

View file

@ -577,7 +577,11 @@ public class LocationController extends BaseController implements NotificationCe
info.lastSentProximityMeters = info.proximityMeters = message.media.proximity_notification_radius; info.lastSentProximityMeters = info.proximityMeters = message.media.proximity_notification_radius;
info.account = currentAccount; info.account = currentAccount;
info.messageObject = new MessageObject(currentAccount, message, false, false); info.messageObject = new MessageObject(currentAccount, message, false, false);
if (info.period == 0x7FFFFFFF) {
info.stopTime = Integer.MAX_VALUE;
} else {
info.stopTime = getConnectionsManager().getCurrentTime() + info.period; info.stopTime = getConnectionsManager().getCurrentTime() + info.period;
}
final SharingLocationInfo old = sharingLocationsMap.get(info.did); final SharingLocationInfo old = sharingLocationsMap.get(info.did);
sharingLocationsMap.put(info.did, info); sharingLocationsMap.put(info.did, info);
if (old != null) { if (old != null) {

View file

@ -455,6 +455,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
public boolean isMuted; public boolean isMuted;
public boolean canDeleteAfter; public boolean canDeleteAfter;
public boolean hasSpoiler; public boolean hasSpoiler;
public String emoji;
public boolean isChatPreviewSpoilerRevealed; public boolean isChatPreviewSpoilerRevealed;
public boolean isAttachSpoilerRevealed; public boolean isAttachSpoilerRevealed;
@ -527,6 +528,39 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
hasSpoiler = false; hasSpoiler = false;
super.reset(); 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 static class SearchImage extends MediaEditState {

View file

@ -1177,7 +1177,24 @@ public class MediaDataController extends BaseController {
} }
public TLRPC.TL_messages_stickerSet getStickerSetByName(String name) { public TLRPC.TL_messages_stickerSet getStickerSetByName(String name) {
return stickerSetsByName.get(name); if (name == null) return null;
return stickerSetsByName.get(name.toLowerCase());
}
public void findStickerSetByNameInCache(String name, Utilities.Callback<TLRPC.TL_messages_stickerSet> whenFound) {
if (whenFound == null)
return;
if (name == null) {
whenFound.run(null);
return;
}
getMessagesStorage().getStorageQueue().postRunnable(() -> {
TLRPC.TL_messages_stickerSet cachedSet = getCachedStickerSetInternal(name.toLowerCase(), 0);
AndroidUtilities.runOnUIThread(() -> {
putStickerSet(cachedSet, false);
whenFound.run(cachedSet);
});
});
} }
public TLRPC.TL_messages_stickerSet getStickerSetByEmojiOrName(String emoji) { public TLRPC.TL_messages_stickerSet getStickerSetByEmojiOrName(String emoji) {
@ -1363,6 +1380,42 @@ public class MediaDataController extends BaseController {
return null; return null;
} }
public void putStickerSet(TLRPC.TL_messages_stickerSet set) {
putStickerSet(set, true);
}
public void putStickerSet(TLRPC.TL_messages_stickerSet set, boolean notify) {
if (set == null || set.set == null) return;
stickerSetsById.put(set.set.id, set);
if (!TextUtils.isEmpty(set.set.short_name)) {
stickerSetsByName.put(set.set.short_name.toLowerCase(), set);
}
for (int i = 0; i < stickerSets.length; ++i) {
ArrayList<TLRPC.TL_messages_stickerSet> sets = stickerSets[i];
if (sets != null) {
for (int j = 0; j < sets.size(); ++j) {
TLRPC.TL_messages_stickerSet setB = sets.get(j);
if (setB != null && setB.set != null && setB.set.id == set.set.id) {
sets.set(j, set);
}
}
}
}
if (groupStickerSets.containsKey(set.set.id)) {
groupStickerSets.put(set.set.id, set);
}
saveStickerSetIntoCache(set);
int type = TYPE_IMAGE;
if (set.set.masks) {
type = TYPE_MASK;
} else if (set.set.emojis) {
type = TYPE_EMOJIPACKS;
}
if (notify) {
getNotificationCenter().postNotificationName(NotificationCenter.stickersDidLoad, type, true);
}
}
private boolean cleanedupStickerSetCache; private boolean cleanedupStickerSetCache;
private void cleanupStickerSetCache() { private void cleanupStickerSetCache() {
if (cleanedupStickerSetCache) { if (cleanedupStickerSetCache) {
@ -2071,8 +2124,11 @@ public class MediaDataController extends BaseController {
} }
public void storeTempStickerSet(TLRPC.TL_messages_stickerSet set) { public void storeTempStickerSet(TLRPC.TL_messages_stickerSet set) {
if (set == null || set.set == null) return;
stickerSetsById.put(set.set.id, set); stickerSetsById.put(set.set.id, set);
stickerSetsByName.put(set.set.short_name, set); if (set.set.short_name != null) {
stickerSetsByName.put(set.set.short_name.toLowerCase(), set);
}
} }
public void addNewStickerSet(TLRPC.TL_messages_stickerSet set) { public void addNewStickerSet(TLRPC.TL_messages_stickerSet set) {
@ -3236,7 +3292,9 @@ public class MediaDataController extends BaseController {
stickerSets[type].add(finalCurrentIndex, messages_stickerSet); stickerSets[type].add(finalCurrentIndex, messages_stickerSet);
stickerSetsById.put(stickerSet.id, messages_stickerSet); stickerSetsById.put(stickerSet.id, messages_stickerSet);
installedStickerSetsById.put(stickerSet.id, messages_stickerSet); installedStickerSetsById.put(stickerSet.id, messages_stickerSet);
stickerSetsByName.put(stickerSet.short_name, messages_stickerSet); if (stickerSet.short_name != null) {
stickerSetsByName.put(stickerSet.short_name.toLowerCase(), messages_stickerSet);
}
removingStickerSetsUndos.remove(stickerSet.id); removingStickerSetsUndos.remove(stickerSet.id);
loadHash[type] = calcStickersHash(stickerSets[type]); loadHash[type] = calcStickersHash(stickerSets[type]);
@ -5940,7 +5998,7 @@ public class MediaDataController extends BaseController {
object.applyTimestampsHighlightForReplyMsg(); object.applyTimestampsHighlightForReplyMsg();
object.messageOwner.reply_to = new TLRPC.TL_messageReplyHeader(); object.messageOwner.reply_to = new TLRPC.TL_messageReplyHeader();
object.messageOwner.reply_to.flags |= 16; object.messageOwner.reply_to.flags |= 16;
object.messageOwner.reply_to.reply_to_msg_id = messageObject.getId(); object.messageOwner.reply_to.reply_to_msg_id = messageObject.getRealId();
} }
} }
} }
@ -5974,14 +6032,14 @@ public class MediaDataController extends BaseController {
if (messageObject == null) { if (messageObject == null) {
continue; continue;
} }
if (!messageObject.isReplyToStory() && messageObject.isReply() && messageObject.getId() > 0) { if (!messageObject.isReplyToStory() && messageObject.isReply() && messageObject.getRealId() > 0) {
if (messageObject.messageOwner.reply_to.reply_to_peer_id != null) { if (messageObject.messageOwner.reply_to.reply_to_peer_id != null) {
continue; continue;
} }
int reply_to_id = messageObject.messageOwner.reply_to.reply_to_msg_id; int reply_to_id = messageObject.messageOwner.reply_to.reply_to_msg_id;
for (int j = 0; j < messages.size(); ++j) { for (int j = 0; j < messages.size(); ++j) {
if (a == j) continue; if (a == j) continue;
if (messages.get(j) != null && messages.get(j).getId() == reply_to_id) { if (messages.get(j) != null && messages.get(j).getRealId() == reply_to_id) {
messageObject.replyMessageObject = messages.get(j); messageObject.replyMessageObject = messages.get(j);
messageObject.applyTimestampsHighlightForReplyMsg(); messageObject.applyTimestampsHighlightForReplyMsg();
if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage) { if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage) {
@ -6017,7 +6075,7 @@ public class MediaDataController extends BaseController {
long storyDialogId = DialogObject.getPeerDialogId(messageObject.messageOwner.media.peer); long storyDialogId = DialogObject.getPeerDialogId(messageObject.messageOwner.media.peer);
messageObject.messageOwner.media.storyItem = StoriesStorage.checkExpiredStateLocal(currentAccount, storyDialogId, messageObject.messageOwner.media.storyItem); messageObject.messageOwner.media.storyItem = StoriesStorage.checkExpiredStateLocal(currentAccount, storyDialogId, messageObject.messageOwner.media.storyItem);
} }
} else if (messageObject.getId() > 0 && messageObject.isReplyToStory()) { } else if (messageObject.getRealId() > 0 && messageObject.isReplyToStory()) {
if (messageObject.messageOwner.replyStory == null) { if (messageObject.messageOwner.replyStory == null) {
long storyDialogId = DialogObject.getPeerDialogId(messageObject.messageOwner.reply_to.peer); long storyDialogId = DialogObject.getPeerDialogId(messageObject.messageOwner.reply_to.peer);
if (messagesWithUnknownStories == null) { if (messagesWithUnknownStories == null) {
@ -6033,7 +6091,7 @@ public class MediaDataController extends BaseController {
long storyDialogId = DialogObject.getPeerDialogId(messageObject.messageOwner.reply_to.peer); long storyDialogId = DialogObject.getPeerDialogId(messageObject.messageOwner.reply_to.peer);
messageObject.messageOwner.replyStory = StoriesStorage.checkExpiredStateLocal(currentAccount, storyDialogId, messageObject.messageOwner.replyStory); messageObject.messageOwner.replyStory = StoriesStorage.checkExpiredStateLocal(currentAccount, storyDialogId, messageObject.messageOwner.replyStory);
} }
} else if (messageObject.getId() > 0 && messageObject.isReply()) { } else if (messageObject.getRealId() > 0 && messageObject.isReply()) {
int messageId = messageObject.messageOwner.reply_to.reply_to_msg_id; int messageId = messageObject.messageOwner.reply_to.reply_to_msg_id;
if (messageId == threadMessageId) { if (messageId == threadMessageId) {
continue; continue;
@ -6987,7 +7045,7 @@ public class MediaDataController extends BaseController {
} }
if (spannable instanceof Spannable) { if (spannable instanceof Spannable) {
AndroidUtilities.addLinks((Spannable) spannable, Linkify.WEB_URLS, false, false); AndroidUtilities.addLinksSafe((Spannable) spannable, Linkify.WEB_URLS, false, false);
URLSpan[] spansUrl = spannable.getSpans(0, message[0].length(), URLSpan.class); URLSpan[] spansUrl = spannable.getSpans(0, message[0].length(), URLSpan.class);
if (spansUrl != null && spansUrl.length > 0) { if (spansUrl != null && spansUrl.length > 0) {
if (entities == null) { if (entities == null) {

View file

@ -159,6 +159,7 @@ public class MessageObject {
public String customName; public String customName;
public boolean reactionsChanged; public boolean reactionsChanged;
public boolean isReactionPush; public boolean isReactionPush;
public boolean isStoryReactionPush;
public boolean isStoryPush, isStoryMentionPush, isStoryPushHidden; public boolean isStoryPush, isStoryMentionPush, isStoryPushHidden;
public boolean putInDownloadsStore; public boolean putInDownloadsStore;
public boolean isDownloadingFile; public boolean isDownloadingFile;
@ -199,22 +200,21 @@ public class MessageObject {
public boolean isRestrictedMessage; public boolean isRestrictedMessage;
public long loadedFileSize; public long loadedFileSize;
public boolean forceExpired; public boolean forceExpired;
public long actionDeleteGroupEventId = -1;
public boolean isSpoilersRevealed; public boolean isSpoilersRevealed;
public boolean isMediaSpoilersRevealed; public boolean isMediaSpoilersRevealed;
public boolean isMediaSpoilersRevealedInSharedMedia; public boolean isMediaSpoilersRevealedInSharedMedia;
public boolean revealingMediaSpoilers; public boolean revealingMediaSpoilers;
public byte[] sponsoredId; public byte[] sponsoredId;
public int sponsoredChannelPost; public String sponsoredTitle, sponsoredUrl;
public TLRPC.ChatInvite sponsoredChatInvite;
public String sponsoredChatInviteHash;
public boolean sponsoredShowPeerPhoto;
public boolean sponsoredRecommended; public boolean sponsoredRecommended;
public TLRPC.Photo sponsoredPhoto;
public String sponsoredInfo, sponsoredAdditionalInfo; public String sponsoredInfo, sponsoredAdditionalInfo;
public TLRPC.TL_sponsoredWebPage sponsoredWebPage;
public TLRPC.BotApp sponsoredBotApp;
public String sponsoredButtonText; public String sponsoredButtonText;
public TLRPC.TL_peerColor sponsoredColor;
public boolean sponsoredCanReport; public boolean sponsoredCanReport;
public boolean replyTextEllipsized; public boolean replyTextEllipsized;
public boolean replyTextRevealed; public boolean replyTextRevealed;
public int overrideLinkColor = -1; public int overrideLinkColor = -1;
@ -224,8 +224,6 @@ public class MessageObject {
public TLRPC.TL_forumTopic replyToForumTopic; // used only for reply message in view all messages public TLRPC.TL_forumTopic replyToForumTopic; // used only for reply message in view all messages
public String botStartParam;
public boolean animateComments; public boolean animateComments;
public boolean loadingCancelled; public boolean loadingCancelled;
@ -253,7 +251,7 @@ public class MessageObject {
return 0; return 0;
} }
public ArrayList<TLRPC.TL_pollAnswer> checkedVotes; public ArrayList<TLRPC.PollAnswer> checkedVotes;
public CharSequence editingMessage; public CharSequence editingMessage;
public ArrayList<TLRPC.MessageEntity> editingMessageEntities; public ArrayList<TLRPC.MessageEntity> editingMessageEntities;
@ -601,6 +599,7 @@ public class MessageObject {
public float currentX; public float currentX;
public float currentY; public float currentY;
public float timeAlpha; public float timeAlpha;
public float progress;
} }
public static class VCardData { public static class VCardData {
@ -1941,6 +1940,7 @@ public class MessageObject {
new_participant = action.new_participant; new_participant = action.new_participant;
} }
messageOwner = new TLRPC.TL_message(); messageOwner = new TLRPC.TL_message();
messageOwner.realId = -1;
long peerId = MessageObject.getPeerId(prev_participant.peer); long peerId = MessageObject.getPeerId(prev_participant.peer);
TLObject whoUser; TLObject whoUser;
if (peerId > 0) { if (peerId > 0) {
@ -2008,7 +2008,7 @@ public class MessageObject {
} }
if (o.delete_messages != n.delete_messages) { if (o.delete_messages != n.delete_messages) {
rights.append('\n').append(n.delete_messages ? '+' : '-').append(' '); rights.append('\n').append(n.delete_messages ? '+' : '-').append(' ');
rights.append(LocaleController.getString("EventLogPromotedDeleteMessages", R.string.EventLogPromotedDeleteMessages)); rights.append(LocaleController.getString(R.string.EventLogPromotedDeleteMessages));
} }
if (o.add_admins != n.add_admins) { if (o.add_admins != n.add_admins) {
rights.append('\n').append(n.add_admins ? '+' : '-').append(' '); rights.append('\n').append(n.add_admins ? '+' : '-').append(' ');
@ -2043,6 +2043,7 @@ public class MessageObject {
} else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionDefaultBannedRights) { } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionDefaultBannedRights) {
TLRPC.TL_channelAdminLogEventActionDefaultBannedRights bannedRights = (TLRPC.TL_channelAdminLogEventActionDefaultBannedRights) event.action; TLRPC.TL_channelAdminLogEventActionDefaultBannedRights bannedRights = (TLRPC.TL_channelAdminLogEventActionDefaultBannedRights) event.action;
messageOwner = new TLRPC.TL_message(); messageOwner = new TLRPC.TL_message();
messageOwner.realId = -1;
TLRPC.TL_chatBannedRights o = bannedRights.prev_banned_rights; TLRPC.TL_chatBannedRights o = bannedRights.prev_banned_rights;
TLRPC.TL_chatBannedRights n = bannedRights.new_banned_rights; TLRPC.TL_chatBannedRights n = bannedRights.new_banned_rights;
@ -2120,6 +2121,7 @@ public class MessageObject {
} else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantToggleBan) { } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantToggleBan) {
TLRPC.TL_channelAdminLogEventActionParticipantToggleBan action = (TLRPC.TL_channelAdminLogEventActionParticipantToggleBan) event.action; TLRPC.TL_channelAdminLogEventActionParticipantToggleBan action = (TLRPC.TL_channelAdminLogEventActionParticipantToggleBan) event.action;
messageOwner = new TLRPC.TL_message(); messageOwner = new TLRPC.TL_message();
messageOwner.realId = -1;
long peerId = getPeerId(action.prev_participant.peer); long peerId = getPeerId(action.prev_participant.peer);
TLObject whoUser; TLObject whoUser;
if (peerId > 0) { if (peerId > 0) {
@ -2306,9 +2308,9 @@ public class MessageObject {
} else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionDeleteMessage) { } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionDeleteMessage) {
message = ((TLRPC.TL_channelAdminLogEventActionDeleteMessage) event.action).message; message = ((TLRPC.TL_channelAdminLogEventActionDeleteMessage) event.action).message;
if (fromUser != null && fromUser.id == MessagesController.getInstance(currentAccount).telegramAntispamUserId) { if (fromUser != null && fromUser.id == MessagesController.getInstance(currentAccount).telegramAntispamUserId) {
messageText = LocaleController.getString("EventLogDeletedMessages", R.string.EventLogDeletedMessages).replace("un1", UserObject.getUserName(fromUser)); messageText = LocaleController.getString(R.string.EventLogDeletedMessages).replace("un1", UserObject.getUserName(fromUser));
} else { } else {
messageText = replaceWithLink(LocaleController.getString("EventLogDeletedMessages", R.string.EventLogDeletedMessages), "un1", fromUser); messageText = replaceWithLink(LocaleController.getString(R.string.EventLogDeletedMessages), "un1", fromUser);
} }
} else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) { } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) {
long newChatId = ((TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) event.action).new_value; long newChatId = ((TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) event.action).new_value;
@ -2990,9 +2992,8 @@ public class MessageObject {
message.out = false; message.out = false;
message.realId = message.id; message.realId = message.id;
message.id = mid[0]++; message.id = mid[0]++;
message.flags &= ~TLRPC.MESSAGE_FLAG_REPLY;
message.reply_to = null;
message.flags = message.flags & ~TLRPC.MESSAGE_FLAG_EDITED; message.flags = message.flags & ~TLRPC.MESSAGE_FLAG_EDITED;
message.dialog_id = -chat.id;
MessageObject messageObject = new MessageObject(currentAccount, message, null, null, true, true, eventId); MessageObject messageObject = new MessageObject(currentAccount, message, null, null, true, true, eventId);
messageObject.currentEvent = event; messageObject.currentEvent = event;
if (messageObject.contentType >= 0) { if (messageObject.contentType >= 0) {
@ -3016,6 +3017,9 @@ public class MessageObject {
messageObject.generateLinkDescription(); messageObject.generateLinkDescription();
} }
} }
if (event.action instanceof TLRPC.TL_channelAdminLogEventActionDeleteMessage) {
return;
}
if (contentType >= 0) { if (contentType >= 0) {
createDateArray(currentAccount, event, messageObjects, messagesByDays, addToEnd); createDateArray(currentAccount, event, messageObjects, messagesByDays, addToEnd);
if (addToEnd) { if (addToEnd) {
@ -5330,13 +5334,13 @@ public class MessageObject {
} }
} }
} }
} else if (sponsoredWebPage != null && sponsoredWebPage.photo != null) { } else if (sponsoredPhoto != null) {
if (!update || photoThumbs == null) { if (!update || photoThumbs == null) {
photoThumbs = new ArrayList<>(sponsoredWebPage.photo.sizes); photoThumbs = new ArrayList<>(sponsoredPhoto.sizes);
} else if (!photoThumbs.isEmpty()) { } else if (!photoThumbs.isEmpty()) {
updatePhotoSizeLocations(photoThumbs, sponsoredWebPage.photo.sizes); updatePhotoSizeLocations(photoThumbs, sponsoredPhoto.sizes);
} }
photoThumbsObject = sponsoredWebPage.photo; photoThumbsObject = sponsoredPhoto;
if (strippedThumb == null) { if (strippedThumb == null) {
createStrippedThumb(); createStrippedThumb();
} }
@ -5587,7 +5591,7 @@ public class MessageObject {
if (!TextUtils.isEmpty(linkDescription)) { if (!TextUtils.isEmpty(linkDescription)) {
if (containsUrls(linkDescription)) { if (containsUrls(linkDescription)) {
try { try {
AndroidUtilities.addLinks((Spannable) linkDescription, Linkify.WEB_URLS); AndroidUtilities.addLinksSafe((Spannable) linkDescription, Linkify.WEB_URLS, false, true);
} catch (Exception e) { } catch (Exception e) {
FileLog.e(e); FileLog.e(e);
} }
@ -5708,7 +5712,7 @@ public class MessageObject {
if (useManualParse) { if (useManualParse) {
if (containsUrls(caption)) { if (containsUrls(caption)) {
try { try {
AndroidUtilities.addLinks((Spannable) caption, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS); AndroidUtilities.addLinksSafe((Spannable) caption, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS, false, true);
} catch (Exception e) { } catch (Exception e) {
FileLog.e(e); FileLog.e(e);
} }
@ -5920,13 +5924,13 @@ public class MessageObject {
if (messageText instanceof Spannable && containsUrls(messageText)) { if (messageText instanceof Spannable && containsUrls(messageText)) {
if (messageText.length() < 1000) { if (messageText.length() < 1000) {
try { try {
AndroidUtilities.addLinks((Spannable) messageText, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS, internalOnly); AndroidUtilities.addLinksSafe((Spannable) messageText, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS, internalOnly, false);
} catch (Exception e) { } catch (Exception e) {
FileLog.e(e); FileLog.e(e);
} }
} else { } else {
try { try {
AndroidUtilities.addLinks((Spannable) messageText, Linkify.WEB_URLS, internalOnly); AndroidUtilities.addLinksSafe((Spannable) messageText, Linkify.WEB_URLS, internalOnly, false);
} catch (Exception e) { } catch (Exception e) {
FileLog.e(e); FileLog.e(e);
} }
@ -8291,6 +8295,39 @@ public class MessageObject {
return fallback; return fallback;
} }
public static ArrayList<String> findStickerEmoticons(TLRPC.Document document, Integer currentAccountForFull) {
if (document == null) {
return null;
}
ArrayList<String> emojis = new ArrayList<>();
for (int a = 0, N = document.attributes.size(); a < N; a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeCustomEmoji ||
attribute instanceof TLRPC.TL_documentAttributeSticker) {
if (currentAccountForFull != null) {
TLRPC.TL_messages_stickerSet set = MediaDataController.getInstance(currentAccountForFull).getStickerSet(attribute.stickerset, true);
if (set != null && set.packs != null) {
for (int p = 0; p < set.packs.size(); ++p) {
TLRPC.TL_stickerPack pack = set.packs.get(p);
if (pack.documents.contains(document.id) && Emoji.getEmojiDrawable(pack.emoticon) != null) {
emojis.add(pack.emoticon);
}
}
}
if (!emojis.isEmpty()) {
return emojis;
}
}
if (!TextUtils.isEmpty(attribute.alt) && Emoji.getEmojiDrawable(attribute.alt) != null) {
emojis.add(attribute.alt);
return emojis;
}
}
}
return null;
}
public static boolean isAnimatedEmoji(TLRPC.Document document) { public static boolean isAnimatedEmoji(TLRPC.Document document) {
if (document == null) { if (document == null) {
return false; return false;
@ -9650,7 +9687,12 @@ public class MessageObject {
} }
} }
} }
if (newReaction == null) { if (newReaction == null) {
int maxChatReactions = MessagesController.getInstance(currentAccount).getChatMaxUniqReactions(getDialogId());
if (messageOwner.reactions.results.size() + 1 > maxChatReactions) {
return false;
}
newReaction = new TLRPC.TL_reactionCount(); newReaction = new TLRPC.TL_reactionCount();
newReaction.reaction = visibleReaction.toTLReaction(); newReaction.reaction = visibleReaction.toTLReaction();
messageOwner.reactions.results.add(newReaction); messageOwner.reactions.results.add(newReaction);
@ -9932,7 +9974,7 @@ public class MessageObject {
return hasLinkPreview && !isGiveawayOrGiveawayResults() && return hasLinkPreview && !isGiveawayOrGiveawayResults() &&
webpage != null && (webpage.photo != null || isVideoDocument(webpage.document)) && webpage != null && (webpage.photo != null || isVideoDocument(webpage.document)) &&
!(webpage != null && TextUtils.isEmpty(webpage.description) && TextUtils.isEmpty(webpage.title)) && !(webpage != null && TextUtils.isEmpty(webpage.description) && TextUtils.isEmpty(webpage.title)) &&
!(isSponsored() && sponsoredWebPage == null && sponsoredChannelPost == 0) && // drawInstantViewType = 1 !isSponsored() && // drawInstantViewType = 1
!"telegram_megagroup".equals(webpageType) && // drawInstantViewType = 2 !"telegram_megagroup".equals(webpageType) && // drawInstantViewType = 2
!"telegram_background".equals(webpageType) && // drawInstantViewType = 6 !"telegram_background".equals(webpageType) && // drawInstantViewType = 6
!"telegram_voicechat".equals(webpageType) && // drawInstantViewType = 9 !"telegram_voicechat".equals(webpageType) && // drawInstantViewType = 9

View file

@ -348,7 +348,7 @@ public class MessagePreviewParams {
try { try {
Spannable spanned = SpannableString.valueOf(text); Spannable spanned = SpannableString.valueOf(text);
try { try {
AndroidUtilities.addLinks(spanned, Linkify.WEB_URLS); AndroidUtilities.addLinksSafe(spanned, Linkify.WEB_URLS, false, true);
} catch (Exception e2) { } catch (Exception e2) {
FileLog.e(e2); FileLog.e(e2);
} }

View file

@ -10,6 +10,7 @@ package org.telegram.messenger;
import static org.telegram.messenger.NotificationsController.TYPE_CHANNEL; import static org.telegram.messenger.NotificationsController.TYPE_CHANNEL;
import static org.telegram.messenger.NotificationsController.TYPE_PRIVATE; import static org.telegram.messenger.NotificationsController.TYPE_PRIVATE;
import static org.telegram.messenger.NotificationsController.TYPE_REACTIONS_MESSAGES;
import android.Manifest; import android.Manifest;
import android.app.Activity; import android.app.Activity;
@ -61,6 +62,7 @@ import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Business.QuickRepliesController; import org.telegram.ui.Business.QuickRepliesController;
import org.telegram.ui.ChannelMonetizationLayout;
import org.telegram.ui.ChatActivity; import org.telegram.ui.ChatActivity;
import org.telegram.ui.ChatReactionsEditActivity; import org.telegram.ui.ChatReactionsEditActivity;
import org.telegram.ui.ChatRightsEditActivity; import org.telegram.ui.ChatRightsEditActivity;
@ -70,13 +72,17 @@ import org.telegram.ui.Components.BulletinFactory;
import org.telegram.ui.Components.ImageUpdater; import org.telegram.ui.Components.ImageUpdater;
import org.telegram.ui.Components.JoinCallAlert; import org.telegram.ui.Components.JoinCallAlert;
import org.telegram.ui.Components.MotionBackgroundDrawable; import org.telegram.ui.Components.MotionBackgroundDrawable;
import org.telegram.ui.Components.Premium.GiftPremiumBottomSheet;
import org.telegram.ui.Components.Premium.LimitReachedBottomSheet; import org.telegram.ui.Components.Premium.LimitReachedBottomSheet;
import org.telegram.ui.Components.Premium.boosts.BoostRepository;
import org.telegram.ui.Components.Premium.boosts.PremiumPreviewGiftToUsersBottomSheet;
import org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble; import org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble;
import org.telegram.ui.Components.SwipeGestureSettingsView; import org.telegram.ui.Components.SwipeGestureSettingsView;
import org.telegram.ui.Components.TranscribeButton; import org.telegram.ui.Components.TranscribeButton;
import org.telegram.ui.DialogsActivity; import org.telegram.ui.DialogsActivity;
import org.telegram.ui.EditWidgetActivity; import org.telegram.ui.EditWidgetActivity;
import org.telegram.ui.LaunchActivity; import org.telegram.ui.LaunchActivity;
import org.telegram.ui.NotificationsSettingsActivity;
import org.telegram.ui.PremiumPreviewFragment; import org.telegram.ui.PremiumPreviewFragment;
import org.telegram.ui.ProfileActivity; import org.telegram.ui.ProfileActivity;
import org.telegram.ui.SecretMediaViewer; import org.telegram.ui.SecretMediaViewer;
@ -507,6 +513,7 @@ public class MessagesController extends BaseController implements NotificationCe
public boolean saveGifsWithStickers; public boolean saveGifsWithStickers;
private String installReferer; private String installReferer;
public Set<String> pendingSuggestions; public Set<String> pendingSuggestions;
public Set<String> dismissedSuggestions;
public Set<String> exportUri; public Set<String> exportUri;
public Set<String> exportGroupUri; public Set<String> exportGroupUri;
public Set<String> exportPrivateUri; public Set<String> exportPrivateUri;
@ -599,6 +606,11 @@ public class MessagesController extends BaseController implements NotificationCe
public int businessChatLinksLimit; public int businessChatLinksLimit;
public boolean channelRevenueWithdrawalEnabled; public boolean channelRevenueWithdrawalEnabled;
public boolean newNoncontactPeersRequirePremiumWithoutOwnpremium; public boolean newNoncontactPeersRequirePremiumWithoutOwnpremium;
public int reactionsUniqMax;
public String premiumManageSubscriptionUrl;
public boolean androidDisableRoundCamera2;
public int storiesPinnedToTopCountMax;
public boolean showAnnualPerMonth = false;
public int savedDialogsPinnedLimitDefault; public int savedDialogsPinnedLimitDefault;
public int savedDialogsPinnedLimitPremium; public int savedDialogsPinnedLimitPremium;
@ -762,6 +774,14 @@ public class MessagesController extends BaseController implements NotificationCe
return getUserConfig().isPremium() ? reactionsInChatMax : 1; return getUserConfig().isPremium() ? reactionsInChatMax : 1;
} }
public int getChatMaxUniqReactions(long dialogId) {
TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(-dialogId);
if (chatFull != null && (chatFull instanceof TLRPC.TL_chatFull ? (chatFull.flags & 1048576) != 0 : (chatFull.flags2 & 8192) != 0)) {
return chatFull.reactions_limit;
}
return reactionsUniqMax;
}
public boolean isPremiumUser(TLRPC.User currentUser) { public boolean isPremiumUser(TLRPC.User currentUser) {
return !premiumFeaturesBlocked() && currentUser.premium; return !premiumFeaturesBlocked() && currentUser.premium;
} }
@ -1409,6 +1429,7 @@ public class MessagesController extends BaseController implements NotificationCe
roundVideoBitrate = mainPreferences.getInt("roundVideoBitrate", 1000); roundVideoBitrate = mainPreferences.getInt("roundVideoBitrate", 1000);
roundAudioBitrate = mainPreferences.getInt("roundAudioBitrate", 64); roundAudioBitrate = mainPreferences.getInt("roundAudioBitrate", 64);
pendingSuggestions = mainPreferences.getStringSet("pendingSuggestions", null); pendingSuggestions = mainPreferences.getStringSet("pendingSuggestions", null);
dismissedSuggestions = mainPreferences.getStringSet("dismissedSuggestions", null);
channelsLimitDefault = mainPreferences.getInt("channelsLimitDefault", 500); channelsLimitDefault = mainPreferences.getInt("channelsLimitDefault", 500);
channelsLimitPremium = mainPreferences.getInt("channelsLimitPremium", 2 * channelsLimitDefault); channelsLimitPremium = mainPreferences.getInt("channelsLimitPremium", 2 * channelsLimitDefault);
savedGifsLimitDefault = mainPreferences.getInt("savedGifsLimitDefault", 200); savedGifsLimitDefault = mainPreferences.getInt("savedGifsLimitDefault", 200);
@ -1518,6 +1539,11 @@ public class MessagesController extends BaseController implements NotificationCe
businessChatLinksLimit = mainPreferences.getInt("businessChatLinksLimit", 100); businessChatLinksLimit = mainPreferences.getInt("businessChatLinksLimit", 100);
channelRevenueWithdrawalEnabled = mainPreferences.getBoolean("channelRevenueWithdrawalEnabled", false); channelRevenueWithdrawalEnabled = mainPreferences.getBoolean("channelRevenueWithdrawalEnabled", false);
newNoncontactPeersRequirePremiumWithoutOwnpremium = mainPreferences.getBoolean("newNoncontactPeersRequirePremiumWithoutOwnpremium", false); newNoncontactPeersRequirePremiumWithoutOwnpremium = mainPreferences.getBoolean("newNoncontactPeersRequirePremiumWithoutOwnpremium", false);
reactionsUniqMax = mainPreferences.getInt("reactionsUniqMax", 11);
premiumManageSubscriptionUrl = mainPreferences.getString("premiumManageSubscriptionUrl", ApplicationLoader.isStandaloneBuild() ? "https://t.me/premiumbot?start=status" : "https://play.google.com/store/account/subscriptions?sku=telegram_premium&package=org.telegram.messenger");
androidDisableRoundCamera2 = mainPreferences.getBoolean("androidDisableRoundCamera2", false);
storiesPinnedToTopCountMax = mainPreferences.getInt("storiesPinnedToTopCountMax", 3);
showAnnualPerMonth = mainPreferences.getBoolean("showAnnualPerMonth", false);
scheduleTranscriptionUpdate(); scheduleTranscriptionUpdate();
BuildVars.GOOGLE_AUTH_CLIENT_ID = mainPreferences.getString("googleAuthClientId", BuildVars.GOOGLE_AUTH_CLIENT_ID); BuildVars.GOOGLE_AUTH_CLIENT_ID = mainPreferences.getString("googleAuthClientId", BuildVars.GOOGLE_AUTH_CLIENT_ID);
if (mainPreferences.contains("dcDomainName2")) { if (mainPreferences.contains("dcDomainName2")) {
@ -1544,6 +1570,11 @@ public class MessagesController extends BaseController implements NotificationCe
} else { } else {
pendingSuggestions = new HashSet<>(); pendingSuggestions = new HashSet<>();
} }
if (dismissedSuggestions != null) {
dismissedSuggestions = new HashSet<>(dismissedSuggestions);
} else {
dismissedSuggestions = new HashSet<>();
}
exportUri = mainPreferences.getStringSet("exportUri2", null); exportUri = mainPreferences.getStringSet("exportUri2", null);
if (exportUri != null) { if (exportUri != null) {
@ -2284,11 +2315,14 @@ public class MessagesController extends BaseController implements NotificationCe
getNotificationCenter().postNotificationName(NotificationCenter.dialogFiltersUpdated); getNotificationCenter().postNotificationName(NotificationCenter.dialogFiltersUpdated);
} }
private Runnable loadAppConfigRunnable = this::loadAppConfig;
public void loadAppConfig() { public void loadAppConfig() {
loadAppConfig(false); loadAppConfig(false);
} }
public void loadAppConfig(boolean force) { public void loadAppConfig(boolean force) {
AndroidUtilities.cancelRunOnUIThread(loadAppConfigRunnable);
if (force) { if (force) {
appConfigFetcher.forceRequest(currentAccount, 0); appConfigFetcher.forceRequest(currentAccount, 0);
} }
@ -2296,6 +2330,8 @@ public class MessagesController extends BaseController implements NotificationCe
if (config != null && config.config instanceof TLRPC.TL_jsonObject) { if (config != null && config.config instanceof TLRPC.TL_jsonObject) {
applyAppConfig((TLRPC.TL_jsonObject) config.config); applyAppConfig((TLRPC.TL_jsonObject) config.config);
} }
AndroidUtilities.cancelRunOnUIThread(loadAppConfigRunnable);
AndroidUtilities.runOnUIThread(loadAppConfigRunnable, 4 * 60 * 1000 + 10);
})); }));
} }
@ -2982,6 +3018,26 @@ public class MessagesController extends BaseController implements NotificationCe
} }
break; break;
} }
case "dismissed_suggestions": {
HashSet<String> newSuggestions = new HashSet<>();
if (value.value instanceof TLRPC.TL_jsonArray) {
TLRPC.TL_jsonArray array = (TLRPC.TL_jsonArray) value.value;
for (int b = 0, N2 = array.value.size(); b < N2; b++) {
TLRPC.JSONValue val = array.value.get(b);
if (val instanceof TLRPC.TL_jsonString) {
TLRPC.TL_jsonString string = (TLRPC.TL_jsonString) val;
newSuggestions.add(string.value);
}
}
}
if (!dismissedSuggestions.equals(newSuggestions)) {
dismissedSuggestions = newSuggestions;
editor.putStringSet("dismissedSuggestions", dismissedSuggestions);
getNotificationCenter().postNotificationName(NotificationCenter.newSuggestionsAvailable);
changed = true;
}
break;
}
case "emojies_sounds": { case "emojies_sounds": {
try { try {
HashMap<String, EmojiSound> newEmojies = new HashMap<>(); HashMap<String, EmojiSound> newEmojies = new HashMap<>();
@ -3974,6 +4030,61 @@ public class MessagesController extends BaseController implements NotificationCe
} }
break; break;
} }
case "reactions_uniq_max": {
if (value.value instanceof TLRPC.TL_jsonBool) {
TLRPC.TL_jsonNumber num = (TLRPC.TL_jsonNumber) value.value;
if (num.value != reactionsUniqMax) {
reactionsUniqMax = (int) num.value;
editor.putInt("reactionsUniqMax", reactionsUniqMax);
changed = true;
}
}
break;
}
case "premium_manage_subscription_url": {
if (value.value instanceof TLRPC.TL_jsonString) {
TLRPC.TL_jsonString str = (TLRPC.TL_jsonString) value.value;
if (!TextUtils.equals(str.value, premiumManageSubscriptionUrl)) {
premiumManageSubscriptionUrl = str.value;
editor.putString("premiumManageSubscriptionUrl", premiumManageSubscriptionUrl);
changed = true;
}
}
break;
}
case "android_disable_round_camera2": {
if (value.value instanceof TLRPC.TL_jsonBool) {
TLRPC.TL_jsonBool bool = (TLRPC.TL_jsonBool) value.value;
if (bool.value != androidDisableRoundCamera2) {
androidDisableRoundCamera2 = bool.value;
editor.putBoolean("androidDisableRoundCamera2", androidDisableRoundCamera2);
changed = true;
}
}
break;
}
case "stories_pinned_to_top_count_max": {
if (value.value instanceof TLRPC.TL_jsonNumber) {
TLRPC.TL_jsonNumber num = (TLRPC.TL_jsonNumber) value.value;
if (num.value != storiesPinnedToTopCountMax) {
storiesPinnedToTopCountMax = (int) num.value;
editor.putInt("storiesPinnedToTopCountMax", storiesPinnedToTopCountMax);
changed = true;
}
}
break;
}
case "show_annual_per_month": {
if (value.value instanceof TLRPC.TL_jsonBool) {
TLRPC.TL_jsonBool bool = (TLRPC.TL_jsonBool) value.value;
if (bool.value != showAnnualPerMonth) {
showAnnualPerMonth = bool.value;
editor.putBoolean("showAnnualPerMonth", showAnnualPerMonth);
changed = true;
}
}
break;
}
} }
} }
@ -4505,7 +4616,8 @@ public class MessagesController extends BaseController implements NotificationCe
channelRevenueWithdrawalEnabled = false; channelRevenueWithdrawalEnabled = false;
collectDeviceStats = false; collectDeviceStats = false;
smsjobsStickyNotificationEnabled = false; smsjobsStickyNotificationEnabled = false;
mainPreferences.edit().remove("getfileExperimentalParams").remove("smsjobsStickyNotificationEnabled").remove("channelRevenueWithdrawalEnabled").apply(); showAnnualPerMonth = false;
mainPreferences.edit().remove("getfileExperimentalParams").remove("smsjobsStickyNotificationEnabled").remove("channelRevenueWithdrawalEnabled").remove("showAnnualPerMonth").apply();
} }
private boolean savePremiumFeaturesPreviewOrder(String key, SparseIntArray array, SharedPreferences.Editor editor, ArrayList<TLRPC.JSONValue> value) { private boolean savePremiumFeaturesPreviewOrder(String key, SparseIntArray array, SharedPreferences.Editor editor, ArrayList<TLRPC.JSONValue> value) {
@ -4556,9 +4668,11 @@ public class MessagesController extends BaseController implements NotificationCe
return; return;
} }
if (did == 0) { if (did == 0) {
if (pendingSuggestions.remove(suggestion)) { if (pendingSuggestions.remove(suggestion) || !dismissedSuggestions.contains(suggestion)) {
dismissedSuggestions.add(suggestion);
SharedPreferences.Editor editor = mainPreferences.edit(); SharedPreferences.Editor editor = mainPreferences.edit();
editor.putStringSet("pendingSuggestions", pendingSuggestions); editor.putStringSet("pendingSuggestions", pendingSuggestions);
editor.putStringSet("dismissedSuggestions", dismissedSuggestions);
editor.commit(); editor.commit();
getNotificationCenter().postNotificationName(NotificationCenter.newSuggestionsAvailable); getNotificationCenter().postNotificationName(NotificationCenter.newSuggestionsAvailable);
} else { } else {
@ -4823,7 +4937,9 @@ public class MessagesController extends BaseController implements NotificationCe
public TLRPC.InputPeer getInputPeer(long id) { public TLRPC.InputPeer getInputPeer(long id) {
TLRPC.InputPeer inputPeer; TLRPC.InputPeer inputPeer;
if (id < 0) { if (id == getUserConfig().getClientUserId()) {
inputPeer = new TLRPC.TL_inputPeerSelf();
} else if (id < 0) {
TLRPC.Chat chat = getChat(-id); TLRPC.Chat chat = getChat(-id);
if (ChatObject.isChannel(chat)) { if (ChatObject.isChannel(chat)) {
inputPeer = new TLRPC.TL_inputPeerChannel(); inputPeer = new TLRPC.TL_inputPeerChannel();
@ -4864,6 +4980,16 @@ public class MessagesController extends BaseController implements NotificationCe
return inputPeer; return inputPeer;
} }
public static TLRPC.InputPeer getInputPeer(TLObject userOrChat) {
if (userOrChat instanceof TLRPC.User) {
return getInputPeer((TLRPC.User) userOrChat);
} else if (userOrChat instanceof TLRPC.Chat) {
return getInputPeer((TLRPC.Chat) userOrChat);
} else {
return null;
}
}
public TLRPC.Peer getPeer(long id) { public TLRPC.Peer getPeer(long id) {
TLRPC.Peer inputPeer; TLRPC.Peer inputPeer;
if (id < 0) { if (id < 0) {
@ -7294,6 +7420,10 @@ public class MessagesController extends BaseController implements NotificationCe
} }
public void setParticipantBannedRole(long chatId, TLRPC.User user, TLRPC.Chat chat, TLRPC.TL_chatBannedRights rights, boolean isChannel, BaseFragment parentFragment) { public void setParticipantBannedRole(long chatId, TLRPC.User user, TLRPC.Chat chat, TLRPC.TL_chatBannedRights rights, boolean isChannel, BaseFragment parentFragment) {
setParticipantBannedRole(chatId, user, chat, rights, isChannel, parentFragment, null);
}
public void setParticipantBannedRole(long chatId, TLRPC.User user, TLRPC.Chat chat, TLRPC.TL_chatBannedRights rights, boolean isChannel, BaseFragment parentFragment, Runnable whenDone) {
if (user == null && chat == null || rights == null) { if (user == null && chat == null || rights == null) {
return; return;
} }
@ -7309,6 +7439,9 @@ public class MessagesController extends BaseController implements NotificationCe
if (error == null) { if (error == null) {
processUpdates((TLRPC.Updates) response, false); processUpdates((TLRPC.Updates) response, false);
AndroidUtilities.runOnUIThread(() -> loadFullChat(chatId, 0, true), 1000); AndroidUtilities.runOnUIThread(() -> loadFullChat(chatId, 0, true), 1000);
if (whenDone != null) {
AndroidUtilities.runOnUIThread(whenDone);
}
} else { } else {
AndroidUtilities.runOnUIThread(() -> AlertsCreator.processError(currentAccount, error, parentFragment, req, isChannel)); AndroidUtilities.runOnUIThread(() -> AlertsCreator.processError(currentAccount, error, parentFragment, req, isChannel));
} }
@ -10694,7 +10827,7 @@ public class MessagesController extends BaseController implements NotificationCe
editor1.commit(); editor1.commit();
} }
loadingNotificationSettings = 3; loadingNotificationSettings = 4;
for (int a = 0; a < 3; a++) { for (int a = 0; a < 3; a++) {
TLRPC.TL_account_getNotifySettings req = new TLRPC.TL_account_getNotifySettings(); TLRPC.TL_account_getNotifySettings req = new TLRPC.TL_account_getNotifySettings();
if (a == 0) { if (a == 0) {
@ -10763,7 +10896,7 @@ public class MessagesController extends BaseController implements NotificationCe
} }
} }
getNotificationsController().getNotificationsSettingsFacade().applySoundSettings(notify_settings.android_sound, editor, 0, 0, type, false); getNotificationsController().getNotificationsSettingsFacade().applySoundSettings(notify_settings.android_sound, editor, 0, 0, type, false);
editor.commit(); editor.apply();
if (loadingNotificationSettings == 0) { if (loadingNotificationSettings == 0) {
getUserConfig().notificationsSettingsLoaded = true; getUserConfig().notificationsSettingsLoaded = true;
getUserConfig().saveConfig(false); getUserConfig().saveConfig(false);
@ -10771,12 +10904,57 @@ public class MessagesController extends BaseController implements NotificationCe
} }
})); }));
} }
getConnectionsManager().sendRequest(new TLRPC.TL_account_getReactionsNotifySettings(), (res, err) -> AndroidUtilities.runOnUIThread(() -> {
loadingNotificationSettings--;
if (res instanceof TLRPC.TL_reactionsNotifySettings) {
TLRPC.TL_reactionsNotifySettings notify_settings = (TLRPC.TL_reactionsNotifySettings) res;
SharedPreferences.Editor editor = notificationsPreferences.edit();
editor.putBoolean("EnableReactionsMessages", notify_settings.messages_notify_from != null);
if (notify_settings.messages_notify_from != null) {
editor.putBoolean("EnableReactionsMessagesContacts", notify_settings.messages_notify_from instanceof TLRPC.TL_reactionNotificationsFromContacts);
}
editor.putBoolean("EnableReactionsStories", notify_settings.stories_notify_from != null);
if (notify_settings.stories_notify_from != null) {
editor.putBoolean("EnableReactionsStoriesContacts", notify_settings.stories_notify_from instanceof TLRPC.TL_reactionNotificationsFromContacts);
}
editor.putBoolean("EnableReactionsPreview", notify_settings.show_previews);
getNotificationsController().getNotificationsSettingsFacade().applySoundSettings(notify_settings.sound, editor, 0, 0, TYPE_REACTIONS_MESSAGES, false);
editor.apply();
}
if (loadingNotificationSettings == 0) {
getUserConfig().notificationsSettingsLoaded = true;
getUserConfig().saveConfig(false);
}
}));
} }
if (!getUserConfig().notificationsSignUpSettingsLoaded) { if (!getUserConfig().notificationsSignUpSettingsLoaded) {
loadSignUpNotificationsSettings(); loadSignUpNotificationsSettings();
} }
} }
public void reloadReactionsNotifySettings() {
getConnectionsManager().sendRequest(new TLRPC.TL_account_getReactionsNotifySettings(), (res, err) -> AndroidUtilities.runOnUIThread(() -> {
if (res instanceof TLRPC.TL_reactionsNotifySettings) {
TLRPC.TL_reactionsNotifySettings notify_settings = (TLRPC.TL_reactionsNotifySettings) res;
SharedPreferences.Editor editor = notificationsPreferences.edit();
editor.putBoolean("EnableReactionsMessages", notify_settings.messages_notify_from != null);
if (notify_settings.messages_notify_from != null) {
editor.putBoolean("EnableReactionsMessagesContacts", notify_settings.messages_notify_from instanceof TLRPC.TL_reactionNotificationsFromContacts);
}
editor.putBoolean("EnableReactionsStories", notify_settings.stories_notify_from != null);
if (notify_settings.stories_notify_from != null) {
editor.putBoolean("EnableReactionsStoriesContacts", notify_settings.stories_notify_from instanceof TLRPC.TL_reactionNotificationsFromContacts);
}
editor.putBoolean("EnableReactionsPreview", notify_settings.show_previews);
getNotificationsController().getNotificationsSettingsFacade().applySoundSettings(notify_settings.sound, editor, 0, 0, TYPE_REACTIONS_MESSAGES, false);
editor.apply();
getNotificationCenter().postNotificationName(NotificationCenter.notificationsSettingsUpdated);
}
}));
}
public void loadSignUpNotificationsSettings() { public void loadSignUpNotificationsSettings() {
if (!loadingNotificationSignUpSettings) { if (!loadingNotificationSignUpSettings) {
loadingNotificationSignUpSettings = true; loadingNotificationSignUpSettings = true;
@ -13581,6 +13759,10 @@ public class MessagesController extends BaseController implements NotificationCe
} }
public void deleteParticipantFromChat(long chatId, TLRPC.InputPeer peer, boolean forceDelete, boolean revoke) { public void deleteParticipantFromChat(long chatId, TLRPC.InputPeer peer, boolean forceDelete, boolean revoke) {
deleteParticipantFromChat(chatId, peer, forceDelete, revoke, null);
}
public void deleteParticipantFromChat(long chatId, TLRPC.InputPeer peer, boolean forceDelete, boolean revoke, Runnable whenDone) {
if (peer == null) { if (peer == null) {
return; return;
} }
@ -13623,7 +13805,6 @@ public class MessagesController extends BaseController implements NotificationCe
TLRPC.TL_messages_deleteChat req = new TLRPC.TL_messages_deleteChat(); TLRPC.TL_messages_deleteChat req = new TLRPC.TL_messages_deleteChat();
req.chat_id = chatId; req.chat_id = chatId;
getConnectionsManager().sendRequest(req, (response, error) -> { getConnectionsManager().sendRequest(req, (response, error) -> {
}); });
return; return;
} }
@ -13645,6 +13826,9 @@ public class MessagesController extends BaseController implements NotificationCe
if (isChannel && !self) { if (isChannel && !self) {
AndroidUtilities.runOnUIThread(() -> loadFullChat(chatId, 0, true), 1000); AndroidUtilities.runOnUIThread(() -> loadFullChat(chatId, 0, true), 1000);
} }
if (whenDone != null) {
AndroidUtilities.runOnUIThread(whenDone);
}
}, ConnectionsManager.RequestFlagInvokeAfter); }, ConnectionsManager.RequestFlagInvokeAfter);
} }
@ -14431,6 +14615,7 @@ public class MessagesController extends BaseController implements NotificationCe
long[] ids = corrected.valueAt(a); long[] ids = corrected.valueAt(a);
getSendMessagesHelper().processSentMessage((int) ids[1]); getSendMessagesHelper().processSentMessage((int) ids[1]);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, (int) ids[1], newId, null, ids[0], 0L, -1, false); getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, (int) ids[1], newId, null, ids[0], 0L, -1, false);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer2, (int) ids[1], newId, null, ids[0], 0L, -1, false);
} }
}); });
} }
@ -14687,6 +14872,7 @@ public class MessagesController extends BaseController implements NotificationCe
long[] ids = corrected.valueAt(a); long[] ids = corrected.valueAt(a);
getSendMessagesHelper().processSentMessage((int) ids[1]); getSendMessagesHelper().processSentMessage((int) ids[1]);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, (int) ids[1], newId, null, ids[0], 0L, -1, false); getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, (int) ids[1], newId, null, ids[0], 0L, -1, false);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer2, (int) ids[1], newId, null, ids[0], 0L, -1, false);
} }
}); });
} }
@ -17486,6 +17672,41 @@ public class MessagesController extends BaseController implements NotificationCe
if (UserObject.isUserSelf(currentUser)) { if (UserObject.isUserSelf(currentUser)) {
getNotificationCenter().postNotificationName(NotificationCenter.mainUserInfoChanged); getNotificationCenter().postNotificationName(NotificationCenter.mainUserInfoChanged);
} }
} else if (baseUpdate instanceof TLRPC.TL_updateNewStoryReaction) {
TLRPC.TL_updateNewStoryReaction update = (TLRPC.TL_updateNewStoryReaction) baseUpdate;
long dialogId = DialogObject.getPeerDialogId(update.peer);
int story_id = update.story_id;
TLRPC.Message msg = new TLRPC.Message();
msg.id = -story_id;
msg.dialog_id = dialogId;
msg.peer_id = getPeer(dialogId);
msg.date = getConnectionsManager().getCurrentTime();
TLRPC.User user = getMessagesController().getUser(msg.dialog_id);
if (user != null && getNotificationsSettings(currentAccount).getBoolean("EnableReactionsPreview", true)) {
ReactionsLayoutInBubble.VisibleReaction reaction = ReactionsLayoutInBubble.VisibleReaction.fromTLReaction(update.reaction).flatten();
if (reaction.emojicon != null) {
msg.message = LocaleController.formatString(R.string.PushReactStory, UserObject.getFirstName(user), reaction.emojicon);
} else {
msg.message = LocaleController.formatString(R.string.PushReactStoryHidden);
}
} else {
msg.message = LocaleController.formatString(R.string.PushReactStoryHidden);
}
ArrayList<MessageObject> messageObjects = new ArrayList<MessageObject>();
MessageObject message = new MessageObject(currentAccount, msg, false, false);
message.isStoryReactionPush = true;
message.localType = 1;
if (user != null) {
message.localUserName = UserObject.getFirstName(user);
}
messageObjects.add(message);
getNotificationsController().processNewMessages(messageObjects, true, false, null);
} else if (baseUpdate instanceof TLRPC.TL_updateBroadcastRevenueTransactions) {
TLRPC.TL_updateBroadcastRevenueTransactions update = (TLRPC.TL_updateBroadcastRevenueTransactions) baseUpdate;
if (ChannelMonetizationLayout.instance != null) {
ChannelMonetizationLayout.instance.setupBalances(update.balances);
ChannelMonetizationLayout.instance.reloadTransactions();
}
} else if (baseUpdate instanceof TLRPC.TL_updateUser) { } else if (baseUpdate instanceof TLRPC.TL_updateUser) {
TLRPC.TL_updateUser update = (TLRPC.TL_updateUser) baseUpdate; TLRPC.TL_updateUser update = (TLRPC.TL_updateUser) baseUpdate;
TLRPC.User currentUser = getUser(update.user_id); TLRPC.User currentUser = getUser(update.user_id);
@ -18673,7 +18894,7 @@ public class MessagesController extends BaseController implements NotificationCe
if (topicId != 0) { if (topicId != 0) {
return isDialogMuted(dialogId, 0, chat); return isDialogMuted(dialogId, 0, chat);
} else { } else {
return !getNotificationsController().isGlobalNotificationsEnabled(dialogId, forceChannel); return !getNotificationsController().isGlobalNotificationsEnabled(dialogId, forceChannel, false, false);
} }
} }
if (mute_type == 2) { if (mute_type == 2) {
@ -18764,24 +18985,20 @@ public class MessagesController extends BaseController implements NotificationCe
message.flags |= 128; message.flags |= 128;
} }
message.peer_id = getPeer(dialogId); message.peer_id = getPeer(dialogId);
message.from_id = sponsoredMessage.from_id;
message.flags |= 256; message.flags |= 256;
message.date = getConnectionsManager().getCurrentTime(); message.date = getConnectionsManager().getCurrentTime();
message.id = messageId--; message.id = messageId--;
MessageObject messageObject = new MessageObject(currentAccount, message, usersDict, chatsDict, true, true); MessageObject messageObject = new MessageObject(currentAccount, message, usersDict, chatsDict, true, true);
messageObject.sponsoredId = sponsoredMessage.random_id; messageObject.sponsoredId = sponsoredMessage.random_id;
messageObject.botStartParam = sponsoredMessage.start_param; messageObject.sponsoredTitle = sponsoredMessage.title;
messageObject.sponsoredChannelPost = sponsoredMessage.channel_post; messageObject.sponsoredUrl = sponsoredMessage.url;
messageObject.sponsoredChatInvite = sponsoredMessage.chat_invite;
messageObject.sponsoredChatInviteHash = sponsoredMessage.chat_invite_hash;
messageObject.sponsoredRecommended = sponsoredMessage.recommended; messageObject.sponsoredRecommended = sponsoredMessage.recommended;
messageObject.sponsoredShowPeerPhoto = sponsoredMessage.show_peer_photo; messageObject.sponsoredPhoto = sponsoredMessage.photo;
messageObject.sponsoredInfo = sponsoredMessage.sponsor_info; messageObject.sponsoredInfo = sponsoredMessage.sponsor_info;
messageObject.sponsoredAdditionalInfo = sponsoredMessage.additional_info; messageObject.sponsoredAdditionalInfo = sponsoredMessage.additional_info;
messageObject.sponsoredWebPage = sponsoredMessage.webpage;
messageObject.sponsoredBotApp = sponsoredMessage.app;
messageObject.sponsoredButtonText = sponsoredMessage.button_text; messageObject.sponsoredButtonText = sponsoredMessage.button_text;
messageObject.sponsoredCanReport = sponsoredMessage.can_report; messageObject.sponsoredCanReport = sponsoredMessage.can_report;
messageObject.sponsoredColor = sponsoredMessage.color;
result.add(messageObject); result.add(messageObject);
} }
} }
@ -19831,7 +20048,7 @@ public class MessagesController extends BaseController implements NotificationCe
}); });
} }
public void setCustomChatReactions(long chatId, int type, List<TLRPC.Reaction> reactions, Utilities.Callback<TLRPC.TL_error> onError, Runnable onSuccess) { public void setCustomChatReactions(long chatId, int type, List<TLRPC.Reaction> reactions, int reactionsCount, Utilities.Callback<TLRPC.TL_error> onError, Runnable onSuccess) {
TLRPC.TL_messages_setChatAvailableReactions req = new TLRPC.TL_messages_setChatAvailableReactions(); TLRPC.TL_messages_setChatAvailableReactions req = new TLRPC.TL_messages_setChatAvailableReactions();
req.peer = getInputPeer(-chatId); req.peer = getInputPeer(-chatId);
if (type == ChatReactionsEditActivity.SELECT_TYPE_NONE || reactions.isEmpty()) { if (type == ChatReactionsEditActivity.SELECT_TYPE_NONE || reactions.isEmpty()) {
@ -19843,6 +20060,8 @@ public class MessagesController extends BaseController implements NotificationCe
req.available_reactions = someReactions; req.available_reactions = someReactions;
someReactions.reactions.addAll(reactions); someReactions.reactions.addAll(reactions);
} }
req.flags |= 1;
req.reactions_limit = reactionsCount;
getConnectionsManager().sendRequest(req, (response, error) -> { getConnectionsManager().sendRequest(req, (response, error) -> {
if (response != null) { if (response != null) {
processUpdates((TLRPC.Updates) response, false); processUpdates((TLRPC.Updates) response, false);
@ -19871,6 +20090,17 @@ public class MessagesController extends BaseController implements NotificationCe
}); });
} }
}); });
TLRPC.ChatFull chatFull = getChatFull(chatId);
if (chatFull != null) {
if (chatFull instanceof TLRPC.TL_channelFull) {
chatFull.flags2 |= 8192;
} else {
chatFull.flags |= 1048576;
}
chatFull.reactions_limit = reactionsCount;
getMessagesStorage().updateChatInfo(chatFull, false);
}
} }
public void setChatReactions(long chatId, int type, List<String> reactions) { public void setChatReactions(long chatId, int type, List<String> reactions) {
@ -19975,6 +20205,24 @@ public class MessagesController extends BaseController implements NotificationCe
return false; return false;
} }
public void getChannelParticipant(TLRPC.Chat chat, TLRPC.User user, Utilities.Callback<TLRPC.ChannelParticipant> callback) {
if (chat == null || user == null) {
if (callback != null) {
callback.run(null);
}
return;
}
TLRPC.TL_channels_getParticipant req = new TLRPC.TL_channels_getParticipant();
req.channel = getInputChannel(chat.id);
req.participant = getInputPeer(user);
getConnectionsManager().sendRequest(req, (res, err) -> {
if (callback != null) {
TLRPC.ChannelParticipant participant = res instanceof TLRPC.TL_channels_channelParticipant ? ((TLRPC.TL_channels_channelParticipant) res).participant : null;
callback.run(participant);
}
});
}
public void checkIsInChat(boolean tryCacheFirst, TLRPC.Chat chat, TLRPC.User user, IsInChatCheckedCallback callback) { public void checkIsInChat(boolean tryCacheFirst, TLRPC.Chat chat, TLRPC.User user, IsInChatCheckedCallback callback) {
if (chat == null || user == null) { if (chat == null || user == null) {
if (callback != null) { if (callback != null) {
@ -20397,9 +20645,16 @@ public class MessagesController extends BaseController implements NotificationCe
} }
private HashMap<Long, ChannelRecommendations> cachedChannelRecommendations; private HashMap<Long, ChannelRecommendations> cachedChannelRecommendations;
public ChannelRecommendations getCachedChannelRecommendations(long chatId) {
if (cachedChannelRecommendations == null) {
return null;
}
return cachedChannelRecommendations.get(chatId);
}
public ChannelRecommendations getChannelRecommendations(long chatId) { public ChannelRecommendations getChannelRecommendations(long chatId) {
TLRPC.InputChannel inputChannel = getInputChannel(chatId); TLRPC.InputChannel inputChannel = getInputChannel(chatId);
if (inputChannel == null) { if (inputChannel == null && chatId != 0) {
return null; return null;
} }
if (cachedChannelRecommendations == null) { if (cachedChannelRecommendations == null) {
@ -20415,7 +20670,10 @@ public class MessagesController extends BaseController implements NotificationCe
} }
cachedChannelRecommendations.put(chatId, null); cachedChannelRecommendations.put(chatId, null);
TLRPC.TL_channels_getChannelRecommendations req = new TLRPC.TL_channels_getChannelRecommendations(); TLRPC.TL_channels_getChannelRecommendations req = new TLRPC.TL_channels_getChannelRecommendations();
if (chatId != 0) {
req.flags |= 1;
req.channel = inputChannel; req.channel = inputChannel;
}
getConnectionsManager().sendRequest(req, (res, err) -> AndroidUtilities.runOnUIThread(() -> { getConnectionsManager().sendRequest(req, (res, err) -> AndroidUtilities.runOnUIThread(() -> {
if (res instanceof TLRPC.messages_Chats) { if (res instanceof TLRPC.messages_Chats) {
ArrayList<TLRPC.Chat> chats = ((TLRPC.messages_Chats) res).chats; ArrayList<TLRPC.Chat> chats = ((TLRPC.messages_Chats) res).chats;
@ -20907,4 +21165,22 @@ public class MessagesController extends BaseController implements NotificationCe
} }
})); }));
} }
public void disableAds(boolean send) {
TLRPC.UserFull userFull = getUserFull(getUserConfig().getClientUserId());
if (userFull == null) return;
userFull.sponsored_enabled = false;
getMessagesStorage().updateUserInfo(userFull, false);
if (send) {
TLRPC.TL_account_toggleSponsoredMessages req = new TLRPC.TL_account_toggleSponsoredMessages();
req.enabled = false;
getConnectionsManager().sendRequest(req, null);
}
}
public boolean isSponsoredDisabled() {
TLRPC.UserFull userFull = getUserFull(getUserConfig().getClientUserId());
if (userFull == null) return false;
return !userFull.sponsored_enabled;
}
} }

View file

@ -104,7 +104,7 @@ public class MessagesStorage extends BaseController {
} }
} }
public final static int LAST_DB_VERSION = 152; public final static int LAST_DB_VERSION = 153;
private boolean databaseMigrationInProgress; private boolean databaseMigrationInProgress;
public boolean showClearDatabaseAlert; public boolean showClearDatabaseAlert;
private LongSparseIntArray dialogIsForum = new LongSparseIntArray(); private LongSparseIntArray dialogIsForum = new LongSparseIntArray();
@ -698,7 +698,7 @@ public class MessagesStorage extends BaseController {
database.executeFast("CREATE TABLE stories (dialog_id INTEGER, story_id INTEGER, data BLOB, custom_params BLOB, PRIMARY KEY (dialog_id, story_id));").stepThis().dispose(); database.executeFast("CREATE TABLE stories (dialog_id INTEGER, story_id INTEGER, data BLOB, custom_params BLOB, PRIMARY KEY (dialog_id, story_id));").stepThis().dispose();
database.executeFast("CREATE TABLE stories_counter (dialog_id INTEGER PRIMARY KEY, count INTEGER, max_read INTEGER);").stepThis().dispose(); database.executeFast("CREATE TABLE stories_counter (dialog_id INTEGER PRIMARY KEY, count INTEGER, max_read INTEGER);").stepThis().dispose();
database.executeFast("CREATE TABLE profile_stories (dialog_id INTEGER, story_id INTEGER, data BLOB, type INTEGER, seen INTEGER, PRIMARY KEY(dialog_id, story_id));").stepThis().dispose(); database.executeFast("CREATE TABLE profile_stories (dialog_id INTEGER, story_id INTEGER, data BLOB, type INTEGER, seen INTEGER, pin INTEGER, PRIMARY KEY(dialog_id, story_id));").stepThis().dispose();
database.executeFast("CREATE TABLE story_drafts (id INTEGER PRIMARY KEY, date INTEGER, data BLOB, type INTEGER);").stepThis().dispose(); database.executeFast("CREATE TABLE story_drafts (id INTEGER PRIMARY KEY, date INTEGER, data BLOB, type INTEGER);").stepThis().dispose();
@ -1312,6 +1312,16 @@ public class MessagesStorage extends BaseController {
}); });
} }
public void deleteAllStoryReactionPushMessages() {
storageQueue.postRunnable(() -> {
try {
database.executeFast("DELETE FROM unread_push_messages WHERE is_reaction = 2").stepThis().dispose();
} catch (Exception e) {
checkSQLException(e);
}
});
}
public void putPushMessage(MessageObject message) { public void putPushMessage(MessageObject message) {
storageQueue.postRunnable(() -> { storageQueue.postRunnable(() -> {
try { try {
@ -1350,7 +1360,7 @@ public class MessagesStorage extends BaseController {
} }
state.bindInteger(9, flags); state.bindInteger(9, flags);
state.bindLong(10, MessageObject.getTopicId(currentAccount, message.messageOwner, false)); state.bindLong(10, MessageObject.getTopicId(currentAccount, message.messageOwner, false));
state.bindInteger(11, message.isReactionPush ? 1 : 0); state.bindInteger(11, (message.isReactionPush ? 1 : 0) + (message.isStoryReactionPush ? 1 : 0));
state.step(); state.step();
data.reuse(); data.reuse();
@ -3717,7 +3727,9 @@ public class MessagesStorage extends BaseController {
} }
MessageObject messageObject = new MessageObject(currentAccount, message, messageText, name, userName, (flags & 1) != 0, (flags & 2) != 0, (message.flags & 0x80000000) != 0, false); MessageObject messageObject = new MessageObject(currentAccount, message, messageText, name, userName, (flags & 1) != 0, (flags & 2) != 0, (message.flags & 0x80000000) != 0, false);
messageObject.isReactionPush = cursor.intValue(10) != 0; final int is_reaction = cursor.intValue(10);
messageObject.isReactionPush = is_reaction == 1;
messageObject.isStoryReactionPush = is_reaction == 2;
pushMessages.add(messageObject); pushMessages.add(messageObject);
addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad, null); addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad, null);
} }
@ -5175,7 +5187,7 @@ public class MessagesStorage extends BaseController {
TLRPC.Message message = new TLRPC.TL_message(); TLRPC.Message message = new TLRPC.TL_message();
SQLiteCursor cursor = null; SQLiteCursor cursor = null;
try { try {
cursor = database.queryFinalized("SELECT custom_params FROM messages_v2 WHERE mid = " + messageId + " AND uid = " + dialogId); cursor = database.queryFinalized("SELECT custom_params FROM messages_v2 WHERE mid = ? AND uid = ?", messageId, dialogId);
boolean read = false; boolean read = false;
if (cursor.next()) { if (cursor.next()) {
MessageCustomParamsHelper.readLocalParams(message, cursor.byteBufferValue(0)); MessageCustomParamsHelper.readLocalParams(message, cursor.byteBufferValue(0));
@ -5184,7 +5196,7 @@ public class MessagesStorage extends BaseController {
cursor.dispose(); cursor.dispose();
cursor = null; cursor = null;
if (!read) { if (!read) {
cursor = database.queryFinalized("SELECT custom_params FROM messages_topics WHERE mid = " + messageId + " AND uid = " + dialogId); cursor = database.queryFinalized("SELECT custom_params FROM messages_topics WHERE mid = ? AND uid = ?", messageId, dialogId);
if (cursor.next()) { if (cursor.next()) {
MessageCustomParamsHelper.readLocalParams(message, cursor.byteBufferValue(0)); MessageCustomParamsHelper.readLocalParams(message, cursor.byteBufferValue(0));
read = true; read = true;

View file

@ -706,6 +706,9 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
} }
} else if (id == NotificationCenter.messagePlayingDidSeek) { } else if (id == NotificationCenter.messagePlayingDidSeek) {
MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject(); MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
if (messageObject == null) {
return;
}
long progress = Math.round(messageObject.audioPlayerDuration * (float) args[1]) * 1000L; long progress = Math.round(messageObject.audioPlayerDuration * (float) args[1]) * 1000L;
updatePlaybackState(progress); updatePlaybackState(progress);
if (remoteControlClient != null && Build.VERSION.SDK_INT >= 18) { if (remoteControlClient != null && Build.VERSION.SDK_INT >= 18) {

View file

@ -44,6 +44,7 @@ public class NotificationCenter {
public static final int loadingMessagesFailed = totalEvents++; public static final int loadingMessagesFailed = totalEvents++;
public static final int messageReceivedByAck = totalEvents++; public static final int messageReceivedByAck = totalEvents++;
public static final int messageReceivedByServer = totalEvents++; public static final int messageReceivedByServer = totalEvents++;
public static final int messageReceivedByServer2 = totalEvents++;
public static final int messageSendError = totalEvents++; public static final int messageSendError = totalEvents++;
public static final int forceImportContactsStart = totalEvents++; public static final int forceImportContactsStart = totalEvents++;
public static final int contactsDidLoad = totalEvents++; public static final int contactsDidLoad = totalEvents++;

View file

@ -27,6 +27,8 @@ public class NotificationDismissReceiver extends BroadcastReceiver {
int date = intent.getIntExtra("messageDate", 0); int date = intent.getIntExtra("messageDate", 0);
if (intent.hasExtra("story") && intent.getBooleanExtra("story", false)) { if (intent.hasExtra("story") && intent.getBooleanExtra("story", false)) {
NotificationsController.getInstance(currentAccount).processIgnoreStories(); NotificationsController.getInstance(currentAccount).processIgnoreStories();
} else if (intent.hasExtra("storyReaction") && intent.getBooleanExtra("storyReaction", false)) {
NotificationsController.getInstance(currentAccount).processIgnoreStoryReactions();
} else if (dialogId == 0) { } else if (dialogId == 0) {
MessagesController.getNotificationsSettings(currentAccount).edit().putInt("dismissDate", date).commit(); MessagesController.getNotificationsSettings(currentAccount).edit().putInt("dismissDate", date).commit();
} else { } else {

View file

@ -253,7 +253,11 @@ public class NotificationsController extends BaseController {
} }
NotificationChannel notificationChannel = systemNotificationManager.getNotificationChannel(OTHER_NOTIFICATIONS_CHANNEL); NotificationChannel notificationChannel = systemNotificationManager.getNotificationChannel(OTHER_NOTIFICATIONS_CHANNEL);
if (notificationChannel != null && notificationChannel.getImportance() == NotificationManager.IMPORTANCE_NONE) { if (notificationChannel != null && notificationChannel.getImportance() == NotificationManager.IMPORTANCE_NONE) {
try {
systemNotificationManager.deleteNotificationChannel(OTHER_NOTIFICATIONS_CHANNEL); systemNotificationManager.deleteNotificationChannel(OTHER_NOTIFICATIONS_CHANNEL);
} catch (Exception e) {
FileLog.e(e);
}
OTHER_NOTIFICATIONS_CHANNEL = null; OTHER_NOTIFICATIONS_CHANNEL = null;
notificationChannel = null; notificationChannel = null;
} }
@ -319,7 +323,7 @@ public class NotificationsController extends BaseController {
SharedPreferences.Editor editor = preferences.edit(); SharedPreferences.Editor editor = preferences.edit();
long flags; long flags;
boolean override = topicId != 0; boolean override = topicId != 0;
boolean defaultEnabled = NotificationsController.getInstance(currentAccount).isGlobalNotificationsEnabled(did); boolean defaultEnabled = NotificationsController.getInstance(currentAccount).isGlobalNotificationsEnabled(did, false, false);
String sharedPrefKey = NotificationsController.getSharedPrefKey(did, topicId); String sharedPrefKey = NotificationsController.getSharedPrefKey(did, topicId);
if (selectedTimeInSeconds == Integer.MAX_VALUE) { if (selectedTimeInSeconds == Integer.MAX_VALUE) {
@ -511,6 +515,8 @@ public class NotificationsController extends BaseController {
int mid = mids.get(b); int mid = mids.get(b);
MessageObject messageObject = sparseArray.get(mid); MessageObject messageObject = sparseArray.get(mid);
if (messageObject != null) { if (messageObject != null) {
if (messageObject.isStoryReactionPush)
continue;
if (isReactions && !messageObject.isReactionPush) { if (isReactions && !messageObject.isReactionPush) {
continue; continue;
} }
@ -664,6 +670,31 @@ public class NotificationsController extends BaseController {
}); });
} }
public void processSeenStoryReactions(long dialogId, int storyId) {
if (dialogId != getUserConfig().getClientUserId())
return;
notificationsQueue.postRunnable(() -> {
boolean changed = false;
for (int i = 0; i < pushMessages.size(); ++i) {
MessageObject msgObject = pushMessages.get(i);
if (msgObject.isStoryReactionPush && Math.abs(msgObject.getId()) == storyId) {
pushMessages.remove(i);
SparseArray<MessageObject> msgs = pushMessagesDict.get(msgObject.getDialogId());
if (msgs != null) msgs.remove(msgObject.getId());
if (msgs != null && msgs.size() <= 0) pushMessagesDict.remove(msgObject.getDialogId());
ArrayList<Integer> ids = new ArrayList<>();
ids.add(msgObject.getId());
getMessagesStorage().deletePushMessages(msgObject.getDialogId(), ids);
i--;
changed = true;
}
}
if (changed) {
showOrUpdateNotification(false);
}
});
}
public void processDeleteStory(long dialogId, int storyId) { public void processDeleteStory(long dialogId, int storyId) {
notificationsQueue.postRunnable(() -> { notificationsQueue.postRunnable(() -> {
boolean changed = false; boolean changed = false;
@ -723,6 +754,27 @@ public class NotificationsController extends BaseController {
}); });
} }
public void processIgnoreStoryReactions() {
notificationsQueue.postRunnable(() -> {
boolean changed = false;
for (int i = 0; i < pushMessages.size(); ++i) {
MessageObject msg = pushMessages.get(i);
if (msg != null && msg.isStoryReactionPush) {
pushMessages.remove(i);
i--;
SparseArray<MessageObject> arr = pushMessagesDict.get(msg.getDialogId());
if (arr != null) arr.remove(msg.getId());
if (arr != null && arr.size() <= 0) pushMessagesDict.remove(msg.getDialogId());
changed = true;
}
}
getMessagesStorage().deleteAllStoryReactionPushMessages();
if (changed) {
showOrUpdateNotification(false);
}
});
}
public void processIgnoreStories(long dialogId) { public void processIgnoreStories(long dialogId) {
notificationsQueue.postRunnable(() -> { notificationsQueue.postRunnable(() -> {
boolean changed = !storyPushMessages.isEmpty(); boolean changed = !storyPushMessages.isEmpty();
@ -735,6 +787,10 @@ public class NotificationsController extends BaseController {
}); });
} }
public void processReadStories() {
}
public void processReadMessages(LongSparseIntArray inbox, long dialogId, int maxDate, int maxId, boolean isPopup) { public void processReadMessages(LongSparseIntArray inbox, long dialogId, int maxDate, int maxId, boolean isPopup) {
ArrayList<MessageObject> popupArrayRemove = new ArrayList<>(0); ArrayList<MessageObject> popupArrayRemove = new ArrayList<>(0);
notificationsQueue.postRunnable(() -> { notificationsQueue.postRunnable(() -> {
@ -744,13 +800,15 @@ public class NotificationsController extends BaseController {
int messageId = inbox.get(key); int messageId = inbox.get(key);
for (int a = 0; a < pushMessages.size(); a++) { for (int a = 0; a < pushMessages.size(); a++) {
MessageObject messageObject = pushMessages.get(a); MessageObject messageObject = pushMessages.get(a);
if (!messageObject.messageOwner.from_scheduled && messageObject.getDialogId() == key && messageObject.getId() <= messageId) { if (!messageObject.messageOwner.from_scheduled && messageObject.getDialogId() == key && messageObject.getId() <= messageId && !messageObject.isStoryReactionPush) {
if (isPersonalMessage(messageObject)) { if (isPersonalMessage(messageObject)) {
personalCount--; personalCount--;
} }
popupArrayRemove.add(messageObject); popupArrayRemove.add(messageObject);
long did; long did;
if (messageObject.messageOwner.peer_id.channel_id != 0) { if (messageObject.isStoryReactionPush) {
did = messageObject.getDialogId();
} else if (messageObject.messageOwner.peer_id.channel_id != 0) {
did = -messageObject.messageOwner.peer_id.channel_id; did = -messageObject.messageOwner.peer_id.channel_id;
} else { } else {
did = 0; did = 0;
@ -772,7 +830,7 @@ public class NotificationsController extends BaseController {
if (dialogId != 0 && (maxId != 0 || maxDate != 0)) { if (dialogId != 0 && (maxId != 0 || maxDate != 0)) {
for (int a = 0; a < pushMessages.size(); a++) { for (int a = 0; a < pushMessages.size(); a++) {
MessageObject messageObject = pushMessages.get(a); MessageObject messageObject = pushMessages.get(a);
if (messageObject.getDialogId() == dialogId) { if (messageObject.getDialogId() == dialogId && !messageObject.isStoryReactionPush) {
boolean remove = false; boolean remove = false;
if (maxDate != 0) { if (maxDate != 0) {
if (messageObject.messageOwner.date <= maxDate) { if (messageObject.messageOwner.date <= maxDate) {
@ -794,7 +852,9 @@ public class NotificationsController extends BaseController {
personalCount--; personalCount--;
} }
long did; long did;
if (messageObject.messageOwner.peer_id.channel_id != 0) { if (messageObject.isStoryReactionPush) {
did = messageObject.getDialogId();
} else if (messageObject.messageOwner.peer_id.channel_id != 0) {
did = -messageObject.messageOwner.peer_id.channel_id; did = -messageObject.messageOwner.peer_id.channel_id;
} else { } else {
did = 0; did = 0;
@ -826,6 +886,7 @@ public class NotificationsController extends BaseController {
} }
private int addToPopupMessages(ArrayList<MessageObject> popupArrayAdd, MessageObject messageObject, long dialogId, boolean isChannel, SharedPreferences preferences) { private int addToPopupMessages(ArrayList<MessageObject> popupArrayAdd, MessageObject messageObject, long dialogId, boolean isChannel, SharedPreferences preferences) {
if (messageObject.isStoryReactionPush) return 0;
int popup = 0; int popup = 0;
if (!DialogObject.isEncryptedDialog(dialogId)) { if (!DialogObject.isEncryptedDialog(dialogId)) {
if (preferences.getBoolean("custom_" + dialogId, false)) { if (preferences.getBoolean("custom_" + dialogId, false)) {
@ -865,7 +926,9 @@ public class NotificationsController extends BaseController {
for (int b = 0, N2 = messages.size(); b < N2; b++) { for (int b = 0, N2 = messages.size(); b < N2; b++) {
MessageObject messageObject = messages.get(b); MessageObject messageObject = messages.get(b);
long did; long did;
if (messageObject.messageOwner.peer_id.channel_id != 0) { if (messageObject.isStoryReactionPush) {
did = messageObject.getDialogId();
} else if (messageObject.messageOwner.peer_id.channel_id != 0) {
did = -messageObject.messageOwner.peer_id.channel_id; did = -messageObject.messageOwner.peer_id.channel_id;
} else { } else {
did = 0; did = 0;
@ -875,7 +938,7 @@ public class NotificationsController extends BaseController {
break; break;
} }
MessageObject oldMessage = sparseArray.get(messageObject.getId()); MessageObject oldMessage = sparseArray.get(messageObject.getId());
if (oldMessage != null && oldMessage.isReactionPush) { if (oldMessage != null && (oldMessage.isReactionPush || oldMessage.isStoryReactionPush)) {
oldMessage = null; oldMessage = null;
} }
if (oldMessage != null) { if (oldMessage != null) {
@ -967,7 +1030,9 @@ public class NotificationsController extends BaseController {
isChannel = false; isChannel = false;
} }
long did; long did;
if (messageObject.messageOwner.peer_id.channel_id != 0) { if (messageObject.isStoryReactionPush) {
did = messageObject.getDialogId();
} else if (messageObject.messageOwner.peer_id.channel_id != 0) {
did = -messageObject.messageOwner.peer_id.channel_id; did = -messageObject.messageOwner.peer_id.channel_id;
} else { } else {
did = 0; did = 0;
@ -1007,7 +1072,7 @@ public class NotificationsController extends BaseController {
long originalDialogId = dialogId; long originalDialogId = dialogId;
long topicId = MessageObject.getTopicId(currentAccount, messageObject.messageOwner, getMessagesController().isForum(messageObject)); long topicId = MessageObject.getTopicId(currentAccount, messageObject.messageOwner, getMessagesController().isForum(messageObject));
if (dialogId == openedDialogId && ApplicationLoader.isScreenOn) { if (dialogId == openedDialogId && ApplicationLoader.isScreenOn && !messageObject.isStoryReactionPush) {
if (!isFcm) { if (!isFcm) {
playInChatSound(); playInChatSound();
} }
@ -1032,7 +1097,7 @@ public class NotificationsController extends BaseController {
} else { } else {
int notifyOverride = getNotifyOverride(preferences, dialogId, topicId); int notifyOverride = getNotifyOverride(preferences, dialogId, topicId);
if (notifyOverride == -1) { if (notifyOverride == -1) {
value = isGlobalNotificationsEnabled(dialogId, isChannel); value = isGlobalNotificationsEnabled(dialogId, isChannel, messageObject.isReactionPush, messageObject.isStoryReactionPush);
/*if (BuildVars.DEBUG_PRIVATE_VERSION && BuildVars.LOGS_ENABLED) { /*if (BuildVars.DEBUG_PRIVATE_VERSION && BuildVars.LOGS_ENABLED) {
FileLog.d("global notify settings for " + dialog_id + " = " + value); FileLog.d("global notify settings for " + dialog_id + " = " + value);
}*/ }*/
@ -1113,7 +1178,7 @@ public class NotificationsController extends BaseController {
int notifyOverride = getNotifyOverride(preferences, dialog_id, topicId); int notifyOverride = getNotifyOverride(preferences, dialog_id, topicId);
boolean canAddValue; boolean canAddValue;
if (notifyOverride == -1) { if (notifyOverride == -1) {
canAddValue = isGlobalNotificationsEnabled(dialog_id, isChannel); canAddValue = isGlobalNotificationsEnabled(dialog_id, isChannel, messageObject.isReactionPush, messageObject.isStoryReactionPush);
} else { } else {
canAddValue = notifyOverride != 2; canAddValue = notifyOverride != 2;
} }
@ -1208,7 +1273,7 @@ public class NotificationsController extends BaseController {
if (!forum) { if (!forum) {
int notifyOverride = getNotifyOverride(preferences, dialogId, 0); int notifyOverride = getNotifyOverride(preferences, dialogId, 0);
if (notifyOverride == -1) { if (notifyOverride == -1) {
canAddValue = isGlobalNotificationsEnabled(dialogId); canAddValue = isGlobalNotificationsEnabled(dialogId, false, false);
} else { } else {
canAddValue = notifyOverride != 2; canAddValue = notifyOverride != 2;
} }
@ -1248,7 +1313,7 @@ public class NotificationsController extends BaseController {
pushDialogsOverrideMention.remove(dialogId); pushDialogsOverrideMention.remove(dialogId);
for (int a = 0; a < pushMessages.size(); a++) { for (int a = 0; a < pushMessages.size(); a++) {
MessageObject messageObject = pushMessages.get(a); MessageObject messageObject = pushMessages.get(a);
if (!messageObject.messageOwner.from_scheduled && messageObject.getDialogId() == dialogId) { if (!messageObject.messageOwner.from_scheduled && messageObject.getDialogId() == dialogId && !messageObject.isStoryReactionPush) {
if (isPersonalMessage(messageObject)) { if (isPersonalMessage(messageObject)) {
personalCount--; personalCount--;
} }
@ -1362,7 +1427,7 @@ public class NotificationsController extends BaseController {
} else { } else {
int notifyOverride = getNotifyOverride(preferences, dialog_id, topicId); int notifyOverride = getNotifyOverride(preferences, dialog_id, topicId);
if (notifyOverride == -1) { if (notifyOverride == -1) {
value = isGlobalNotificationsEnabled(dialog_id); value = isGlobalNotificationsEnabled(dialog_id, messageObject.isReactionPush, messageObject.isStoryReactionPush);
} else { } else {
value = notifyOverride != 2; value = notifyOverride != 2;
} }
@ -1392,7 +1457,7 @@ public class NotificationsController extends BaseController {
} else { } else {
int notifyOverride = getNotifyOverride(preferences, dialog_id, 0); int notifyOverride = getNotifyOverride(preferences, dialog_id, 0);
if (notifyOverride == -1) { if (notifyOverride == -1) {
value = isGlobalNotificationsEnabled(dialog_id); value = isGlobalNotificationsEnabled(dialog_id, false, false);
} else { } else {
value = notifyOverride != 2; value = notifyOverride != 2;
} }
@ -1435,7 +1500,7 @@ public class NotificationsController extends BaseController {
} else { } else {
int notifyOverride = getNotifyOverride(preferences, dialogId, topicId); int notifyOverride = getNotifyOverride(preferences, dialogId, topicId);
if (notifyOverride == -1) { if (notifyOverride == -1) {
value = isGlobalNotificationsEnabled(dialogId); value = isGlobalNotificationsEnabled(dialogId, messageObject.isReactionPush, messageObject.isStoryReactionPush);
} else { } else {
value = notifyOverride != 2; value = notifyOverride != 2;
} }
@ -1446,7 +1511,9 @@ public class NotificationsController extends BaseController {
} }
if (mid != 0) { if (mid != 0) {
long did; long did;
if (messageObject.messageOwner.peer_id.channel_id != 0) { if (messageObject.isStoryReactionPush) {
did = messageObject.getDialogId();
} else if (messageObject.messageOwner.peer_id.channel_id != 0) {
did = -messageObject.messageOwner.peer_id.channel_id; did = -messageObject.messageOwner.peer_id.channel_id;
} else { } else {
did = 0; did = 0;
@ -1893,9 +1960,9 @@ public class NotificationsController extends BaseController {
} else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) object.messageOwner.media; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) object.messageOwner.media;
if (mediaPoll.poll.quiz) { if (mediaPoll.poll.quiz) {
return LocaleController.formatString("NotificationActionPinnedQuiz2", R.string.NotificationActionPinnedQuiz2, name, chat.title, mediaPoll.poll.question); return LocaleController.formatString("NotificationActionPinnedQuiz2", R.string.NotificationActionPinnedQuiz2, name, chat.title, mediaPoll.poll.question.text);
} else { } else {
return LocaleController.formatString("NotificationActionPinnedPoll2", R.string.NotificationActionPinnedPoll2, name, chat.title, mediaPoll.poll.question); return LocaleController.formatString("NotificationActionPinnedPoll2", R.string.NotificationActionPinnedPoll2, name, chat.title, mediaPoll.poll.question.text);
} }
} else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(object.messageOwner.message)) { if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(object.messageOwner.message)) {
@ -1965,9 +2032,9 @@ public class NotificationsController extends BaseController {
} else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) object.messageOwner.media; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) object.messageOwner.media;
if (mediaPoll.poll.quiz) { if (mediaPoll.poll.quiz) {
return LocaleController.formatString("NotificationActionPinnedQuizChannel2", R.string.NotificationActionPinnedQuizChannel2, chat.title, mediaPoll.poll.question); return LocaleController.formatString("NotificationActionPinnedQuizChannel2", R.string.NotificationActionPinnedQuizChannel2, chat.title, mediaPoll.poll.question.text);
} else { } else {
return LocaleController.formatString("NotificationActionPinnedPollChannel2", R.string.NotificationActionPinnedPollChannel2, chat.title, mediaPoll.poll.question); return LocaleController.formatString("NotificationActionPinnedPollChannel2", R.string.NotificationActionPinnedPollChannel2, chat.title, mediaPoll.poll.question.text);
} }
} else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(object.messageOwner.message)) { if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(object.messageOwner.message)) {
@ -2037,9 +2104,9 @@ public class NotificationsController extends BaseController {
} else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) object.messageOwner.media; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) object.messageOwner.media;
if (mediaPoll.poll.quiz) { if (mediaPoll.poll.quiz) {
return LocaleController.formatString("NotificationActionPinnedQuizUser", R.string.NotificationActionPinnedQuizUser, name, mediaPoll.poll.question); return LocaleController.formatString("NotificationActionPinnedQuizUser", R.string.NotificationActionPinnedQuizUser, name, mediaPoll.poll.question.text);
} else { } else {
return LocaleController.formatString("NotificationActionPinnedPollUser", R.string.NotificationActionPinnedPollUser, name, mediaPoll.poll.question); return LocaleController.formatString("NotificationActionPinnedPollUser", R.string.NotificationActionPinnedPollUser, name, mediaPoll.poll.question.text);
} }
} else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(object.messageOwner.message)) { if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(object.messageOwner.message)) {
@ -2377,9 +2444,9 @@ public class NotificationsController extends BaseController {
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) messageObject.messageOwner.media; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) messageObject.messageOwner.media;
if (mediaPoll.poll.quiz) { if (mediaPoll.poll.quiz) {
msg = LocaleController.formatString("NotificationMessageQuiz2", R.string.NotificationMessageQuiz2, name, mediaPoll.poll.question); msg = LocaleController.formatString("NotificationMessageQuiz2", R.string.NotificationMessageQuiz2, name, mediaPoll.poll.question.text);
} else { } else {
msg = LocaleController.formatString("NotificationMessagePoll2", R.string.NotificationMessagePoll2, name, mediaPoll.poll.question); msg = LocaleController.formatString("NotificationMessagePoll2", R.string.NotificationMessagePoll2, name, mediaPoll.poll.question.text);
} }
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
msg = LocaleController.formatString("NotificationMessageMap", R.string.NotificationMessageMap, name); msg = LocaleController.formatString("NotificationMessageMap", R.string.NotificationMessageMap, name);
@ -2600,9 +2667,9 @@ public class NotificationsController extends BaseController {
} else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) object.messageOwner.media; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) object.messageOwner.media;
if (mediaPoll.poll.quiz) { if (mediaPoll.poll.quiz) {
msg = LocaleController.formatString("NotificationActionPinnedQuiz2", R.string.NotificationActionPinnedQuiz2, name, chat.title, mediaPoll.poll.question); msg = LocaleController.formatString("NotificationActionPinnedQuiz2", R.string.NotificationActionPinnedQuiz2, name, chat.title, mediaPoll.poll.question.text);
} else { } else {
msg = LocaleController.formatString("NotificationActionPinnedPoll2", R.string.NotificationActionPinnedPoll2, name, chat.title, mediaPoll.poll.question); msg = LocaleController.formatString("NotificationActionPinnedPoll2", R.string.NotificationActionPinnedPoll2, name, chat.title, mediaPoll.poll.question.text);
} }
} else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(object.messageOwner.message)) { if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(object.messageOwner.message)) {
@ -2672,9 +2739,9 @@ public class NotificationsController extends BaseController {
} else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) object.messageOwner.media; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) object.messageOwner.media;
if (mediaPoll.poll.quiz) { if (mediaPoll.poll.quiz) {
msg = LocaleController.formatString("NotificationActionPinnedQuizChannel2", R.string.NotificationActionPinnedQuizChannel2, chat.title, mediaPoll.poll.question); msg = LocaleController.formatString("NotificationActionPinnedQuizChannel2", R.string.NotificationActionPinnedQuizChannel2, chat.title, mediaPoll.poll.question.text);
} else { } else {
msg = LocaleController.formatString("NotificationActionPinnedPollChannel2", R.string.NotificationActionPinnedPollChannel2, chat.title, mediaPoll.poll.question); msg = LocaleController.formatString("NotificationActionPinnedPollChannel2", R.string.NotificationActionPinnedPollChannel2, chat.title, mediaPoll.poll.question.text);
} }
} else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(object.messageOwner.message)) { if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(object.messageOwner.message)) {
@ -2746,9 +2813,9 @@ public class NotificationsController extends BaseController {
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) messageObject.messageOwner.media; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) messageObject.messageOwner.media;
if (mediaPoll.poll.quiz) { if (mediaPoll.poll.quiz) {
msg = LocaleController.formatString("ChannelMessageQuiz2", R.string.ChannelMessageQuiz2, name, mediaPoll.poll.question); msg = LocaleController.formatString("ChannelMessageQuiz2", R.string.ChannelMessageQuiz2, name, mediaPoll.poll.question.text);
} else { } else {
msg = LocaleController.formatString("ChannelMessagePoll2", R.string.ChannelMessagePoll2, name, mediaPoll.poll.question); msg = LocaleController.formatString("ChannelMessagePoll2", R.string.ChannelMessagePoll2, name, mediaPoll.poll.question.text);
} }
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGiveaway) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGiveaway) {
TLRPC.TL_messageMediaGiveaway giveaway = (TLRPC.TL_messageMediaGiveaway) messageObject.messageOwner.media; TLRPC.TL_messageMediaGiveaway giveaway = (TLRPC.TL_messageMediaGiveaway) messageObject.messageOwner.media;
@ -2819,9 +2886,9 @@ public class NotificationsController extends BaseController {
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) messageObject.messageOwner.media; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) messageObject.messageOwner.media;
if (mediaPoll.poll.quiz) { if (mediaPoll.poll.quiz) {
msg = LocaleController.formatString("NotificationMessageGroupQuiz2", R.string.NotificationMessageGroupQuiz2, name, chat.title, mediaPoll.poll.question); msg = LocaleController.formatString("NotificationMessageGroupQuiz2", R.string.NotificationMessageGroupQuiz2, name, chat.title, mediaPoll.poll.question.text);
} else { } else {
msg = LocaleController.formatString("NotificationMessageGroupPoll2", R.string.NotificationMessageGroupPoll2, name, chat.title, mediaPoll.poll.question); msg = LocaleController.formatString("NotificationMessageGroupPoll2", R.string.NotificationMessageGroupPoll2, name, chat.title, mediaPoll.poll.question.text);
} }
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
msg = LocaleController.formatString("NotificationMessageGroupGame", R.string.NotificationMessageGroupGame, name, chat.title, messageObject.messageOwner.media.game.title); msg = LocaleController.formatString("NotificationMessageGroupGame", R.string.NotificationMessageGroupGame, name, chat.title, messageObject.messageOwner.media.game.title);
@ -2897,7 +2964,7 @@ public class NotificationsController extends BaseController {
private boolean isPersonalMessage(MessageObject messageObject) { private boolean isPersonalMessage(MessageObject messageObject) {
return messageObject.messageOwner.peer_id != null && messageObject.messageOwner.peer_id.chat_id == 0 && messageObject.messageOwner.peer_id.channel_id == 0 return messageObject.messageOwner.peer_id != null && messageObject.messageOwner.peer_id.chat_id == 0 && messageObject.messageOwner.peer_id.channel_id == 0
&& (messageObject.messageOwner.action == null || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionEmpty); && (messageObject.messageOwner.action == null || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionEmpty) || messageObject.isStoryReactionPush;
} }
private int getNotifyOverride(SharedPreferences preferences, long dialog_id, long topicId) { private int getNotifyOverride(SharedPreferences preferences, long dialog_id, long topicId) {
@ -3118,6 +3185,8 @@ public class NotificationsController extends BaseController {
key = "groups"; key = "groups";
} else if (type == TYPE_STORIES) { } else if (type == TYPE_STORIES) {
key = "stories"; key = "stories";
} else if (type == TYPE_REACTIONS_MESSAGES || type == TYPE_REACTIONS_STORIES) {
key = "reactions";
} else { } else {
key = "private"; key = "private";
} }
@ -3143,6 +3212,8 @@ public class NotificationsController extends BaseController {
key = "groups_ia"; key = "groups_ia";
} else if (type == TYPE_STORIES) { } else if (type == TYPE_STORIES) {
key = "stories_ia"; key = "stories_ia";
} else if (type == TYPE_REACTIONS_MESSAGES || type == TYPE_REACTIONS_STORIES) {
key = "reactions_ia";
} else { } else {
key = "private_ia"; key = "private_ia";
} }
@ -3166,6 +3237,8 @@ public class NotificationsController extends BaseController {
overwriteKey = "overwrite_group"; overwriteKey = "overwrite_group";
} else if (type == TYPE_STORIES) { } else if (type == TYPE_STORIES) {
overwriteKey = "overwrite_stories"; overwriteKey = "overwrite_stories";
} else if (type == TYPE_REACTIONS_MESSAGES || type == TYPE_REACTIONS_STORIES) {
overwriteKey = "overwrite_reactions";
} else { } else {
overwriteKey = "overwrite_private"; overwriteKey = "overwrite_private";
} }
@ -3291,7 +3364,7 @@ public class NotificationsController extends BaseController {
protected void ensureGroupsCreated() { protected void ensureGroupsCreated() {
SharedPreferences preferences = getAccountInstance().getNotificationsSettings(); SharedPreferences preferences = getAccountInstance().getNotificationsSettings();
if (groupsCreated == null) { if (groupsCreated == null) {
groupsCreated = preferences.getBoolean("groupsCreated4", false); groupsCreated = preferences.getBoolean("groupsCreated5", false);
} }
if (!groupsCreated) { if (!groupsCreated) {
try { try {
@ -3312,6 +3385,11 @@ public class NotificationsController extends BaseController {
editor = getAccountInstance().getNotificationsSettings().edit(); editor = getAccountInstance().getNotificationsSettings().edit();
} }
editor.remove("priority_channel").remove("vibrate_channel").remove("ChannelSoundPath").remove("ChannelSound"); editor.remove("priority_channel").remove("vibrate_channel").remove("ChannelSoundPath").remove("ChannelSound");
} else if (id.contains("_reactions_")) {
if (editor == null) {
editor = getAccountInstance().getNotificationsSettings().edit();
}
editor.remove("priority_react").remove("vibrate_react").remove("ReactionSoundPath").remove("ReactionSound");
} else if (id.contains("_groups_")) { } else if (id.contains("_groups_")) {
if (editor == null) { if (editor == null) {
editor = getAccountInstance().getNotificationsSettings().edit(); editor = getAccountInstance().getNotificationsSettings().edit();
@ -3342,7 +3420,7 @@ public class NotificationsController extends BaseController {
} catch (Exception e) { } catch (Exception e) {
FileLog.e(e); FileLog.e(e);
} }
preferences.edit().putBoolean("groupsCreated4", true).commit(); preferences.edit().putBoolean("groupsCreated5", true).commit();
groupsCreated = true; groupsCreated = true;
} }
if (!channelGroupsCreated) { if (!channelGroupsCreated) {
@ -3351,6 +3429,7 @@ public class NotificationsController extends BaseController {
String groupsId = "groups" + currentAccount; String groupsId = "groups" + currentAccount;
String privateId = "private" + currentAccount; String privateId = "private" + currentAccount;
String storiesId = "stories" + currentAccount; String storiesId = "stories" + currentAccount;
String reactionsId = "reactions" + currentAccount;
String otherId = "other" + currentAccount; String otherId = "other" + currentAccount;
for (int a = 0, N = list.size(); a < N; a++) { for (int a = 0, N = list.size(); a < N; a++) {
String id = list.get(a).getId(); String id = list.get(a).getId();
@ -3360,17 +3439,19 @@ public class NotificationsController extends BaseController {
groupsId = null; groupsId = null;
} else if (storiesId != null && storiesId.equals(id)) { } else if (storiesId != null && storiesId.equals(id)) {
storiesId = null; storiesId = null;
} else if (reactionsId != null && reactionsId.equals(id)) {
reactionsId = null;
} else if (privateId != null && privateId.equals(id)) { } else if (privateId != null && privateId.equals(id)) {
privateId = null; privateId = null;
} else if (otherId != null && otherId.equals(id)) { } else if (otherId != null && otherId.equals(id)) {
otherId = null; otherId = null;
} }
if (channelsId == null && storiesId == null && groupsId == null && privateId == null && otherId == null) { if (channelsId == null && storiesId == null && reactionsId == null && groupsId == null && privateId == null && otherId == null) {
break; break;
} }
} }
if (channelsId != null || groupsId != null || storiesId != null || privateId != null || otherId != null) { if (channelsId != null || groupsId != null || reactionsId != null || storiesId != null || privateId != null || otherId != null) {
TLRPC.User user = getMessagesController().getUser(getUserConfig().getClientUserId()); TLRPC.User user = getMessagesController().getUser(getUserConfig().getClientUserId());
if (user == null) { if (user == null) {
getUserConfig().getCurrentUser(); getUserConfig().getCurrentUser();
@ -3390,7 +3471,10 @@ public class NotificationsController extends BaseController {
channelGroups.add(new NotificationChannelGroup(groupsId, LocaleController.getString("NotificationsGroups", R.string.NotificationsGroups) + userName)); channelGroups.add(new NotificationChannelGroup(groupsId, LocaleController.getString("NotificationsGroups", R.string.NotificationsGroups) + userName));
} }
if (storiesId != null) { if (storiesId != null) {
channelGroups.add(new NotificationChannelGroup(storiesId, LocaleController.getString("NotificationsStories", R.string.NotificationsStories) + userName)); channelGroups.add(new NotificationChannelGroup(storiesId, LocaleController.getString(R.string.NotificationsStories) + userName));
}
if (reactionsId != null) {
channelGroups.add(new NotificationChannelGroup(reactionsId, LocaleController.getString(R.string.NotificationsReactions) + userName));
} }
if (privateId != null) { if (privateId != null) {
channelGroups.add(new NotificationChannelGroup(privateId, LocaleController.getString("NotificationsPrivateChats", R.string.NotificationsPrivateChats) + userName)); channelGroups.add(new NotificationChannelGroup(privateId, LocaleController.getString("NotificationsPrivateChats", R.string.NotificationsPrivateChats) + userName));
@ -3428,6 +3512,9 @@ public class NotificationsController extends BaseController {
} else if (type == TYPE_STORIES) { } else if (type == TYPE_STORIES) {
groupId = "stories" + currentAccount; groupId = "stories" + currentAccount;
overwriteKey = "overwrite_stories"; overwriteKey = "overwrite_stories";
} else if (type == TYPE_REACTIONS_MESSAGES || type == TYPE_REACTIONS_STORIES) {
groupId = "reactions" + currentAccount;
overwriteKey = "overwrite_reactions";
} else { } else {
groupId = "private" + currentAccount; groupId = "private" + currentAccount;
overwriteKey = "overwrite_private"; overwriteKey = "overwrite_private";
@ -3453,6 +3540,8 @@ public class NotificationsController extends BaseController {
key = isInApp ? "groups_ia" : "groups"; key = isInApp ? "groups_ia" : "groups";
} else if (type == TYPE_STORIES) { } else if (type == TYPE_STORIES) {
key = isInApp ? "stories_ia" : "stories"; key = isInApp ? "stories_ia" : "stories";
} else if (type == TYPE_REACTIONS_MESSAGES || type == TYPE_REACTIONS_STORIES) {
key = isInApp ? "reactions_ia" : "reactions";
} else { } else {
key = isInApp ? "private_ia" : "private"; key = isInApp ? "private_ia" : "private";
} }
@ -3511,6 +3600,9 @@ public class NotificationsController extends BaseController {
if (!isInApp) { if (!isInApp) {
if (type == TYPE_STORIES) { if (type == TYPE_STORIES) {
editor.putBoolean("EnableAllStories", false); editor.putBoolean("EnableAllStories", false);
} else if (type == TYPE_REACTIONS_MESSAGES) {
editor.putBoolean("EnableReactionsMessages", true);
editor.putBoolean("EnableReactionsStories", true);
} else { } else {
editor.putInt(getGlobalNotificationsKey(type), Integer.MAX_VALUE); editor.putInt(getGlobalNotificationsKey(type), Integer.MAX_VALUE);
} }
@ -3541,6 +3633,9 @@ public class NotificationsController extends BaseController {
if (isDefault) { if (isDefault) {
if (type == TYPE_STORIES) { if (type == TYPE_STORIES) {
editor.putBoolean("EnableAllStories", true); editor.putBoolean("EnableAllStories", true);
} else if (type == TYPE_REACTIONS_MESSAGES) {
editor.putBoolean("EnableReactionsMessages", true);
editor.putBoolean("EnableReactionsStories", true);
} else { } else {
editor.putInt(getGlobalNotificationsKey(type), 0); editor.putInt(getGlobalNotificationsKey(type), 0);
} }
@ -3550,6 +3645,8 @@ public class NotificationsController extends BaseController {
editor.putInt("priority_group", priority); editor.putInt("priority_group", priority);
} else if (type == TYPE_STORIES) { } else if (type == TYPE_STORIES) {
editor.putInt("priority_stories", priority); editor.putInt("priority_stories", priority);
} else if (type == TYPE_REACTIONS_MESSAGES || type == TYPE_REACTIONS_STORIES) {
editor.putInt("priority_react", priority);
} else { } else {
editor.putInt("priority_messages", priority); editor.putInt("priority_messages", priority);
} }
@ -3578,6 +3675,8 @@ public class NotificationsController extends BaseController {
editor.putInt("vibrate_group", vibrate ? 0 : 2); editor.putInt("vibrate_group", vibrate ? 0 : 2);
} else if (type == TYPE_STORIES) { } else if (type == TYPE_STORIES) {
editor.putInt("vibrate_stories", vibrate ? 0 : 2); editor.putInt("vibrate_stories", vibrate ? 0 : 2);
} else if (type == TYPE_REACTIONS_MESSAGES || type == TYPE_REACTIONS_STORIES) {
editor.putInt("vibrate_react", vibrate ? 0 : 2);
} else { } else {
editor.putInt("vibrate_messages", vibrate ? 0 : 2); editor.putInt("vibrate_messages", vibrate ? 0 : 2);
} }
@ -3600,6 +3699,8 @@ public class NotificationsController extends BaseController {
editor.putInt("GroupLed", channelLedColor); editor.putInt("GroupLed", channelLedColor);
} else if (type == TYPE_STORIES) { } else if (type == TYPE_STORIES) {
editor.putInt("StoriesLed", channelLedColor); editor.putInt("StoriesLed", channelLedColor);
} else if (type == TYPE_REACTIONS_STORIES || type == TYPE_REACTIONS_MESSAGES) {
editor.putInt("ReactionsLed", channelLedColor);
} else { } else {
editor.putInt("MessagesLed", channelLedColor); editor.putInt("MessagesLed", channelLedColor);
} }
@ -3816,7 +3917,7 @@ public class NotificationsController extends BaseController {
int notifyOverride = getNotifyOverride(preferences, override_dialog_id, topicId); int notifyOverride = getNotifyOverride(preferences, override_dialog_id, topicId);
boolean value; boolean value;
if (notifyOverride == -1) { if (notifyOverride == -1) {
value = isGlobalNotificationsEnabled(dialog_id, isChannel); value = isGlobalNotificationsEnabled(dialog_id, isChannel, lastMessageObject.isReactionPush, lastMessageObject.isReactionPush);
} else { } else {
value = notifyOverride != 2; value = notifyOverride != 2;
} }
@ -3846,6 +3947,9 @@ public class NotificationsController extends BaseController {
} else { } else {
name = chatName; name = chatName;
} }
if (lastMessageObject != null && (lastMessageObject.isReactionPush || lastMessageObject.isStoryReactionPush) && !preferences.getBoolean("EnableReactionsPreview", true)) {
name = LocaleController.getString("NotificationHiddenName", R.string.NotificationHiddenName);
}
String detailText; String detailText;
if (UserConfig.getActivatedAccountsCount() > 1) { if (UserConfig.getActivatedAccountsCount() > 1) {
@ -4001,7 +4105,19 @@ public class NotificationsController extends BaseController {
} }
boolean vibrateOnlyIfSilent = false; boolean vibrateOnlyIfSilent = false;
if (chatId != 0) { if (lastMessageObject != null && (lastMessageObject.isReactionPush || lastMessageObject.isStoryReactionPush)) {
long soundDocumentId = preferences.getLong("ReactionSoundDocId", 0);
if (soundDocumentId != 0) {
isInternalSoundFile = true;
soundPath = getMediaDataController().ringtoneDataStore.getSoundPath(soundDocumentId);
} else {
soundPath = preferences.getString("ReactionSoundPath", defaultPath);
}
vibrate = preferences.getInt("vibrate_react", 0);
importance = preferences.getInt("priority_react", 1);
ledColor = preferences.getInt("ReactionsLed", 0xff0000ff);
chatType = lastMessageObject.isStoryReactionPush ? TYPE_REACTIONS_STORIES : TYPE_REACTIONS_MESSAGES;
} else if (chatId != 0) {
if (isChannel) { if (isChannel) {
long soundDocumentId = preferences.getLong("ChannelSoundDocId", 0); long soundDocumentId = preferences.getLong("ChannelSoundDocId", 0);
if (soundDocumentId != 0) { if (soundDocumentId != 0) {
@ -4096,7 +4212,9 @@ public class NotificationsController extends BaseController {
intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (lastMessageObject.isStoryPush) { if (lastMessageObject.isStoryReactionPush) {
intent.putExtra("storyId", Math.abs(lastMessageObject.getId()));
} else if (lastMessageObject.isStoryPush) {
long[] peerIds = new long[storyPushMessages.size()]; long[] peerIds = new long[storyPushMessages.size()];
for (int i = 0; i < storyPushMessages.size(); ++i) { for (int i = 0; i < storyPushMessages.size(); ++i) {
peerIds[i] = storyPushMessages.get(i).dialogId; peerIds[i] = storyPushMessages.get(i).dialogId;
@ -4159,6 +4277,9 @@ public class NotificationsController extends BaseController {
if (lastMessageObject.isStoryPush) { if (lastMessageObject.isStoryPush) {
dismissIntent.putExtra("story", true); dismissIntent.putExtra("story", true);
} }
if (lastMessageObject.isStoryReactionPush) {
dismissIntent.putExtra("storyReaction", true);
}
mBuilder.setDeleteIntent(PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 1, dismissIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT)); mBuilder.setDeleteIntent(PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 1, dismissIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
} catch (Throwable e) { } catch (Throwable e) {
FileLog.e(e); FileLog.e(e);
@ -4342,6 +4463,8 @@ public class NotificationsController extends BaseController {
editor.putString("GlobalSound", ringtoneName); editor.putString("GlobalSound", ringtoneName);
} else if (chatType == TYPE_STORIES) { } else if (chatType == TYPE_STORIES) {
editor.putString("StoriesSound", ringtoneName); editor.putString("StoriesSound", ringtoneName);
} else if (chatType == TYPE_REACTIONS_MESSAGES || chatType == TYPE_REACTIONS_STORIES) {
editor.putString("ReactionSound", ringtoneName);
} }
if (chatType == TYPE_CHANNEL) { if (chatType == TYPE_CHANNEL) {
editor.putString("ChannelSoundPath", newSound); editor.putString("ChannelSoundPath", newSound);
@ -4351,6 +4474,8 @@ public class NotificationsController extends BaseController {
editor.putString("GlobalSoundPath", newSound); editor.putString("GlobalSoundPath", newSound);
} else if (chatType == TYPE_STORIES) { } else if (chatType == TYPE_STORIES) {
editor.putString("StoriesSoundPath", newSound); editor.putString("StoriesSoundPath", newSound);
} else if (chatType == TYPE_REACTIONS_MESSAGES || chatType == TYPE_REACTIONS_STORIES) {
editor.putString("ReactionSound", newSound);
} }
getNotificationsController().deleteNotificationChannelGlobalInternal(chatType, -1); getNotificationsController().deleteNotificationChannelGlobalInternal(chatType, -1);
} else { } else {
@ -4527,7 +4652,7 @@ public class NotificationsController extends BaseController {
photoPath = user.photo.photo_small; photoPath = user.photo.photo_small;
} }
} else if (!DialogObject.isEncryptedDialog(dialogId)) { } else if (!DialogObject.isEncryptedDialog(dialogId)) {
canReply = (lastMessageObject != null && !lastMessageObject.isReactionPush) && dialogId != 777000; canReply = (lastMessageObject != null && !lastMessageObject.isReactionPush && !lastMessageObject.isStoryReactionPush) && dialogId != 777000;
if (DialogObject.isUserDialog(dialogId)) { if (DialogObject.isUserDialog(dialogId)) {
user = getMessagesController().getUser(dialogId); user = getMessagesController().getUser(dialogId);
if (user == null) { if (user == null) {
@ -4605,6 +4730,11 @@ public class NotificationsController extends BaseController {
name = LocaleController.getString("SecretChatName", R.string.SecretChatName); name = LocaleController.getString("SecretChatName", R.string.SecretChatName);
photoPath = null; photoPath = null;
} }
if (lastMessageObject != null && lastMessageObject.isStoryReactionPush && !preferences.getBoolean("EnableReactionsPreview", true)) {
canReply = false;
name = LocaleController.getString("NotificationHiddenChatName", R.string.NotificationHiddenChatName);
photoPath = null;
}
if (waitingForPasscode) { if (waitingForPasscode) {
if (DialogObject.isChatDialog(dialogId)) { if (DialogObject.isChatDialog(dialogId)) {
@ -4964,7 +5094,9 @@ public class NotificationsController extends BaseController {
intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.addCategory(Intent.CATEGORY_LAUNCHER);
if (dialogKey.story) { if (lastMessageObject != null && lastMessageObject.isStoryReactionPush) {
intent.putExtra("storyId", Math.abs(lastMessageObject.getId()));
} else if (dialogKey.story) {
long[] peerIds = new long[storyPushMessages.size()]; long[] peerIds = new long[storyPushMessages.size()];
for (int i = 0; i < storyPushMessages.size(); ++i) { for (int i = 0; i < storyPushMessages.size(); ++i) {
peerIds[i] = storyPushMessages.get(i).dialogId; peerIds[i] = storyPushMessages.get(i).dialogId;
@ -5068,7 +5200,7 @@ public class NotificationsController extends BaseController {
if (wearReplyAction != null) { if (wearReplyAction != null) {
builder.addAction(wearReplyAction); builder.addAction(wearReplyAction);
} }
if (!waitingForPasscode && !dialogKey.story) { if (!waitingForPasscode && !dialogKey.story && (lastMessageObject == null || !lastMessageObject.isStoryReactionPush)) {
builder.addAction(readAction); builder.addAction(readAction);
} }
if (sortedDialogs.size() == 1 && !TextUtils.isEmpty(summary) && !dialogKey.story) { if (sortedDialogs.size() == 1 && !TextUtils.isEmpty(summary) && !dialogKey.story) {
@ -5395,7 +5527,7 @@ public class NotificationsController extends BaseController {
SharedPreferences.Editor editor = preferences.edit(); SharedPreferences.Editor editor = preferences.edit();
TLRPC.Dialog dialog = MessagesController.getInstance(UserConfig.selectedAccount).dialogs_dict.get(dialog_id); TLRPC.Dialog dialog = MessagesController.getInstance(UserConfig.selectedAccount).dialogs_dict.get(dialog_id);
if (setting == SETTING_MUTE_UNMUTE) { if (setting == SETTING_MUTE_UNMUTE) {
boolean defaultEnabled = isGlobalNotificationsEnabled(dialog_id); boolean defaultEnabled = isGlobalNotificationsEnabled(dialog_id, false, false);
if (defaultEnabled) { if (defaultEnabled) {
editor.remove("notify2_" + NotificationsController.getSharedPrefKey(dialog_id, topicId)); editor.remove("notify2_" + NotificationsController.getSharedPrefKey(dialog_id, topicId));
} else { } else {
@ -5513,9 +5645,36 @@ public class NotificationsController extends BaseController {
public final static int TYPE_PRIVATE = 1; public final static int TYPE_PRIVATE = 1;
public final static int TYPE_CHANNEL = 2; public final static int TYPE_CHANNEL = 2;
public final static int TYPE_STORIES = 3; public final static int TYPE_STORIES = 3;
public final static int TYPE_REACTIONS_MESSAGES = 4;
public final static int TYPE_REACTIONS_STORIES = 5;
public void updateServerNotificationsSettings(int type) { public void updateServerNotificationsSettings(int type) {
SharedPreferences preferences = getAccountInstance().getNotificationsSettings(); SharedPreferences preferences = getAccountInstance().getNotificationsSettings();
if (type == TYPE_REACTIONS_MESSAGES || type == TYPE_REACTIONS_STORIES) {
TLRPC.TL_account_setReactionsNotifySettings req = new TLRPC.TL_account_setReactionsNotifySettings();
req.settings = new TLRPC.TL_reactionsNotifySettings();
if (preferences.getBoolean("EnableReactionsMessages", true)) {
req.settings.flags |= 1;
if (preferences.getBoolean("EnableReactionsMessagesContacts", false)) {
req.settings.messages_notify_from = new TLRPC.TL_reactionNotificationsFromContacts();
} else {
req.settings.messages_notify_from = new TLRPC.TL_reactionNotificationsFromAll();
}
}
if (preferences.getBoolean("EnableReactionsStories", true)) {
req.settings.flags |= 2;
if (preferences.getBoolean("EnableReactionsStoriesContacts", false)) {
req.settings.stories_notify_from = new TLRPC.TL_reactionNotificationsFromContacts();
} else {
req.settings.stories_notify_from = new TLRPC.TL_reactionNotificationsFromAll();
}
}
req.settings.show_previews = preferences.getBoolean("EnableReactionsPreview", true);
req.settings.sound = getInputSound(preferences, "ReactionSound", "ReactionSoundDocId", "ReactionSoundPath");
getConnectionsManager().sendRequest(req, (response, error) -> { });
return;
}
TLRPC.TL_account_updateNotifySettings req = new TLRPC.TL_account_updateNotifySettings(); TLRPC.TL_account_updateNotifySettings req = new TLRPC.TL_account_updateNotifySettings();
req.settings = new TLRPC.TL_inputPeerNotifySettings(); req.settings = new TLRPC.TL_inputPeerNotifySettings();
req.settings.flags = 5; req.settings.flags = 5;
@ -5576,13 +5735,17 @@ public class NotificationsController extends BaseController {
} }
} }
public boolean isGlobalNotificationsEnabled(long dialogId) { public boolean isGlobalNotificationsEnabled(long dialogId, boolean isReaction, boolean isStoryReaction) {
return isGlobalNotificationsEnabled(dialogId, null); return isGlobalNotificationsEnabled(dialogId, null, isReaction, isStoryReaction);
} }
public boolean isGlobalNotificationsEnabled(long dialogId, Boolean forceChannel) { public boolean isGlobalNotificationsEnabled(long dialogId, Boolean forceChannel, boolean isReaction, boolean isStoryReaction) {
int type; int type;
if (DialogObject.isChatDialog(dialogId)) { if (isReaction) {
type = TYPE_REACTIONS_MESSAGES;
} else if (isStoryReaction) {
type = TYPE_REACTIONS_STORIES;
} else if (DialogObject.isChatDialog(dialogId)) {
if (forceChannel != null) { if (forceChannel != null) {
if (forceChannel) { if (forceChannel) {
type = TYPE_CHANNEL; type = TYPE_CHANNEL;
@ -5604,6 +5767,12 @@ public class NotificationsController extends BaseController {
} }
public boolean isGlobalNotificationsEnabled(int type) { public boolean isGlobalNotificationsEnabled(int type) {
if (type == TYPE_REACTIONS_MESSAGES) {
return getAccountInstance().getNotificationsSettings().getBoolean("EnableReactionsMessages", true);
}
if (type == TYPE_REACTIONS_STORIES) {
return getAccountInstance().getNotificationsSettings().getBoolean("EnableReactionsStories", true);
}
if (type == TYPE_STORIES) { if (type == TYPE_STORIES) {
return getAccountInstance().getNotificationsSettings().getBoolean("EnableAllStories", true); return getAccountInstance().getNotificationsSettings().getBoolean("EnableAllStories", true);
} }
@ -5631,7 +5800,7 @@ public class NotificationsController extends BaseController {
if (mute) { if (mute) {
NotificationsController.getInstance(currentAccount).muteUntil(dialog_id, topicId, Integer.MAX_VALUE); NotificationsController.getInstance(currentAccount).muteUntil(dialog_id, topicId, Integer.MAX_VALUE);
} else { } else {
boolean defaultEnabled = NotificationsController.getInstance(currentAccount).isGlobalNotificationsEnabled(dialog_id); boolean defaultEnabled = NotificationsController.getInstance(currentAccount).isGlobalNotificationsEnabled(dialog_id, false, false);
boolean override = topicId != 0; boolean override = topicId != 0;
SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
SharedPreferences.Editor editor = preferences.edit(); SharedPreferences.Editor editor = preferences.edit();

View file

@ -1,6 +1,8 @@
package org.telegram.messenger; package org.telegram.messenger;
import static org.telegram.messenger.NotificationsController.TYPE_PRIVATE; import static org.telegram.messenger.NotificationsController.TYPE_PRIVATE;
import static org.telegram.messenger.NotificationsController.TYPE_REACTIONS_MESSAGES;
import static org.telegram.messenger.NotificationsController.TYPE_REACTIONS_STORIES;
import android.content.SharedPreferences; import android.content.SharedPreferences;
@ -208,6 +210,10 @@ public class NotificationsSettingsFacade {
soundPref = "GlobalSound"; soundPref = "GlobalSound";
soundDocPref = "GlobalSoundDocId"; soundDocPref = "GlobalSoundDocId";
soundPathPref = "GlobalSoundPath"; soundPathPref = "GlobalSoundPath";
} else if (globalType == TYPE_REACTIONS_MESSAGES || globalType == TYPE_REACTIONS_STORIES) {
soundPref = "ReactionSound";
soundDocPref = "ReactionSoundDocId";
soundPathPref = "ReactionSoundPath";
} else { } else {
soundPref = "ChannelSound"; soundPref = "ChannelSound";
soundDocPref = "ChannelSoundDocId"; soundDocPref = "ChannelSoundDocId";

View file

@ -373,6 +373,8 @@ public class PushListenerController {
int msg_id; int msg_id;
if (custom.has("msg_id")) { if (custom.has("msg_id")) {
msg_id = custom.getInt("msg_id"); msg_id = custom.getInt("msg_id");
} else if (custom.has("story_id")) {
msg_id = custom.getInt("story_id");
} else { } else {
msg_id = 0; msg_id = 0;
} }
@ -1199,6 +1201,9 @@ public class PushListenerController {
} }
if (messageText != null) { if (messageText != null) {
TLRPC.TL_message messageOwner = new TLRPC.TL_message(); TLRPC.TL_message messageOwner = new TLRPC.TL_message();
if (loc_key.startsWith("REACT_STORY") && msg_id > 0) {
msg_id = -msg_id;
}
messageOwner.id = msg_id; messageOwner.id = msg_id;
messageOwner.random_id = random_id; messageOwner.random_id = random_id;
messageOwner.message = message1 != null ? message1 : messageText; messageOwner.message = message1 != null ? message1 : messageText;
@ -1243,7 +1248,8 @@ public class PushListenerController {
messageObject.messageOwner.reply_to.forum_topic = true; messageObject.messageOwner.reply_to.forum_topic = true;
messageObject.messageOwner.reply_to.reply_to_top_id = topicId; messageObject.messageOwner.reply_to.reply_to_top_id = topicId;
} }
messageObject.isReactionPush = loc_key.startsWith("REACT_") || loc_key.startsWith("CHAT_REACT_"); messageObject.isStoryReactionPush = loc_key.startsWith("REACT_STORY");
messageObject.isReactionPush = !messageObject.isStoryReactionPush && (loc_key.startsWith("REACT_") || loc_key.startsWith("CHAT_REACT_"));
messageObject.isStoryPush = loc_key.equals("STORY_NOTEXT") || loc_key.equals("STORY_HIDDEN_AUTHOR"); messageObject.isStoryPush = loc_key.equals("STORY_NOTEXT") || loc_key.equals("STORY_HIDDEN_AUTHOR");
messageObject.isStoryMentionPush = loc_key.equals("MESSAGE_STORY_MENTION"); messageObject.isStoryMentionPush = loc_key.equals("MESSAGE_STORY_MENTION");
messageObject.isStoryPushHidden = loc_key.equals("STORY_HIDDEN_AUTHOR"); messageObject.isStoryPushHidden = loc_key.equals("STORY_HIDDEN_AUTHOR");
@ -1288,107 +1294,117 @@ public class PushListenerController {
private static String getReactedText(String loc_key, Object[] args) { private static String getReactedText(String loc_key, Object[] args) {
switch (loc_key) { switch (loc_key) {
case "REACT_HIDDEN": {
return LocaleController.formatString(R.string.PushReactHidden, args);
}
case "REACT_TEXT": { case "REACT_TEXT": {
return LocaleController.formatString("PushReactText", R.string.PushReactText, args); return LocaleController.formatString(R.string.PushReactText, args);
} }
case "REACT_NOTEXT": { case "REACT_NOTEXT": {
return LocaleController.formatString("PushReactNoText", R.string.PushReactNoText, args); return LocaleController.formatString(R.string.PushReactNoText, args);
} }
case "REACT_PHOTO": { case "REACT_PHOTO": {
return LocaleController.formatString("PushReactPhoto", R.string.PushReactPhoto, args); return LocaleController.formatString(R.string.PushReactPhoto, args);
} }
case "REACT_VIDEO": { case "REACT_VIDEO": {
return LocaleController.formatString("PushReactVideo", R.string.PushReactVideo, args); return LocaleController.formatString(R.string.PushReactVideo, args);
} }
case "REACT_ROUND": { case "REACT_ROUND": {
return LocaleController.formatString("PushReactRound", R.string.PushReactRound, args); return LocaleController.formatString(R.string.PushReactRound, args);
} }
case "REACT_DOC": { case "REACT_DOC": {
return LocaleController.formatString("PushReactDoc", R.string.PushReactDoc, args); return LocaleController.formatString(R.string.PushReactDoc, args);
} }
case "REACT_STICKER": { case "REACT_STICKER": {
return LocaleController.formatString("PushReactSticker", R.string.PushReactSticker, args); return LocaleController.formatString(R.string.PushReactSticker, args);
} }
case "REACT_AUDIO": { case "REACT_AUDIO": {
return LocaleController.formatString("PushReactAudio", R.string.PushReactAudio, args); return LocaleController.formatString(R.string.PushReactAudio, args);
} }
case "REACT_CONTACT": { case "REACT_CONTACT": {
return LocaleController.formatString("PushReactContect", R.string.PushReactContect, args); return LocaleController.formatString(R.string.PushReactContect, args);
} }
case "REACT_GEO": { case "REACT_GEO": {
return LocaleController.formatString("PushReactGeo", R.string.PushReactGeo, args); return LocaleController.formatString(R.string.PushReactGeo, args);
} }
case "REACT_GEOLIVE": { case "REACT_GEOLIVE": {
return LocaleController.formatString("PushReactGeoLocation", R.string.PushReactGeoLocation, args); return LocaleController.formatString(R.string.PushReactGeoLocation, args);
} }
case "REACT_POLL": { case "REACT_POLL": {
return LocaleController.formatString("PushReactPoll", R.string.PushReactPoll, args); return LocaleController.formatString(R.string.PushReactPoll, args);
} }
case "REACT_QUIZ": { case "REACT_QUIZ": {
return LocaleController.formatString("PushReactQuiz", R.string.PushReactQuiz, args); return LocaleController.formatString(R.string.PushReactQuiz, args);
} }
case "REACT_GAME": { case "REACT_GAME": {
return LocaleController.formatString("PushReactGame", R.string.PushReactGame, args); return LocaleController.formatString(R.string.PushReactGame, args);
} }
case "REACT_INVOICE": { case "REACT_INVOICE": {
return LocaleController.formatString("PushReactInvoice", R.string.PushReactInvoice, args); return LocaleController.formatString(R.string.PushReactInvoice, args);
} }
case "REACT_GIF": { case "REACT_GIF": {
return LocaleController.formatString("PushReactGif", R.string.PushReactGif, args); return LocaleController.formatString(R.string.PushReactGif, args);
} }
case "REACT_GIVEAWAY": { case "REACT_GIVEAWAY": {
return LocaleController.formatString("NotificationReactGiveaway", R.string.NotificationReactGiveaway, args); return LocaleController.formatString(R.string.NotificationReactGiveaway, args);
} }
case "CHAT_REACT_GIVEAWAY": { case "CHAT_REACT_GIVEAWAY": {
return LocaleController.formatString("NotificationChatReactGiveaway", R.string.NotificationChatReactGiveaway, args); return LocaleController.formatString(R.string.NotificationChatReactGiveaway, args);
} }
case "CHAT_REACT_TEXT": { case "CHAT_REACT_TEXT": {
return LocaleController.formatString("PushChatReactText", R.string.PushChatReactText, args); return LocaleController.formatString(R.string.PushChatReactText, args);
} }
case "CHAT_REACT_NOTEXT": { case "CHAT_REACT_NOTEXT": {
return LocaleController.formatString("PushChatReactNotext", R.string.PushChatReactNotext, args); return LocaleController.formatString(R.string.PushChatReactNotext, args);
} }
case "CHAT_REACT_PHOTO": { case "CHAT_REACT_PHOTO": {
return LocaleController.formatString("PushChatReactPhoto", R.string.PushChatReactPhoto, args); return LocaleController.formatString(R.string.PushChatReactPhoto, args);
} }
case "CHAT_REACT_VIDEO": { case "CHAT_REACT_VIDEO": {
return LocaleController.formatString("PushChatReactVideo", R.string.PushChatReactVideo, args); return LocaleController.formatString(R.string.PushChatReactVideo, args);
} }
case "CHAT_REACT_ROUND": { case "CHAT_REACT_ROUND": {
return LocaleController.formatString("PushChatReactRound", R.string.PushChatReactRound, args); return LocaleController.formatString(R.string.PushChatReactRound, args);
} }
case "CHAT_REACT_DOC": { case "CHAT_REACT_DOC": {
return LocaleController.formatString("PushChatReactDoc", R.string.PushChatReactDoc, args); return LocaleController.formatString(R.string.PushChatReactDoc, args);
} }
case "CHAT_REACT_STICKER": { case "CHAT_REACT_STICKER": {
return LocaleController.formatString("PushChatReactSticker", R.string.PushChatReactSticker, args); return LocaleController.formatString(R.string.PushChatReactSticker, args);
} }
case "CHAT_REACT_AUDIO": { case "CHAT_REACT_AUDIO": {
return LocaleController.formatString("PushChatReactAudio", R.string.PushChatReactAudio, args); return LocaleController.formatString(R.string.PushChatReactAudio, args);
} }
case "CHAT_REACT_CONTACT": { case "CHAT_REACT_CONTACT": {
return LocaleController.formatString("PushChatReactContact", R.string.PushChatReactContact, args); return LocaleController.formatString(R.string.PushChatReactContact, args);
} }
case "CHAT_REACT_GEO": { case "CHAT_REACT_GEO": {
return LocaleController.formatString("PushChatReactGeo", R.string.PushChatReactGeo, args); return LocaleController.formatString(R.string.PushChatReactGeo, args);
} }
case "CHAT_REACT_GEOLIVE": { case "CHAT_REACT_GEOLIVE": {
return LocaleController.formatString("PushChatReactGeoLive", R.string.PushChatReactGeoLive, args); return LocaleController.formatString(R.string.PushChatReactGeoLive, args);
} }
case "CHAT_REACT_POLL": { case "CHAT_REACT_POLL": {
return LocaleController.formatString("PushChatReactPoll", R.string.PushChatReactPoll, args); return LocaleController.formatString(R.string.PushChatReactPoll, args);
} }
case "CHAT_REACT_QUIZ": { case "CHAT_REACT_QUIZ": {
return LocaleController.formatString("PushChatReactQuiz", R.string.PushChatReactQuiz, args); return LocaleController.formatString(R.string.PushChatReactQuiz, args);
} }
case "CHAT_REACT_GAME": { case "CHAT_REACT_GAME": {
return LocaleController.formatString("PushChatReactGame", R.string.PushChatReactGame, args); return LocaleController.formatString(R.string.PushChatReactGame, args);
} }
case "CHAT_REACT_INVOICE": { case "CHAT_REACT_INVOICE": {
return LocaleController.formatString("PushChatReactInvoice", R.string.PushChatReactInvoice, args); return LocaleController.formatString(R.string.PushChatReactInvoice, args);
} }
case "CHAT_REACT_GIF": { case "CHAT_REACT_GIF": {
return LocaleController.formatString("PushChatReactGif", R.string.PushChatReactGif, args); return LocaleController.formatString(R.string.PushChatReactGif, args);
}
/* stories */
case "REACT_STORY": {
return LocaleController.formatString(R.string.PushReactStory, args);
}
case "REACT_STORY_HIDDEN": {
return LocaleController.formatString(R.string.PushReactStoryHidden, args);
} }
} }
return null; return null;

View file

@ -760,6 +760,7 @@ public class SecretChatHelper extends BaseController {
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, newMsgObj.id, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, false); getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, newMsgObj.id, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, false);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer2, newMsgObj.id, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, false);
getSendMessagesHelper().processSentMessage(newMsgObj.id); getSendMessagesHelper().processSentMessage(newMsgObj.id);
getSendMessagesHelper().removeFromSendingMessages(newMsgObj.id, false); getSendMessagesHelper().removeFromSendingMessages(newMsgObj.id, false);
}); });

View file

@ -961,7 +961,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} else if (message.type == 1) { } else if (message.type == 1) {
if (media.file == null) { if (media.file == null) {
media.file = file; media.file = file;
if (media.thumb == null && message.photoSize != null && message.photoSize.location != null) { if (media.thumb == null && message.photoSize != null && message.photoSize.location != null && (message.obj == null || message.obj.videoEditedInfo == null || !message.obj.videoEditedInfo.isSticker)) {
performSendDelayedMessage(message); performSendDelayedMessage(message);
} else { } else {
performSendMessageRequest(message.sendRequest, message.obj, message.originalPath, null, message.parentObject, null, message.scheduled); performSendMessageRequest(message.sendRequest, message.obj, message.originalPath, null, message.parentObject, null, message.scheduled);
@ -2322,6 +2322,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
newMsgObj1.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; newMsgObj1.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
getMediaDataController().increasePeerRaiting(peer); getMediaDataController().increasePeerRaiting(peer);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, message.id, message, peer, 0L, existFlags, scheduleDate != 0); getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, message.id, message, peer, 0L, existFlags, scheduleDate != 0);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer2, oldId, message.id, message, peer, 0L, existFlags, scheduleDate != 0);
processSentMessage(oldId); processSentMessage(oldId);
removeFromSendingMessages(oldId, scheduleDate != 0); removeFromSendingMessages(oldId, scheduleDate != 0);
}); });
@ -2748,7 +2749,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
delayedMessage.originalPath = originalPath; delayedMessage.originalPath = originalPath;
delayedMessage.type = 2; delayedMessage.type = 2;
delayedMessage.obj = messageObject; delayedMessage.obj = messageObject;
if (!document.thumbs.isEmpty()) { if (!document.thumbs.isEmpty() && (videoEditedInfo == null || !videoEditedInfo.isSticker)) {
TLRPC.PhotoSize photoSize = document.thumbs.get(0); TLRPC.PhotoSize photoSize = document.thumbs.get(0);
if (!(photoSize instanceof TLRPC.TL_photoStrippedSize)) { if (!(photoSize instanceof TLRPC.TL_photoStrippedSize)) {
delayedMessage.photoSize = photoSize; delayedMessage.photoSize = photoSize;
@ -2966,7 +2967,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
return waitingForVote.get(key); return waitingForVote.get(key);
} }
public int sendVote(final MessageObject messageObject, final ArrayList<TLRPC.TL_pollAnswer> answers, final Runnable finishRunnable) { public int sendVote(final MessageObject messageObject, final ArrayList<TLRPC.PollAnswer> answers, final Runnable finishRunnable) {
if (messageObject == null) { if (messageObject == null) {
return 0; return 0;
} }
@ -2981,7 +2982,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
if (answers != null) { if (answers != null) {
options = new byte[answers.size()]; options = new byte[answers.size()];
for (int a = 0; a < answers.size(); a++) { for (int a = 0; a < answers.size(); a++) {
TLRPC.TL_pollAnswer answer = answers.get(a); TLRPC.PollAnswer answer = answers.get(a);
req.options.add(answer.option); req.options.add(answer.option);
options[a] = answer.option[0]; options[a] = answer.option[0];
} }
@ -5172,7 +5173,11 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} }
putToUploadingMessages(message.obj); putToUploadingMessages(message.obj);
} else { } else {
String location = FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE) + "/" + message.photoSize.location.volume_id + "_" + message.photoSize.location.local_id + ".jpg"; String ext = "jpg";
if (message.obj != null && message.obj.videoEditedInfo != null && message.obj.videoEditedInfo.isSticker) {
ext = "webp";
}
String location = FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE) + "/" + message.photoSize.location.volume_id + "_" + message.photoSize.location.local_id + "." + ext;
putToDelayedMessages(location, message); putToDelayedMessages(location, message);
getFileLoader().uploadFile(location, false, true, ConnectionsManager.FileTypePhoto); getFileLoader().uploadFile(location, false, true, ConnectionsManager.FileTypePhoto);
putToUploadingMessages(message.obj); putToUploadingMessages(message.obj);
@ -5860,6 +5865,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
getStatsController().incrementSentItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_MESSAGES, 1); getStatsController().incrementSentItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_MESSAGES, 1);
newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, grouped_id, existFlags, scheduled); getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, grouped_id, existFlags, scheduled);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer2, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, grouped_id, existFlags, scheduled);
getMessagesStorage().getStorageQueue().postRunnable(() -> { getMessagesStorage().getStorageQueue().postRunnable(() -> {
int mode = scheduled ? ChatActivity.MODE_SCHEDULED : 0; int mode = scheduled ? ChatActivity.MODE_SCHEDULED : 0;
if (newMsgObj.quick_reply_shortcut_id != 0 || newMsgObj.quick_reply_shortcut != null) { if (newMsgObj.quick_reply_shortcut_id != 0 || newMsgObj.quick_reply_shortcut != null) {
@ -5870,6 +5876,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
getMediaDataController().increasePeerRaiting(newMsgObj.dialog_id); getMediaDataController().increasePeerRaiting(newMsgObj.dialog_id);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, grouped_id, existFlags, scheduled); getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, grouped_id, existFlags, scheduled);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer2, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, grouped_id, existFlags, scheduled);
processSentMessage(oldId); processSentMessage(oldId);
removeFromSendingMessages(oldId, scheduled); removeFromSendingMessages(oldId, scheduled);
}); });
@ -6197,6 +6204,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
}); });
} else { } else {
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, scheduled); getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, scheduled);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer2, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, scheduled);
getMessagesStorage().getStorageQueue().postRunnable(() -> { getMessagesStorage().getStorageQueue().postRunnable(() -> {
int mode = scheduled ? ChatActivity.MODE_SCHEDULED : 0; int mode = scheduled ? ChatActivity.MODE_SCHEDULED : 0;
if (newMsgObj.quick_reply_shortcut_id != 0 || newMsgObj.quick_reply_shortcut != null) { if (newMsgObj.quick_reply_shortcut_id != 0 || newMsgObj.quick_reply_shortcut != null) {
@ -6207,6 +6215,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
getMediaDataController().increasePeerRaiting(newMsgObj.dialog_id); getMediaDataController().increasePeerRaiting(newMsgObj.dialog_id);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, scheduled); getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, scheduled);
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer2, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, scheduled);
processSentMessage(oldId); processSentMessage(oldId);
removeFromSendingMessages(oldId, scheduled); removeFromSendingMessages(oldId, scheduled);
}); });
@ -6419,7 +6428,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
newMsg.media.document.size = sentMessage.media.document.size; newMsg.media.document.size = sentMessage.media.document.size;
newMsg.media.document.mime_type = sentMessage.media.document.mime_type; newMsg.media.document.mime_type = sentMessage.media.document.mime_type;
if ((sentMessage.flags & TLRPC.MESSAGE_FLAG_FWD) == 0 && MessageObject.isOut(sentMessage) && !MessageObject.isQuickReply(sentMessage)) { if ((sentMessage.flags & TLRPC.MESSAGE_FLAG_FWD) == 0 && (MessageObject.isOut(sentMessage) || sentMessage.dialog_id == getUserConfig().getClientUserId()) && !MessageObject.isQuickReply(sentMessage)) {
if (MessageObject.isNewGifDocument(sentMessage.media.document)) { if (MessageObject.isNewGifDocument(sentMessage.media.document)) {
boolean save; boolean save;
if (MessageObject.isDocumentHasAttachedStickers(sentMessage.media.document)) { if (MessageObject.isDocumentHasAttachedStickers(sentMessage.media.document)) {
@ -8162,7 +8171,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
TLRPC.PhotoSize size = null; TLRPC.PhotoSize size = null;
if (thumb != null) { if (thumb != null) {
int side = isEncrypted || info.ttl != 0 ? 90 : Math.max(thumb.getWidth(), thumb.getHeight()); int side = isEncrypted || info.ttl != 0 ? 90 : Math.max(thumb.getWidth(), thumb.getHeight());
size = ImageLoader.scaleAndSaveImage(thumb, side, side, side > 90 ? 80 : 55, isEncrypted); size = ImageLoader.scaleAndSaveImage(null, thumb, videoEditedInfo != null && videoEditedInfo.isSticker ? Bitmap.CompressFormat.WEBP : Bitmap.CompressFormat.JPEG, false, side, side, side > 90 ? 80 : 55, isEncrypted, 0, 0, false);
if (size != null && size.location != null) { if (size != null && size.location != null) {
thumbKey = getKeyForPhotoSize(accountInstance, size, null, true, false); thumbKey = getKeyForPhotoSize(accountInstance, size, null, true, false);
} }

View file

@ -254,7 +254,7 @@ public class SharedConfig {
public static boolean forceDisableTabletMode; public static boolean forceDisableTabletMode;
public static boolean updateStickersOrderOnSend = true; public static boolean updateStickersOrderOnSend = true;
public static boolean bigCameraForRound; public static boolean bigCameraForRound;
public static boolean useCamera2; public static Boolean useCamera2Force;
public static boolean useSurfaceInStories; public static boolean useSurfaceInStories;
public static boolean photoViewerBlur = true; public static boolean photoViewerBlur = true;
public static boolean payByInvoice; public static boolean payByInvoice;
@ -643,7 +643,7 @@ public class SharedConfig {
updateStickersOrderOnSend = preferences.getBoolean("updateStickersOrderOnSend", true); updateStickersOrderOnSend = preferences.getBoolean("updateStickersOrderOnSend", true);
dayNightWallpaperSwitchHint = preferences.getInt("dayNightWallpaperSwitchHint", 0); dayNightWallpaperSwitchHint = preferences.getInt("dayNightWallpaperSwitchHint", 0);
bigCameraForRound = preferences.getBoolean("bigCameraForRound", false); bigCameraForRound = preferences.getBoolean("bigCameraForRound", false);
useCamera2 = preferences.getBoolean("useCamera2", BuildVars.DEBUG_VERSION); useCamera2Force = !preferences.contains("useCamera2Force") ? null : preferences.getBoolean("useCamera2Force", false);
useSurfaceInStories = preferences.getBoolean("useSurfaceInStories", Build.VERSION.SDK_INT >= 30); useSurfaceInStories = preferences.getBoolean("useSurfaceInStories", Build.VERSION.SDK_INT >= 30);
payByInvoice = preferences.getBoolean("payByInvoice", false); payByInvoice = preferences.getBoolean("payByInvoice", false);
photoViewerBlur = preferences.getBoolean("photoViewerBlur", true); photoViewerBlur = preferences.getBoolean("photoViewerBlur", true);
@ -1739,10 +1739,14 @@ public class SharedConfig {
.apply(); .apply();
} }
public static void toggleUseCamera2() { public static boolean isUsingCamera2(int currentAccount) {
return useCamera2Force == null ? !MessagesController.getInstance(currentAccount).androidDisableRoundCamera2 : useCamera2Force;
}
public static void toggleUseCamera2(int currentAccount) {
ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE) ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE)
.edit() .edit()
.putBoolean("useCamera2", useCamera2 = !useCamera2) .putBoolean("useCamera2", useCamera2Force = !isUsingCamera2(currentAccount))
.apply(); .apply();
} }

View file

@ -98,6 +98,7 @@ public class TranslateController extends BaseController {
messageObject != null && messageObject.messageOwner != null && messageObject != null && messageObject.messageOwner != null &&
!messageObject.isOutOwner() && !messageObject.isOutOwner() &&
!messageObject.isRestrictedMessage && !messageObject.isRestrictedMessage &&
!messageObject.isSponsored() &&
( (
messageObject.type == MessageObject.TYPE_TEXT || messageObject.type == MessageObject.TYPE_TEXT ||
messageObject.type == MessageObject.TYPE_VIDEO || messageObject.type == MessageObject.TYPE_VIDEO ||
@ -509,7 +510,10 @@ public class TranslateController extends BaseController {
final MessageObject finalMessageObject = messageObject; final MessageObject finalMessageObject = messageObject;
if (finalMessageObject.messageOwner.translatedText == null || !language.equals(finalMessageObject.messageOwner.translatedToLanguage)) { if (finalMessageObject.messageOwner.translatedText == null || !language.equals(finalMessageObject.messageOwner.translatedToLanguage)) {
NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.messageTranslating, finalMessageObject); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.messageTranslating, finalMessageObject);
pushToTranslate(finalMessageObject, language, (text, lang) -> { pushToTranslate(finalMessageObject, language, (id, text, lang) -> {
if (finalMessageObject.getId() != id) {
FileLog.e("wtf, asked to translate " + finalMessageObject.getId() + " but got " + id + "!");
}
finalMessageObject.messageOwner.translatedToLanguage = lang; finalMessageObject.messageOwner.translatedToLanguage = lang;
finalMessageObject.messageOwner.translatedText = text; finalMessageObject.messageOwner.translatedText = text;
if (keepReply) { if (keepReply) {
@ -715,7 +719,7 @@ public class TranslateController extends BaseController {
Runnable runnable; Runnable runnable;
ArrayList<Integer> messageIds = new ArrayList<>(); ArrayList<Integer> messageIds = new ArrayList<>();
ArrayList<TLRPC.TL_textWithEntities> messageTexts = new ArrayList<>(); ArrayList<TLRPC.TL_textWithEntities> messageTexts = new ArrayList<>();
ArrayList<Utilities.Callback2<TLRPC.TL_textWithEntities, String>> callbacks = new ArrayList<>(); ArrayList<Utilities.Callback3<Integer, TLRPC.TL_textWithEntities, String>> callbacks = new ArrayList<>();
String language; String language;
int delay = GROUPING_TRANSLATIONS_TIMEOUT; int delay = GROUPING_TRANSLATIONS_TIMEOUT;
@ -727,9 +731,9 @@ public class TranslateController extends BaseController {
private void pushToTranslate( private void pushToTranslate(
MessageObject message, MessageObject message,
String language, String language,
Utilities.Callback2<TLRPC.TL_textWithEntities, String> callback Utilities.Callback3<Integer, TLRPC.TL_textWithEntities, String> callback
) { ) {
if (message == null || callback == null) { if (message == null || message.getId() < 0 || callback == null) {
return; return;
} }
@ -779,6 +783,7 @@ public class TranslateController extends BaseController {
source.text = message.messageOwner.message; source.text = message.messageOwner.message;
source.entities = message.messageOwner.entities; source.entities = message.messageOwner.entities;
} }
FileLog.d("pending translation +" + message.getId() + " message");
pendingTranslation.messageTexts.add(source); pendingTranslation.messageTexts.add(source);
pendingTranslation.callbacks.add(callback); pendingTranslation.callbacks.add(callback);
pendingTranslation.language = language; pendingTranslation.language = language;
@ -803,7 +808,7 @@ public class TranslateController extends BaseController {
final int reqId = getConnectionsManager().sendRequest(req, (res, err) -> AndroidUtilities.runOnUIThread(() -> { final int reqId = getConnectionsManager().sendRequest(req, (res, err) -> AndroidUtilities.runOnUIThread(() -> {
final ArrayList<Integer> ids; final ArrayList<Integer> ids;
final ArrayList<Utilities.Callback2<TLRPC.TL_textWithEntities, String>> callbacks; final ArrayList<Utilities.Callback3<Integer, TLRPC.TL_textWithEntities, String>> callbacks;
final ArrayList<TLRPC.TL_textWithEntities> texts; final ArrayList<TLRPC.TL_textWithEntities> texts;
synchronized (TranslateController.this) { synchronized (TranslateController.this) {
ids = pendingTranslation1.messageIds; ids = pendingTranslation1.messageIds;
@ -814,14 +819,14 @@ public class TranslateController extends BaseController {
ArrayList<TLRPC.TL_textWithEntities> translated = ((TLRPC.TL_messages_translateResult) res).result; ArrayList<TLRPC.TL_textWithEntities> translated = ((TLRPC.TL_messages_translateResult) res).result;
final int count = Math.min(callbacks.size(), translated.size()); final int count = Math.min(callbacks.size(), translated.size());
for (int i = 0; i < count; ++i) { for (int i = 0; i < count; ++i) {
callbacks.get(i).run(TranslateAlert2.preprocess(texts.get(i), translated.get(i)), pendingTranslation1.language); callbacks.get(i).run(ids.get(i), TranslateAlert2.preprocess(texts.get(i), translated.get(i)), pendingTranslation1.language);
} }
} else if (err != null && "TO_LANG_INVALID".equals(err.text)) { } else if (err != null && "TO_LANG_INVALID".equals(err.text)) {
toggleTranslatingDialog(dialogId, false); toggleTranslatingDialog(dialogId, false);
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.showBulletin, Bulletin.TYPE_ERROR, LocaleController.getString("TranslationFailedAlert2", R.string.TranslationFailedAlert2)); NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.showBulletin, Bulletin.TYPE_ERROR, LocaleController.getString("TranslationFailedAlert2", R.string.TranslationFailedAlert2));
} else { } else {
for (int i = 0; i < callbacks.size(); ++i) { for (int i = 0; i < callbacks.size(); ++i) {
callbacks.get(i).run(null, pendingTranslation1.language); callbacks.get(i).run(ids.get(i), null, pendingTranslation1.language);
} }
} }
synchronized (TranslateController.this) { synchronized (TranslateController.this) {

View file

@ -159,7 +159,7 @@ public class UserConfig extends BaseController {
editor.putBoolean("syncContacts", syncContacts); editor.putBoolean("syncContacts", syncContacts);
editor.putBoolean("suggestContacts", suggestContacts); editor.putBoolean("suggestContacts", suggestContacts);
editor.putBoolean("hasSecureData", hasSecureData); editor.putBoolean("hasSecureData", hasSecureData);
editor.putBoolean("notificationsSettingsLoaded3", notificationsSettingsLoaded); editor.putBoolean("notificationsSettingsLoaded4", notificationsSettingsLoaded);
editor.putBoolean("notificationsSignUpSettingsLoaded", notificationsSignUpSettingsLoaded); editor.putBoolean("notificationsSignUpSettingsLoaded", notificationsSignUpSettingsLoaded);
editor.putLong("autoDownloadConfigLoadTime", autoDownloadConfigLoadTime); editor.putLong("autoDownloadConfigLoadTime", autoDownloadConfigLoadTime);
editor.putBoolean("hasValidDialogLoadIds", hasValidDialogLoadIds); editor.putBoolean("hasValidDialogLoadIds", hasValidDialogLoadIds);
@ -302,7 +302,7 @@ public class UserConfig extends BaseController {
syncContacts = preferences.getBoolean("syncContacts", true); syncContacts = preferences.getBoolean("syncContacts", true);
suggestContacts = preferences.getBoolean("suggestContacts", true); suggestContacts = preferences.getBoolean("suggestContacts", true);
hasSecureData = preferences.getBoolean("hasSecureData", false); hasSecureData = preferences.getBoolean("hasSecureData", false);
notificationsSettingsLoaded = preferences.getBoolean("notificationsSettingsLoaded3", false); notificationsSettingsLoaded = preferences.getBoolean("notificationsSettingsLoaded4", false);
notificationsSignUpSettingsLoaded = preferences.getBoolean("notificationsSignUpSettingsLoaded", false); notificationsSignUpSettingsLoaded = preferences.getBoolean("notificationsSignUpSettingsLoaded", false);
autoDownloadConfigLoadTime = preferences.getLong("autoDownloadConfigLoadTime", 0); autoDownloadConfigLoadTime = preferences.getLong("autoDownloadConfigLoadTime", 0);
hasValidDialogLoadIds = preferences.contains("2dialogsLoadOffsetId") || preferences.getBoolean("hasValidDialogLoadIds", false); hasValidDialogLoadIds = preferences.contains("2dialogsLoadOffsetId") || preferences.getBoolean("hasValidDialogLoadIds", false);

View file

@ -581,6 +581,10 @@ public class Utilities {
public ReturnType run(T arg, T2 arg2, T3 arg3, T4 arg4, T5 arg5); 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) { public static <Key, Value> Value getOrDefault(HashMap<Key, Value> map, Key key, Value defaultValue) {
Value v = map.get(key); Value v = map.get(key);
if (v == null) { if (v == null) {

View file

@ -153,6 +153,7 @@ public class VideoEditedInfo {
public float textViewHeight; public float textViewHeight;
public float textViewX; public float textViewX;
public float textViewY; public float textViewY;
public boolean customTextView;
public TLRPC.Document document; public TLRPC.Document document;
public Object parentObject; public Object parentObject;

View file

@ -317,7 +317,7 @@ public class Browser {
String token = "autologin_token=" + URLEncoder.encode(AccountInstance.getInstance(UserConfig.selectedAccount).getMessagesController().autologinToken, "UTF-8"); String token = "autologin_token=" + URLEncoder.encode(AccountInstance.getInstance(UserConfig.selectedAccount).getMessagesController().autologinToken, "UTF-8");
String url = uri.toString(); String url = uri.toString();
int idx = url.indexOf("://"); int idx = url.indexOf("://");
String path = idx >= 0 ? url.substring(idx + 3) : url; String path = idx >= 0 && idx <= 5 && !url.substring(0, idx).contains(".") ? url.substring(idx + 3) : url;
String fragment = uri.getEncodedFragment(); String fragment = uri.getEncodedFragment();
String finalPath = fragment == null ? path : path.substring(0, path.indexOf("#" + fragment)); String finalPath = fragment == null ? path : path.substring(0, path.indexOf("#" + fragment));
if (finalPath.indexOf('?') >= 0) { if (finalPath.indexOf('?') >= 0) {

View file

@ -21,6 +21,7 @@ import android.os.Build;
import android.os.Handler; import android.os.Handler;
import android.os.HandlerThread; import android.os.HandlerThread;
import android.util.Log; import android.util.Log;
import android.util.Range;
import android.util.Size; import android.util.Size;
import android.util.SizeF; import android.util.SizeF;
import android.view.Surface; import android.view.Surface;
@ -475,6 +476,11 @@ public class Camera2Session {
captureRequestBuilder.set(CaptureRequest.CONTROL_SCENE_MODE, isFront ? CameraMetadata.CONTROL_SCENE_MODE_NIGHT_PORTRAIT : CameraMetadata.CONTROL_SCENE_MODE_NIGHT); captureRequestBuilder.set(CaptureRequest.CONTROL_SCENE_MODE, isFront ? CameraMetadata.CONTROL_SCENE_MODE_NIGHT_PORTRAIT : CameraMetadata.CONTROL_SCENE_MODE_NIGHT);
} }
if (recordingVideo) {
captureRequestBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, new Range<Integer>(30, 60));
captureRequestBuilder.set(CaptureRequest.CONTROL_CAPTURE_INTENT, CaptureRequest.CONTROL_CAPTURE_INTENT_VIDEO_RECORD);
}
if (sensorSize != null && Math.abs(currentZoom - 1f) >= 0.01f) { if (sensorSize != null && Math.abs(currentZoom - 1f) >= 0.01f) {
final int centerX = sensorSize.width() / 2; final int centerX = sensorSize.width() / 2;
final int centerY = sensorSize.height() / 2; final int centerY = sensorSize.height() / 2;

View file

@ -42,8 +42,6 @@ import android.os.Looper;
import android.os.Message; import android.os.Message;
import android.os.VibrationEffect; import android.os.VibrationEffect;
import android.os.Vibrator; import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity; import android.view.Gravity;
import android.view.HapticFeedbackConstants; import android.view.HapticFeedbackConstants;
import android.view.Surface; import android.view.Surface;
@ -55,9 +53,6 @@ import android.widget.ImageView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.core.graphics.ColorUtils; import androidx.core.graphics.ColorUtils;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import com.google.zxing.common.detector.MathUtils;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ApplicationLoader;
@ -66,9 +61,9 @@ import org.telegram.messenger.DispatchQueue;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.messenger.ImageLoader; import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.SharedConfig; import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.messenger.video.MP4Builder; import org.telegram.messenger.video.MP4Builder;
import org.telegram.messenger.video.MediaCodecVideoConvertor; import org.telegram.messenger.video.MediaCodecVideoConvertor;
@ -121,7 +116,7 @@ public class CameraView extends FrameLayout implements TextureView.SurfaceTextur
private int focusAreaSize; private int focusAreaSize;
private Drawable thumbDrawable; private Drawable thumbDrawable;
private final boolean useCamera2 = false && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && SharedConfig.useCamera2; private final boolean useCamera2 = false && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && SharedConfig.isUsingCamera2(UserConfig.selectedAccount);
private final CameraSessionWrapper[] cameraSession = new CameraSessionWrapper[2]; private final CameraSessionWrapper[] cameraSession = new CameraSessionWrapper[2];
private CameraSessionWrapper cameraSessionRecording; private CameraSessionWrapper cameraSessionRecording;

View file

@ -292,9 +292,12 @@ public final class ExtendedDefaultDataSource implements DataSource {
return encryptedFileDataSource; return encryptedFileDataSource;
} }
private FileStreamLoadOperation streamLoadOperation;
private DataSource getStreamDataSource() { private DataSource getStreamDataSource() {
FileStreamLoadOperation streamLoadOperation = new FileStreamLoadOperation(); if (streamLoadOperation == null) {
streamLoadOperation = new FileStreamLoadOperation();
addListenersToDataSource(streamLoadOperation); addListenersToDataSource(streamLoadOperation);
}
return streamLoadOperation; return streamLoadOperation;
} }

View file

@ -53,7 +53,7 @@ public class MediaCodecVideoConvertor {
public boolean convertVideo(ConvertVideoParams convertVideoParams) { public boolean convertVideo(ConvertVideoParams convertVideoParams) {
if (convertVideoParams.isSticker) { if (convertVideoParams.isSticker) {
return WebmEncoder.convert(convertVideoParams); return WebmEncoder.convert(convertVideoParams, 0);
} }
this.callback = convertVideoParams.callback; this.callback = convertVideoParams.callback;
return convertVideoInternal(convertVideoParams, false, 0); return convertVideoInternal(convertVideoParams, false, 0);

View file

@ -15,6 +15,7 @@ import android.opengl.GLES20;
import android.opengl.GLUtils; import android.opengl.GLUtils;
import android.os.Build; import android.os.Build;
import android.text.Layout; import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString; import android.text.SpannableString;
import android.text.Spanned; import android.text.Spanned;
import android.text.TextUtils; import android.text.TextUtils;
@ -70,10 +71,12 @@ public class WebmEncoder {
public static native void stop(long ptr); public static native void stop(long ptr);
public static boolean convert(MediaCodecVideoConvertor.ConvertVideoParams params) { public static boolean convert(MediaCodecVideoConvertor.ConvertVideoParams params, int triesLeft) {
final int W = params.resultWidth; final int W = params.resultWidth;
final int H = params.resultHeight; final int H = params.resultHeight;
final long maxFileSize = 255 * 1024;
final long ptr = createEncoder(params.cacheFile.getAbsolutePath(), W, H, params.framerate, params.bitrate); final long ptr = createEncoder(params.cacheFile.getAbsolutePath(), W, H, params.framerate, params.bitrate);
if (ptr == 0) { if (ptr == 0) {
return true; return true;
@ -102,7 +105,7 @@ public class WebmEncoder {
} }
if (params.callback != null) { if (params.callback != null) {
params.callback.didWriteData(params.cacheFile.length(), (float) frame / framesCount); params.callback.didWriteData(Math.min(maxFileSize, params.cacheFile.length()), (float) frame / framesCount);
} }
if (frame % 3 == 0 && params.callback != null) { if (frame % 3 == 0 && params.callback != null) {
@ -119,11 +122,20 @@ public class WebmEncoder {
} }
} }
if (params.callback != null) { long fileSize = params.cacheFile.length();
params.callback.didWriteData(params.cacheFile.length(), 1f); if (triesLeft > 0 && fileSize > maxFileSize) {
int oldBitrate = params.bitrate;
params.bitrate *= ((float) maxFileSize / fileSize) * .9f;
params.cacheFile.delete();
FileLog.d("webm encoded too much, got " + fileSize + ", old bitrate = " + oldBitrate + " new bitrate = " + params.bitrate);
return convert(params, triesLeft - 1);
} }
FileLog.d("webm encoded to " + params.cacheFile + " with size=" + params.cacheFile.length()); if (params.callback != null) {
params.callback.didWriteData(fileSize, 1f);
}
FileLog.d("webm encoded to " + params.cacheFile + " with size=" + fileSize + " triesLeft=" + triesLeft);
return error; return error;
} }
@ -139,11 +151,17 @@ public class WebmEncoder {
private final Paint clearPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private final Paint clearPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); private final Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
private final Path clipPath;
public FrameDrawer(MediaCodecVideoConvertor.ConvertVideoParams params) { public FrameDrawer(MediaCodecVideoConvertor.ConvertVideoParams params) {
this.W = params.resultWidth; this.W = params.resultWidth;
this.H = params.resultHeight; this.H = params.resultHeight;
this.fps = params.framerate; this.fps = params.framerate;
clipPath = new Path();
RectF bounds = new RectF(0, 0, W, H);
clipPath.addRoundRect(bounds, W * .125f, H * .125f, Path.Direction.CW);
photo = BitmapFactory.decodeFile(params.videoPath); photo = BitmapFactory.decodeFile(params.videoPath);
mediaEntities.addAll(params.mediaEntities); mediaEntities.addAll(params.mediaEntities);
@ -165,6 +183,8 @@ public class WebmEncoder {
public void draw(Canvas canvas, int frame) { public void draw(Canvas canvas, int frame) {
canvas.drawPaint(clearPaint); canvas.drawPaint(clearPaint);
canvas.save();
canvas.clipPath(clipPath);
if (photo != null) { if (photo != null) {
canvas.drawBitmap(photo, 0, 0, null); canvas.drawBitmap(photo, 0, 0, null);
} }
@ -173,6 +193,7 @@ public class WebmEncoder {
VideoEditedInfo.MediaEntity entity = mediaEntities.get(a); VideoEditedInfo.MediaEntity entity = mediaEntities.get(a);
drawEntity(canvas, entity, entity.color, time); drawEntity(canvas, entity, entity.color, time);
} }
canvas.restore();
} }
private void drawEntity(Canvas canvas, VideoEditedInfo.MediaEntity entity, int textColor, long time) { private void drawEntity(Canvas canvas, VideoEditedInfo.MediaEntity entity, int textColor, long time) {
@ -231,7 +252,7 @@ public class WebmEncoder {
editText.setTypeface(typeface); editText.setTypeface(typeface);
} }
editText.setTextSize(TypedValue.COMPLEX_UNIT_PX, entity.fontSize); editText.setTextSize(TypedValue.COMPLEX_UNIT_PX, entity.fontSize);
SpannableString text = new SpannableString(entity.text); CharSequence text = new SpannableString(entity.text);
for (VideoEditedInfo.EmojiEntity e : entity.entities) { for (VideoEditedInfo.EmojiEntity e : entity.entities) {
if (e.documentAbsolutePath == null) { if (e.documentAbsolutePath == null) {
continue; continue;
@ -267,17 +288,19 @@ public class WebmEncoder {
initStickerEntity(e.entity); initStickerEntity(e.entity);
} }
}; };
text.setSpan(span, e.offset, e.offset + e.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ((Spannable) text).setSpan(span, e.offset, e.offset + e.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} }
editText.setText(Emoji.replaceEmoji(text, editText.getPaint().getFontMetricsInt(), (int) (editText.getTextSize() * .8f), false)); text = Emoji.replaceEmoji(text, editText.getPaint().getFontMetricsInt(), (int) (editText.getTextSize() * .8f), false);
editText.setTextColor(entity.color); if (text instanceof Spanned) {
CharSequence text2 = editText.getText(); Emoji.EmojiSpan[] spans = ((Spanned) text).getSpans(0, text.length(), Emoji.EmojiSpan.class);
if (text2 instanceof Spanned) { if (spans != null) {
Emoji.EmojiSpan[] spans = ((Spanned) text2).getSpans(0, text2.length(), Emoji.EmojiSpan.class);
for (int i = 0; i < spans.length; ++i) { for (int i = 0; i < spans.length; ++i) {
spans[i].scale = .85f; spans[i].scale = .85f;
} }
} }
}
editText.setText(text);
editText.setTextColor(entity.color);
int gravity; int gravity;
@ -365,11 +388,11 @@ public class WebmEncoder {
entity.bitmap = Bitmap.createBitmap(entity.W, entity.H, Bitmap.Config.ARGB_8888); entity.bitmap = Bitmap.createBitmap(entity.W, entity.H, Bitmap.Config.ARGB_8888);
entity.metadata = new int[3]; entity.metadata = new int[3];
entity.ptr = RLottieDrawable.create(entity.text, null, entity.W, entity.H, entity.metadata, false, null, false, 0); entity.ptr = RLottieDrawable.create(entity.text, null, entity.W, entity.H, entity.metadata, false, null, false, 0);
entity.framesPerDraw = entity.metadata[1] / fps; entity.framesPerDraw = (float) entity.metadata[1] / fps;
} else if ((entity.subType & 4) != 0) { } else if ((entity.subType & 4) != 0) {
entity.looped = false; entity.looped = false;
entity.animatedFileDrawable = new AnimatedFileDrawable(new File(entity.text), true, 0, 0, null, null, null, 0, UserConfig.selectedAccount, true, 512, 512, null); entity.animatedFileDrawable = new AnimatedFileDrawable(new File(entity.text), true, 0, 0, null, null, null, 0, UserConfig.selectedAccount, true, 512, 512, null);
entity.framesPerDraw = entity.animatedFileDrawable.getFps() / fps; entity.framesPerDraw = (float) entity.animatedFileDrawable.getFps() / fps;
entity.currentFrame = 1; entity.currentFrame = 1;
entity.animatedFileDrawable.getNextFrame(true); entity.animatedFileDrawable.getNextFrame(true);
if (entity.type == VideoEditedInfo.MediaEntity.TYPE_ROUND) { if (entity.type == VideoEditedInfo.MediaEntity.TYPE_ROUND) {
@ -445,12 +468,12 @@ public class WebmEncoder {
if (bitmap != null) { if (bitmap != null) {
entity.matrix.postScale(1f / bitmap.getWidth(), 1f / bitmap.getHeight()); entity.matrix.postScale(1f / bitmap.getWidth(), 1f / bitmap.getHeight());
} }
if ((entity.subType & 2) != 0) { if (entity.type != VideoEditedInfo.MediaEntity.TYPE_TEXT && (entity.subType & 2) != 0) {
entity.matrix.postScale(-1, 1, .5f, .5f); entity.matrix.postScale(-1, 1, .5f, .5f);
} }
entity.matrix.postScale(entity.width * W, entity.height * H); entity.matrix.postScale(entity.width * W, entity.height * H);
entity.matrix.postTranslate(entity.x * W, entity.y * H); entity.matrix.postTranslate(entity.x * W, entity.y * H);
entity.matrix.postRotate((float) (-entity.rotation / Math.PI * 180), (entity.x + entity.width) * W, (entity.x + entity.height) * H); entity.matrix.postRotate((float) (-entity.rotation / Math.PI * 180), (entity.x + entity.width / 2f) * W, (entity.y + entity.height / 2f) * H);
} }
Path path; Path path;

File diff suppressed because it is too large Load diff

View file

@ -780,13 +780,11 @@ public class TL_stats {
} }
public static class TL_broadcastRevenueStats extends TLObject { public static class TL_broadcastRevenueStats extends TLObject {
public static final int constructor = 0xd07b4bad; public static final int constructor = 0x5407e297;
public StatsGraph top_hours_graph; public StatsGraph top_hours_graph;
public StatsGraph revenue_graph; public StatsGraph revenue_graph;
public long current_balance; public TLRPC.TL_broadcastRevenueBalances balances;
public long available_balance;
public long overall_revenue;
public double usd_rate; public double usd_rate;
public static TL_broadcastRevenueStats TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { public static TL_broadcastRevenueStats TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) {
@ -807,9 +805,7 @@ public class TL_stats {
public void readParams(AbstractSerializedData stream, boolean exception) { public void readParams(AbstractSerializedData stream, boolean exception) {
top_hours_graph = StatsGraph.TLdeserialize(stream, stream.readInt32(exception), exception); top_hours_graph = StatsGraph.TLdeserialize(stream, stream.readInt32(exception), exception);
revenue_graph = StatsGraph.TLdeserialize(stream, stream.readInt32(exception), exception); revenue_graph = StatsGraph.TLdeserialize(stream, stream.readInt32(exception), exception);
current_balance = stream.readInt64(exception); balances = TLRPC.TL_broadcastRevenueBalances.TLdeserialize(stream, stream.readInt32(exception), exception);
available_balance = stream.readInt64(exception);
overall_revenue = stream.readInt64(exception);
usd_rate = stream.readDouble(exception); usd_rate = stream.readDouble(exception);
} }
@ -818,9 +814,7 @@ public class TL_stats {
stream.writeInt32(constructor); stream.writeInt32(constructor);
top_hours_graph.serializeToStream(stream); top_hours_graph.serializeToStream(stream);
revenue_graph.serializeToStream(stream); revenue_graph.serializeToStream(stream);
stream.writeInt64(current_balance); balances.serializeToStream(stream);
stream.writeInt64(available_balance);
stream.writeInt64(overall_revenue);
stream.writeDouble(usd_rate); stream.writeDouble(usd_rate);
} }
} }

View file

@ -736,10 +736,12 @@ public class TL_stories {
} }
public static class TL_stories_stories extends TLObject { public static class TL_stories_stories extends TLObject {
public static final int constructor = 0x5dd8c3c8; public static final int constructor = 0x63c3dd0a;
public int flags;
public int count; public int count;
public ArrayList<StoryItem> stories = new ArrayList<>(); public ArrayList<StoryItem> stories = new ArrayList<>();
public ArrayList<Integer> pinned_to_top = new ArrayList<>();
public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.Chat> chats = new ArrayList<>();
public ArrayList<TLRPC.User> users = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>();
@ -757,6 +759,7 @@ public class TL_stories {
} }
public void readParams(AbstractSerializedData stream, boolean exception) { public void readParams(AbstractSerializedData stream, boolean exception) {
flags = stream.readInt32(exception);
count = stream.readInt32(exception); count = stream.readInt32(exception);
int magic = stream.readInt32(exception); int magic = stream.readInt32(exception);
if (magic != 0x1cb5c415) { if (magic != 0x1cb5c415) {
@ -773,6 +776,19 @@ public class TL_stories {
} }
stories.add(object); 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); magic = stream.readInt32(exception);
if (magic != 0x1cb5c415) { if (magic != 0x1cb5c415) {
if (exception) { if (exception) {
@ -807,6 +823,7 @@ public class TL_stories {
public void serializeToStream(AbstractSerializedData stream) { public void serializeToStream(AbstractSerializedData stream) {
stream.writeInt32(constructor); stream.writeInt32(constructor);
stream.writeInt32(flags);
stream.writeInt32(count); stream.writeInt32(count);
stream.writeInt32(0x1cb5c415); stream.writeInt32(0x1cb5c415);
int count = stories.size(); int count = stories.size();
@ -814,6 +831,14 @@ public class TL_stories {
for (int a = 0; a < count; a++) { for (int a = 0; a < count; a++) {
stories.get(a).serializeToStream(stream); 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); stream.writeInt32(0x1cb5c415);
count = chats.size(); count = chats.size();
stream.writeInt32(count); stream.writeInt32(count);
@ -3345,4 +3370,26 @@ public class TL_stories {
stream.writeInt32(limit); 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));
}
}
}
} }

View file

@ -54,6 +54,7 @@ import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.SharedConfig; import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Components.BackButtonMenu; import org.telegram.ui.Components.BackButtonMenu;
import org.telegram.ui.bots.BotWebViewSheet; import org.telegram.ui.bots.BotWebViewSheet;
import org.telegram.ui.Components.Bulletin; import org.telegram.ui.Components.Bulletin;
@ -1622,6 +1623,10 @@ public class ActionBarLayout extends FrameLayout implements INavigationLayout, F
} }
onFragmentStackChanged("addFragmentToStack " + position); onFragmentStackChanged("addFragmentToStack " + position);
} else { } else {
if (position == INavigationLayout.FORCE_ATTACH_VIEW_AS_FIRST) {
position = 0;
attachViewTo(fragment, position);
}
fragmentsStack.add(position, fragment); fragmentsStack.add(position, fragment);
onFragmentStackChanged("addFragmentToStack"); onFragmentStackChanged("addFragmentToStack");
} }
@ -1663,6 +1668,35 @@ public class ActionBarLayout extends FrameLayout implements INavigationLayout, F
fragment.attachStoryViewer(containerView); fragment.attachStoryViewer(containerView);
} }
private void attachViewTo(BaseFragment fragment, int position) {
View fragmentView = fragment.fragmentView;
if (fragmentView == null) {
fragmentView = fragment.createView(parentActivity);
} else {
ViewGroup parent = (ViewGroup) fragmentView.getParent();
if (parent != null) {
fragment.onRemoveFromParent();
parent.removeView(fragmentView);
}
}
if (!fragment.hasOwnBackground && fragmentView.getBackground() == null) {
fragmentView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
}
containerView.addView(fragmentView, Utilities.clamp(position, containerView.getChildCount(), 0), LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
if (fragment.actionBar != null && fragment.actionBar.shouldAddToContainer()) {
if (removeActionBarExtraHeight) {
fragment.actionBar.setOccupyStatusBar(false);
}
ViewGroup parent = (ViewGroup) fragment.actionBar.getParent();
if (parent != null) {
parent.removeView(fragment.actionBar);
}
containerView.addView(fragment.actionBar);
fragment.actionBar.setTitleOverlayText(titleOverlayText, titleOverlayTextId, overlayAction);
}
fragment.attachStoryViewer(containerView);
}
private void closeLastFragmentInternalRemoveOld(BaseFragment fragment) { private void closeLastFragmentInternalRemoveOld(BaseFragment fragment) {
fragment.finishing = true; fragment.finishing = true;
fragment.onPause(); fragment.onPause();

View file

@ -1928,6 +1928,9 @@ public class ActionBarMenuItem extends FrameLayout {
showSubItem(id, false); showSubItem(id, false);
} }
public View getSubItem(int id) {
return popupLayout.findViewWithTag(id);
}
public void showSubItem(int id, boolean animated) { public void showSubItem(int id, boolean animated) {
Item lazyItem = findLazyItem(id); Item lazyItem = findLazyItem(id);
if (lazyItem != null) { if (lazyItem != null) {

View file

@ -73,7 +73,7 @@ public class BottomSheet extends Dialog {
protected int currentAccount = UserConfig.selectedAccount; protected int currentAccount = UserConfig.selectedAccount;
protected ViewGroup containerView; protected ViewGroup containerView;
protected ContainerView container; public ContainerView container;
protected boolean keyboardVisible; protected boolean keyboardVisible;
protected int keyboardHeight; protected int keyboardHeight;
private WindowInsets lastInsets; private WindowInsets lastInsets;
@ -584,25 +584,29 @@ public class BottomSheet extends Dialog {
if (lastInsets != null && Build.VERSION.SDK_INT >= 21) { if (lastInsets != null && Build.VERSION.SDK_INT >= 21) {
l += getLeftInset(); l += getLeftInset();
} }
if (smoothKeyboardAnimationEnabled && startAnimationRunnable == null && keyboardChanged && !dismissed && containerView.getTop() != t) { if (smoothKeyboardAnimationEnabled && startAnimationRunnable == null && keyboardChanged && !dismissed && containerView.getTop() != t || smoothContainerViewLayoutUntil > 0 && System.currentTimeMillis() < smoothContainerViewLayoutUntil) {
containerView.setTranslationY(containerView.getTop() - t); containerView.setTranslationY(containerView.getTop() - t);
onSmoothContainerViewLayout(containerView.getTranslationY());
if (keyboardContentAnimator != null) { if (keyboardContentAnimator != null) {
keyboardContentAnimator.cancel(); keyboardContentAnimator.cancel();
} }
keyboardContentAnimator = ValueAnimator.ofFloat(containerView.getTranslationY(), 0); keyboardContentAnimator = ValueAnimator.ofFloat(containerView.getTranslationY(), 0);
keyboardContentAnimator.addUpdateListener(valueAnimator -> { keyboardContentAnimator.addUpdateListener(valueAnimator -> {
containerView.setTranslationY((Float) valueAnimator.getAnimatedValue()); containerView.setTranslationY((Float) valueAnimator.getAnimatedValue());
onSmoothContainerViewLayout(containerView.getTranslationY());
invalidate(); invalidate();
}); });
keyboardContentAnimator.addListener(new AnimatorListenerAdapter() { keyboardContentAnimator.addListener(new AnimatorListenerAdapter() {
@Override @Override
public void onAnimationEnd(Animator animation) { public void onAnimationEnd(Animator animation) {
containerView.setTranslationY(0); containerView.setTranslationY(0);
onSmoothContainerViewLayout(containerView.getTranslationY());
invalidate(); invalidate();
} }
}); });
keyboardContentAnimator.setDuration(AdjustPanLayoutHelper.keyboardDuration).setInterpolator(AdjustPanLayoutHelper.keyboardInterpolator); keyboardContentAnimator.setDuration(AdjustPanLayoutHelper.keyboardDuration).setInterpolator(AdjustPanLayoutHelper.keyboardInterpolator);
keyboardContentAnimator.start(); keyboardContentAnimator.start();
smoothContainerViewLayoutUntil = -1;
} }
containerView.layout(l, t, l + containerView.getMeasuredWidth(), t + containerView.getMeasuredHeight()); containerView.layout(l, t, l + containerView.getMeasuredWidth(), t + containerView.getMeasuredHeight());
} }
@ -2093,4 +2097,13 @@ public class BottomSheet extends Dialog {
this.playingImagesLayerNum = playingImages; this.playingImagesLayerNum = playingImages;
this.openedLayerNum = onShowing; this.openedLayerNum = onShowing;
} }
private long smoothContainerViewLayoutUntil = -1;
public void smoothContainerViewLayout() {
smoothContainerViewLayoutUntil = System.currentTimeMillis() + 80;
}
protected void onSmoothContainerViewLayout(float ty) {
}
} }

View file

@ -23,6 +23,7 @@ public interface INavigationLayout {
int REBUILD_FLAG_REBUILD_LAST = 1, REBUILD_FLAG_REBUILD_ONLY_LAST = 2; int REBUILD_FLAG_REBUILD_LAST = 1, REBUILD_FLAG_REBUILD_ONLY_LAST = 2;
int FORCE_NOT_ATTACH_VIEW = -2; int FORCE_NOT_ATTACH_VIEW = -2;
int FORCE_ATTACH_VIEW_AS_FIRST = -3;
boolean presentFragment(NavigationParams params); boolean presentFragment(NavigationParams params);
boolean checkTransitionAnimation(); boolean checkTransitionAnimation();

View file

@ -4125,8 +4125,10 @@ public class Theme {
public static final int key_premiumGradientBackground4 = colorsCount++; public static final int key_premiumGradientBackground4 = colorsCount++;
public static final int key_premiumGradientBackgroundOverlay = colorsCount++; public static final int key_premiumGradientBackgroundOverlay = colorsCount++;
public static final int key_premiumStartSmallStarsColor = colorsCount++; public static final int key_premiumStartSmallStarsColor = colorsCount++;
public static final int key_premiumStartGradient1 = colorsCount++; public static final int key_premiumStarGradient1 = colorsCount++;
public static final int key_premiumStartGradient2 = colorsCount++; public static final int key_premiumStarGradient2 = colorsCount++;
public static final int key_premiumCoinGradient1 = colorsCount++;
public static final int key_premiumCoinGradient2 = colorsCount++;
public static final int key_premiumStartSmallStarsColor2 = colorsCount++; public static final int key_premiumStartSmallStarsColor2 = colorsCount++;
public static final int key_premiumGradientBottomSheet1 = colorsCount++; public static final int key_premiumGradientBottomSheet1 = colorsCount++;
public static final int key_premiumGradientBottomSheet2 = colorsCount++; public static final int key_premiumGradientBottomSheet2 = colorsCount++;
@ -4503,8 +4505,8 @@ public class Theme {
themeAccentExclusionKeys.add(key_premiumGradientBackground3); themeAccentExclusionKeys.add(key_premiumGradientBackground3);
themeAccentExclusionKeys.add(key_premiumGradientBackground4); themeAccentExclusionKeys.add(key_premiumGradientBackground4);
themeAccentExclusionKeys.add(key_premiumStartSmallStarsColor); themeAccentExclusionKeys.add(key_premiumStartSmallStarsColor);
themeAccentExclusionKeys.add(key_premiumStartGradient1); themeAccentExclusionKeys.add(key_premiumStarGradient1);
themeAccentExclusionKeys.add(key_premiumStartGradient2); themeAccentExclusionKeys.add(key_premiumStarGradient2);
themeAccentExclusionKeys.add(key_stories_circle1); themeAccentExclusionKeys.add(key_stories_circle1);
themeAccentExclusionKeys.add(key_stories_circle2); themeAccentExclusionKeys.add(key_stories_circle2);
themeAccentExclusionKeys.add(key_stories_circle_dialog1); themeAccentExclusionKeys.add(key_stories_circle_dialog1);
@ -8545,7 +8547,7 @@ public class Theme {
chat_radialProgress2Paint.setStyle(Paint.Style.STROKE); chat_radialProgress2Paint.setStyle(Paint.Style.STROKE);
chat_audioTimePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG); chat_audioTimePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
chat_livePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); chat_livePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
chat_livePaint.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); chat_livePaint.setTypeface(Typeface.DEFAULT_BOLD);
chat_audioTitlePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); chat_audioTitlePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
chat_audioTitlePaint.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); chat_audioTitlePaint.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM));
chat_audioPerformerPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); chat_audioPerformerPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
@ -8876,7 +8878,7 @@ public class Theme {
chat_contextResult_titleTextPaint.setTextSize(dp(15)); chat_contextResult_titleTextPaint.setTextSize(dp(15));
chat_contextResult_descriptionTextPaint.setTextSize(dp(13)); chat_contextResult_descriptionTextPaint.setTextSize(dp(13));
chat_radialProgressPaint.setStrokeWidth(dp(3)); chat_radialProgressPaint.setStrokeWidth(dp(3));
chat_radialProgress2Paint.setStrokeWidth(dp(2)); chat_radialProgress2Paint.setStrokeWidth(dp(2.33f));
chat_commentTextPaint.setTextSize(dp(14)); chat_commentTextPaint.setTextSize(dp(14));
chat_commentTextPaint.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); chat_commentTextPaint.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM));
} }

View file

@ -3,7 +3,6 @@ package org.telegram.ui.ActionBar;
import static org.telegram.ui.ActionBar.Theme.*; import static org.telegram.ui.ActionBar.Theme.*;
import android.graphics.Color; import android.graphics.Color;
import android.util.Log;
import android.util.SparseArray; import android.util.SparseArray;
import androidx.core.graphics.ColorUtils; import androidx.core.graphics.ColorUtils;
@ -758,8 +757,10 @@ public class ThemeColors {
defaultColors[key_premiumGradientBackground3] = 0xffDB5C9D; defaultColors[key_premiumGradientBackground3] = 0xffDB5C9D;
defaultColors[key_premiumGradientBackground4] = 0xffF38926; defaultColors[key_premiumGradientBackground4] = 0xffF38926;
defaultColors[key_premiumGradientBackgroundOverlay] = Color.WHITE; defaultColors[key_premiumGradientBackgroundOverlay] = Color.WHITE;
defaultColors[key_premiumStartGradient1] = 0xffFFFFFF; defaultColors[key_premiumStarGradient1] = 0xffFFFFFF;
defaultColors[key_premiumStartGradient2] = 0xffE3ECFA; defaultColors[key_premiumStarGradient2] = 0xffE3ECFA;
defaultColors[key_premiumCoinGradient1] = -15436801;
defaultColors[key_premiumCoinGradient2] = -4167942;
defaultColors[key_premiumStartSmallStarsColor] = ColorUtils.setAlphaComponent(Color.WHITE, 90); defaultColors[key_premiumStartSmallStarsColor] = ColorUtils.setAlphaComponent(Color.WHITE, 90);
defaultColors[key_premiumStartSmallStarsColor2] = ColorUtils.setAlphaComponent(Color.WHITE, 90); defaultColors[key_premiumStartSmallStarsColor2] = ColorUtils.setAlphaComponent(Color.WHITE, 90);
defaultColors[key_premiumGradientBottomSheet1] = 0xff5B9DE7; defaultColors[key_premiumGradientBottomSheet1] = 0xff5B9DE7;
@ -1505,8 +1506,10 @@ public class ThemeColors {
colorKeysMap.put(key_premiumGradientBackground4, "premiumGradientBackground4"); colorKeysMap.put(key_premiumGradientBackground4, "premiumGradientBackground4");
colorKeysMap.put(key_premiumGradientBackgroundOverlay, "premiumGradientBackgroundOverlay"); colorKeysMap.put(key_premiumGradientBackgroundOverlay, "premiumGradientBackgroundOverlay");
colorKeysMap.put(key_premiumStartSmallStarsColor, "premiumStartSmallStarsColor"); colorKeysMap.put(key_premiumStartSmallStarsColor, "premiumStartSmallStarsColor");
colorKeysMap.put(key_premiumStartGradient1, "premiumStarGradient1"); colorKeysMap.put(key_premiumStarGradient1, "premiumStarGradient1");
colorKeysMap.put(key_premiumStartGradient2, "premiumStarGradient2"); colorKeysMap.put(key_premiumStarGradient2, "premiumStarGradient2");
colorKeysMap.put(key_premiumCoinGradient1, "premiumCoinGradient1");
colorKeysMap.put(key_premiumCoinGradient2, "premiumCoinGradient2");
colorKeysMap.put(key_premiumStartSmallStarsColor2, "premiumStartSmallStarsColor2"); colorKeysMap.put(key_premiumStartSmallStarsColor2, "premiumStartSmallStarsColor2");
colorKeysMap.put(key_premiumGradientBottomSheet1, "premiumGradientBottomSheet1"); colorKeysMap.put(key_premiumGradientBottomSheet1, "premiumGradientBottomSheet1");
colorKeysMap.put(key_premiumGradientBottomSheet2, "premiumGradientBottomSheet2"); colorKeysMap.put(key_premiumGradientBottomSheet2, "premiumGradientBottomSheet2");

View file

@ -63,15 +63,15 @@ import java.util.concurrent.ConcurrentHashMap;
public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
private final int VIEW_TYPE_PROFILE_CELL = 0; public final static int VIEW_TYPE_PROFILE_CELL = 0;
private final int VIEW_TYPE_GRAY_SECTION = 1; public final static int VIEW_TYPE_GRAY_SECTION = 1;
private final int VIEW_TYPE_DIALOG_CELL = 2; public final int VIEW_TYPE_DIALOG_CELL = 2;
private final int VIEW_TYPE_TOPIC_CELL = 3; public final int VIEW_TYPE_TOPIC_CELL = 3;
private final int VIEW_TYPE_LOADING = 4; public final int VIEW_TYPE_LOADING = 4;
private final int VIEW_TYPE_HASHTAG_CELL = 5; public final int VIEW_TYPE_HASHTAG_CELL = 5;
private final int VIEW_TYPE_CATEGORY_LIST = 6; public final int VIEW_TYPE_CATEGORY_LIST = 6;
private final int VIEW_TYPE_ADD_BY_PHONE = 7; public final int VIEW_TYPE_ADD_BY_PHONE = 7;
private final int VIEW_TYPE_INVITE_CONTACT_CELL = 8; public final int VIEW_TYPE_INVITE_CONTACT_CELL = 8;
private Context mContext; private Context mContext;
private Runnable searchRunnable; private Runnable searchRunnable;
private Runnable searchRunnable2; private Runnable searchRunnable2;
@ -1336,6 +1336,12 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
} }
i -= contactsCount + 1; i -= contactsCount + 1;
} }
if (localCount + localServerCount > 0 && (getRecentItemsCount() > 0 || !searchTopics.isEmpty())) {
if (i == 0) {
return false;
}
i--;
}
if (i >= 0 && i < localCount) { if (i >= 0 && i < localCount) {
return false; return false;
} }
@ -1483,12 +1489,23 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
CharSequence username = null; CharSequence username = null;
CharSequence name = null; CharSequence name = null;
boolean isRecent = false; boolean isRecent = false;
boolean isGlobal = isGlobalSearch(position);
String un = null; String un = null;
Object obj = getItem(position); Object obj = getItem(position);
if (obj instanceof TLRPC.User) { if (obj instanceof TLRPC.User) {
user = (TLRPC.User) obj; user = (TLRPC.User) obj;
un = UserObject.getPublicUsername(user); un = UserObject.getPublicUsername(user);
if (un != null && lastSearchText != null && !un.toLowerCase().contains(lastSearchText.toLowerCase())) {
if (user.usernames != null) {
for (int i = 0; i < user.usernames.size(); ++i) {
TLRPC.TL_username u = user.usernames.get(i);
if (u != null && u.active && u.username.toLowerCase().contains(lastSearchText.toLowerCase())) {
un = u.username;
}
}
}
}
} else if (obj instanceof TLRPC.Chat) { } else if (obj instanceof TLRPC.Chat) {
chat = MessagesController.getInstance(currentAccount).getChat(((TLRPC.Chat) obj).id); chat = MessagesController.getInstance(currentAccount).getChat(((TLRPC.Chat) obj).id);
if (chat == null) { if (chat == null) {
@ -1557,7 +1574,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), index, index + foundUserName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), index, index + foundUserName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
name = spannableStringBuilder; name = spannableStringBuilder;
} }
if (un != null && user == null) { if (un != null && (user == null || isGlobal)) {
if (foundUserName.startsWith("@")) { if (foundUserName.startsWith("@")) {
foundUserName = foundUserName.substring(1); foundUserName = foundUserName.substring(1);
} }

View file

@ -311,6 +311,7 @@ public class DrawerLayoutAdapter extends RecyclerListView.SelectionAdapter {
} }
UserConfig me = UserConfig.getInstance(UserConfig.selectedAccount); UserConfig me = UserConfig.getInstance(UserConfig.selectedAccount);
boolean showDivider = false; boolean showDivider = false;
items.add(new Item(16, LocaleController.getString(R.string.MyProfile), R.drawable.left_status_profile));
if (me != null && me.isPremium()) { if (me != null && me.isPremium()) {
if (me.getEmojiStatus() != null) { if (me.getEmojiStatus() != null) {
items.add(new Item(15, LocaleController.getString("ChangeEmojiStatus", R.string.ChangeEmojiStatus), R.drawable.msg_status_edit)); items.add(new Item(15, LocaleController.getString("ChangeEmojiStatus", R.string.ChangeEmojiStatus), R.drawable.msg_status_edit));
@ -319,10 +320,11 @@ public class DrawerLayoutAdapter extends RecyclerListView.SelectionAdapter {
} }
showDivider = true; showDivider = true;
} }
if (MessagesController.getInstance(UserConfig.selectedAccount).storiesEnabled()) { // if (MessagesController.getInstance(UserConfig.selectedAccount).storiesEnabled()) {
items.add(new Item(16, LocaleController.getString("ProfileMyStories", R.string.ProfileMyStories), R.drawable.msg_menu_stories)); // items.add(new Item(17, LocaleController.getString(R.string.ProfileStories), R.drawable.msg_menu_stories));
// showDivider = true;
// }
showDivider = true; showDivider = true;
}
if (ApplicationLoader.applicationLoaderInstance != null) { if (ApplicationLoader.applicationLoaderInstance != null) {
if (ApplicationLoader.applicationLoaderInstance.extendDrawer(items)) { if (ApplicationLoader.applicationLoaderInstance.extendDrawer(items)) {
showDivider = true; showDivider = true;

View file

@ -321,8 +321,9 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
return 2; return 2;
} else if (currentMessageObject != null) { } else if (currentMessageObject != null) {
return 2 + (currentLiveLocations.isEmpty() ? 1 : currentLiveLocations.size() + 3); return 2 + (currentLiveLocations.isEmpty() ? 1 : currentLiveLocations.size() + 3);
} else if (locationType == 2) { } else if (locationType == LocationActivity.LOCATION_TYPE_LIVE) {
return 2 + currentLiveLocations.size(); LocationController.SharingLocationInfo currentInfo = LocationController.getInstance(currentAccount).getSharingLocationInfo(dialogId);
return 2 + currentLiveLocations.size() + (currentInfo != null && currentInfo.period != 0x7FFFFFFF ? 1 : 0);
} else { } else {
if (searching || !searched || places.isEmpty()) { if (searching || !searched || places.isEmpty()) {
int count = 6; int count = 6;
@ -368,7 +369,7 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
emptyCell.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, overScrollHeight)); emptyCell.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, overScrollHeight));
break; break;
case VIEW_TYPE_SEND_LOCATION: case VIEW_TYPE_SEND_LOCATION:
view = new SendLocationCell(mContext, false, resourcesProvider); view = new SendLocationCell(mContext, false, false, resourcesProvider);
break; break;
case VIEW_TYPE_HEADER: case VIEW_TYPE_HEADER:
view = new HeaderCell(mContext, resourcesProvider); view = new HeaderCell(mContext, resourcesProvider);
@ -384,7 +385,13 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
view = new LocationPoweredCell(mContext, resourcesProvider); view = new LocationPoweredCell(mContext, resourcesProvider);
break; break;
case VIEW_TYPE_LIVE_LOCATION: { case VIEW_TYPE_LIVE_LOCATION: {
SendLocationCell cell = new SendLocationCell(mContext, true, resourcesProvider); SendLocationCell cell = new SendLocationCell(mContext, true, false, resourcesProvider);
cell.setDialogId(dialogId);
view = cell;
break;
}
case VIEW_TYPE_DELETE_LIVE_LOCATION: {
SendLocationCell cell = new SendLocationCell(mContext, true, true, resourcesProvider);
cell.setDialogId(dialogId); cell.setDialogId(dialogId);
view = cell; view = cell;
break; break;
@ -428,11 +435,12 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
public static final int VIEW_TYPE_LOADING = 4; public static final int VIEW_TYPE_LOADING = 4;
public static final int VIEW_TYPE_FOOTER = 5; public static final int VIEW_TYPE_FOOTER = 5;
public static final int VIEW_TYPE_LIVE_LOCATION = 6; public static final int VIEW_TYPE_LIVE_LOCATION = 6;
public static final int VIEW_TYPE_SHARING = 7; public static final int VIEW_TYPE_DELETE_LIVE_LOCATION = 7;
public static final int VIEW_TYPE_DIRECTION = 8; public static final int VIEW_TYPE_SHARING = 8;
public static final int VIEW_TYPE_SHADOW = 9; public static final int VIEW_TYPE_DIRECTION = 9;
public static final int VIEW_TYPE_EMPTY = 10; public static final int VIEW_TYPE_SHADOW = 10;
public static final int VIEW_TYPE_STORY_LOCATION = 11; public static final int VIEW_TYPE_EMPTY = 11;
public static final int VIEW_TYPE_STORY_LOCATION = 12;
@Override @Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
@ -493,6 +501,12 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
((LocationLoadingCell) holder.itemView).setLoading(searching); ((LocationLoadingCell) holder.itemView).setLoading(searching);
break; break;
case VIEW_TYPE_LIVE_LOCATION: case VIEW_TYPE_LIVE_LOCATION:
SendLocationCell cell2 = (SendLocationCell) holder.itemView;
cell2.setHasLocation(gpsLocation != null);
cell2.useDivider = position + 1 < getItemCount() && getItemViewType(position + 1) == VIEW_TYPE_DELETE_LIVE_LOCATION;
cell2.invalidate();
break;
case VIEW_TYPE_DELETE_LIVE_LOCATION:
((SendLocationCell) holder.itemView).setHasLocation(gpsLocation != null); ((SendLocationCell) holder.itemView).setHasLocation(gpsLocation != null);
break; break;
case VIEW_TYPE_SHARING: case VIEW_TYPE_SHARING:
@ -504,7 +518,14 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
} else if (currentMessageObject != null && position == 1) { } else if (currentMessageObject != null && position == 1) {
locationCell.setDialog(currentMessageObject, gpsLocation, myLocationDenied); locationCell.setDialog(currentMessageObject, gpsLocation, myLocationDenied);
} else { } else {
locationCell.setDialog(currentLiveLocations.get(position - (currentMessageObject != null ? 5 : 2)), gpsLocation); int index = position - (currentMessageObject != null ? 5 : 2);
LocationController.SharingLocationInfo currentInfo = LocationController.getInstance(currentAccount).getSharingLocationInfo(dialogId);
if (currentInfo != null && currentInfo.period != 0x7FFFFFFF) {
index--;
}
if (index < 0 || index >= currentLiveLocations.size())
return;
locationCell.setDialog(currentLiveLocations.get(index), gpsLocation);
} }
break; break;
case VIEW_TYPE_EMPTY: case VIEW_TYPE_EMPTY:
@ -549,9 +570,14 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
} else if (i > 4 && i < places.size() + 4) { } else if (i > 4 && i < places.size() + 4) {
return currentLiveLocations.get(i - 5); return currentLiveLocations.get(i - 5);
} }
} else if (locationType == 2) { } else if (locationType == LocationActivity.LOCATION_TYPE_LIVE) {
if (i >= 2) { int start = 2;
return currentLiveLocations.get(i - 2); LocationController.SharingLocationInfo currentInfo = LocationController.getInstance(currentAccount).getSharingLocationInfo(dialogId);
if (currentInfo != null && currentInfo.period != 0x7FFFFFFF) {
start++;
}
if (i >= start) {
return currentLiveLocations.get(i - start);
} }
return null; return null;
} else if (locationType == LocationActivity.LOCATION_TYPE_SEND_WITH_LIVE) { } else if (locationType == LocationActivity.LOCATION_TYPE_SEND_WITH_LIVE) {
@ -592,6 +618,10 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
if (locationType == LocationActivity.LOCATION_TYPE_GROUP) { if (locationType == LocationActivity.LOCATION_TYPE_GROUP) {
return VIEW_TYPE_SEND_LOCATION; return VIEW_TYPE_SEND_LOCATION;
} }
LocationController.SharingLocationInfo currentInfo = null;
if (locationType == LocationActivity.LOCATION_TYPE_LIVE || locationType == LocationActivity.LOCATION_TYPE_SEND_WITH_LIVE) {
currentInfo = LocationController.getInstance(currentAccount).getSharingLocationInfo(dialogId);
}
if (currentMessageObject != null) { if (currentMessageObject != null) {
if (currentLiveLocations.isEmpty()) { if (currentLiveLocations.isEmpty()) {
if (position == 2) { if (position == 2) {
@ -609,8 +639,14 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
} }
return VIEW_TYPE_SHARING; return VIEW_TYPE_SHARING;
} }
if (locationType == 2) { if (locationType == LocationActivity.LOCATION_TYPE_LIVE) {
if (position == 2 && currentInfo != null && currentInfo.period != 0x7FFFFFFF) {
return VIEW_TYPE_DELETE_LIVE_LOCATION;
}
if (position == 1) { if (position == 1) {
if (currentInfo != null && currentInfo.period == 0x7FFFFFFF) {
return VIEW_TYPE_DELETE_LIVE_LOCATION;
}
shareLiveLocationPotistion = position; shareLiveLocationPotistion = position;
return VIEW_TYPE_LIVE_LOCATION; return VIEW_TYPE_LIVE_LOCATION;
} else { } else {
@ -620,9 +656,14 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
if (locationType == LocationActivity.LOCATION_TYPE_SEND_WITH_LIVE) { if (locationType == LocationActivity.LOCATION_TYPE_SEND_WITH_LIVE) {
if (position == 1) { if (position == 1) {
return VIEW_TYPE_SEND_LOCATION; return VIEW_TYPE_SEND_LOCATION;
} else if (position == 2) { } else if (position == LocationActivity.LOCATION_TYPE_LIVE) {
if (currentInfo != null) {
shareLiveLocationPotistion = -1;
return VIEW_TYPE_DELETE_LIVE_LOCATION;
} else {
shareLiveLocationPotistion = position; shareLiveLocationPotistion = position;
return VIEW_TYPE_LIVE_LOCATION; return VIEW_TYPE_LIVE_LOCATION;
}
} else if (position == 3) { } else if (position == 3) {
return VIEW_TYPE_SHADOW; return VIEW_TYPE_SHADOW;
} else if (position == 4) { } else if (position == 4) {
@ -642,7 +683,7 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
return VIEW_TYPE_STORY_LOCATION; return VIEW_TYPE_STORY_LOCATION;
} }
if (this.street != null) { if (this.street != null) {
if (position == 2) { if (position == LocationActivity.LOCATION_TYPE_LIVE) {
return VIEW_TYPE_STORY_LOCATION; return VIEW_TYPE_STORY_LOCATION;
} }
position--; position--;
@ -672,7 +713,7 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
if (viewType == VIEW_TYPE_LIVE_LOCATION) { if (viewType == VIEW_TYPE_LIVE_LOCATION) {
return !(LocationController.getInstance(currentAccount).getSharingLocationInfo(dialogId) == null && gpsLocation == null); return !(LocationController.getInstance(currentAccount).getSharingLocationInfo(dialogId) == null && gpsLocation == null);
} }
return viewType == VIEW_TYPE_SEND_LOCATION || viewType == VIEW_TYPE_LOCATION || viewType == VIEW_TYPE_SHARING || viewType == VIEW_TYPE_STORY_LOCATION; return viewType == VIEW_TYPE_SEND_LOCATION || viewType == VIEW_TYPE_LOCATION || viewType == VIEW_TYPE_SHARING || viewType == VIEW_TYPE_STORY_LOCATION || viewType == VIEW_TYPE_DELETE_LIVE_LOCATION;
} }
private int getThemedColor(int key) { private int getThemedColor(int key) {

View file

@ -65,6 +65,7 @@ public class SearchAdapter extends RecyclerListView.SelectionAdapter {
private int searchPointer; private int searchPointer;
private ArrayList<ContactEntry> allUnregistredContacts; private ArrayList<ContactEntry> allUnregistredContacts;
private ArrayList<ContactsController.Contact> unregistredContacts = new ArrayList<>(); private ArrayList<ContactsController.Contact> unregistredContacts = new ArrayList<>();
private String lastQuery;
public SearchAdapter(Context context, LongSparseArray<TLRPC.User> arg1, LongSparseArray<TLRPC.User> selected, boolean usernameSearch, boolean mutual, boolean chats, boolean bots, boolean self, boolean phones, int searchChannelId) { public SearchAdapter(Context context, LongSparseArray<TLRPC.User> arg1, LongSparseArray<TLRPC.User> selected, boolean usernameSearch, boolean mutual, boolean chats, boolean bots, boolean self, boolean phones, int searchChannelId) {
@ -133,6 +134,7 @@ public class SearchAdapter extends RecyclerListView.SelectionAdapter {
private void processSearch(final String query) { private void processSearch(final String query) {
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
lastQuery = query;
if (allowUsernameSearch) { if (allowUsernameSearch) {
searchAdapterHelper.queryServerSearch(query, true, allowChats, allowBots, allowSelf, false, channelId, allowPhoneNumbers, -1, 1); searchAdapterHelper.queryServerSearch(query, true, allowChats, allowBots, allowSelf, false, channelId, allowPhoneNumbers, -1, 1);
} }
@ -260,8 +262,8 @@ public class SearchAdapter extends RecyclerListView.SelectionAdapter {
public int getItemCount() { public int getItemCount() {
unregistredContactsHeaderRow = -1; unregistredContactsHeaderRow = -1;
int count = searchResult.size(); int count = searchResult.size();
unregistredContactsHeaderRow = count;
if (!unregistredContacts.isEmpty()) { if (!unregistredContacts.isEmpty()) {
unregistredContactsHeaderRow = count;
count += unregistredContacts.size() + 1; count += unregistredContacts.size() + 1;
} }
@ -359,7 +361,18 @@ public class SearchAdapter extends RecyclerListView.SelectionAdapter {
String un = null; String un = null;
boolean self = false; boolean self = false;
if (object instanceof TLRPC.User) { if (object instanceof TLRPC.User) {
un = ((TLRPC.User) object).username; TLRPC.User user = (TLRPC.User) object;
un = UserObject.getPublicUsername((TLRPC.User) object);
if (un != null && lastQuery != null && !un.toLowerCase().contains(lastQuery.toLowerCase())) {
if (user.usernames != null) {
for (int i = 0; i < user.usernames.size(); ++i) {
TLRPC.TL_username u = user.usernames.get(i);
if (u != null && u.active && u.username.toLowerCase().contains(lastQuery.toLowerCase())) {
un = u.username;
}
}
}
}
id = ((TLRPC.User) object).id; id = ((TLRPC.User) object).id;
self = ((TLRPC.User) object).self; self = ((TLRPC.User) object).self;
} else if (object instanceof TLRPC.Chat) { } else if (object instanceof TLRPC.Chat) {

View file

@ -13,6 +13,7 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.ImageReceiver;
import org.telegram.messenger.MessagesController;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.ui.Components.AvatarDrawable; import org.telegram.ui.Components.AvatarDrawable;
@ -21,17 +22,20 @@ public class AvatarSpan extends ReplacementSpan {
private final Paint shadowPaint; private final Paint shadowPaint;
private final ImageReceiver imageReceiver; private final ImageReceiver imageReceiver;
private final AvatarDrawable avatarDrawable; private final AvatarDrawable avatarDrawable;
private final int sz; private float sz;
private final int currentAccount; private final int currentAccount;
private View parent; private View parent;
public AvatarSpan(View parent, int currentAccount, int sz) { public AvatarSpan(View parent, int currentAccount) {
this(parent, currentAccount, 18);
}
public AvatarSpan(View parent, int currentAccount, float sz) {
this.currentAccount = currentAccount; this.currentAccount = currentAccount;
this.imageReceiver = new ImageReceiver(parent); this.imageReceiver = new ImageReceiver(parent);
this.avatarDrawable = new AvatarDrawable(); this.avatarDrawable = new AvatarDrawable();
imageReceiver.setRoundRadius(dp(sz)); setSize(sz);
this.sz = sz;
this.shadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG); this.shadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
shadowPaint.setShadowLayer(dp(1), 0, dp(.66f), 0x33000000); shadowPaint.setShadowLayer(dp(1), 0, dp(.66f), 0x33000000);
@ -39,6 +43,11 @@ public class AvatarSpan extends ReplacementSpan {
setParent(parent); setParent(parent);
} }
public void setSize(float sz) {
imageReceiver.setRoundRadius(dp(sz));
this.sz = sz;
}
public void setParent(View parent) { public void setParent(View parent) {
if (this.parent == parent) return; if (this.parent == parent) return;
if (this.parent != null) { if (this.parent != null) {
@ -88,6 +97,11 @@ public class AvatarSpan extends ReplacementSpan {
imageReceiver.setForUserOrChat(user, avatarDrawable); imageReceiver.setForUserOrChat(user, avatarDrawable);
} }
public void setName(String name) {
avatarDrawable.setInfo(0, name, null, null, null, null);
imageReceiver.setForUserOrChat(null, avatarDrawable);
}
@Override @Override
public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) { public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
return dp(sz); return dp(sz);

View file

@ -9,16 +9,9 @@ import android.graphics.Matrix;
import android.graphics.PorterDuff; import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect; import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity; import android.view.Gravity;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -29,10 +22,8 @@ import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BotWebViewVibrationEffect;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaDataController; import org.telegram.messenger.MediaDataController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
@ -40,26 +31,21 @@ import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenuItem; import org.telegram.ui.ActionBar.ActionBarMenuItem;
import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.EditTextCell; import org.telegram.ui.Cells.EditTextCell;
import org.telegram.ui.Cells.TextCell; import org.telegram.ui.Cells.TextCell;
import org.telegram.ui.Components.AnimatedColor;
import org.telegram.ui.Components.AnimatedFloat; import org.telegram.ui.Components.AnimatedFloat;
import org.telegram.ui.Components.AnimatedTextView;
import org.telegram.ui.Components.BulletinFactory; import org.telegram.ui.Components.BulletinFactory;
import org.telegram.ui.Components.ChatAttachAlert;
import org.telegram.ui.Components.ChatGreetingsView; import org.telegram.ui.Components.ChatGreetingsView;
import org.telegram.ui.Components.CircularProgressDrawable; import org.telegram.ui.Components.CircularProgressDrawable;
import org.telegram.ui.Components.CrossfadeDrawable; import org.telegram.ui.Components.CrossfadeDrawable;
import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.EditTextBoldCursor;
import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.SizeNotifierFrameLayout;
import org.telegram.ui.Components.Text;
import org.telegram.ui.Components.UItem; import org.telegram.ui.Components.UItem;
import org.telegram.ui.Components.UniversalAdapter; import org.telegram.ui.Components.UniversalAdapter;
import org.telegram.ui.Components.UniversalFragment; import org.telegram.ui.Components.UniversalFragment;
import org.telegram.ui.Stories.StoryViewer; import org.telegram.ui.ContentPreviewViewer;
import org.telegram.ui.Stories.recorder.EmojiBottomSheet; import org.telegram.ui.Stories.recorder.EmojiBottomSheet;
import org.telegram.ui.Stories.recorder.KeyboardNotifier; import org.telegram.ui.Stories.recorder.KeyboardNotifier;
import org.telegram.ui.Stories.recorder.PreviewView; import org.telegram.ui.Stories.recorder.PreviewView;
@ -113,6 +99,9 @@ public class BusinessIntroActivity extends UniversalFragment implements Notifica
private boolean stickerRandom = true; private boolean stickerRandom = true;
private TLRPC.Document sticker = getMediaDataController().getGreetingsSticker(); private TLRPC.Document sticker = getMediaDataController().getGreetingsSticker();
private String inputStickerPath;
private TLRPC.InputDocument inputSticker;
private boolean keyboardVisible; private boolean keyboardVisible;
@Override @Override
@ -303,8 +292,10 @@ public class BusinessIntroActivity extends UniversalFragment implements Notifica
items.add(UItem.asCustom(messageEdit)); items.add(UItem.asCustom(messageEdit));
if (stickerRandom) { if (stickerRandom) {
items.add(UItem.asButton(BUTTON_STICKER, getString(R.string.BusinessIntroSticker), getString(R.string.BusinessIntroStickerRandom))); items.add(UItem.asButton(BUTTON_STICKER, getString(R.string.BusinessIntroSticker), getString(R.string.BusinessIntroStickerRandom)));
} else if (inputStickerPath != null) {
items.add(UItem.asStickerButton(BUTTON_STICKER, getString(R.string.BusinessIntroSticker), inputStickerPath));
} else { } else {
items.add(UItem.asButton(BUTTON_STICKER, getString(R.string.BusinessIntroSticker), sticker)); items.add(UItem.asStickerButton(BUTTON_STICKER, getString(R.string.BusinessIntroSticker), sticker));
} }
items.add(UItem.asShadow(getString(R.string.BusinessIntroInfo))); items.add(UItem.asShadow(getString(R.string.BusinessIntroInfo)));
if (clearVisible = !isEmpty()) { if (clearVisible = !isEmpty()) {
@ -319,13 +310,6 @@ public class BusinessIntroActivity extends UniversalFragment implements Notifica
return TextUtils.isEmpty(titleEdit.getText()) && TextUtils.isEmpty(messageEdit.getText()) && stickerRandom; return TextUtils.isEmpty(titleEdit.getText()) && TextUtils.isEmpty(messageEdit.getText()) && stickerRandom;
} }
@Override
public void didReceivedNotification(int id, int account, Object... args) {
if (id == NotificationCenter.userInfoDidLoad) {
setValue();
}
}
private String currentTitle, currentMessage; private String currentTitle, currentMessage;
private long currentSticker; private long currentSticker;
@ -347,6 +331,7 @@ public class BusinessIntroActivity extends UniversalFragment implements Notifica
} else { } else {
titleEdit.setText(currentTitle = ""); titleEdit.setText(currentTitle = "");
messageEdit.setText(currentMessage = ""); messageEdit.setText(currentMessage = "");
inputSticker = null;
sticker = null; sticker = null;
} }
currentSticker = sticker == null ? 0 : sticker.id; currentSticker = sticker == null ? 0 : sticker.id;
@ -371,14 +356,16 @@ public class BusinessIntroActivity extends UniversalFragment implements Notifica
@Override @Override
protected void onClick(UItem item, View view, int position, float x, float y) { protected void onClick(UItem item, View view, int position, float x, float y) {
if (item.id == BUTTON_STICKER) { if (item.id == BUTTON_STICKER) {
EmojiBottomSheet sheet = new EmojiBottomSheet(getContext(), true, getResourceProvider()); EmojiBottomSheet sheet = new EmojiBottomSheet(getContext(), true, getResourceProvider(), true);
sheet.whenDocumentSelected((parentObject, document, a) -> { sheet.whenDocumentSelected((parentObject, document, a) -> {
stickerRandom = false; stickerRandom = false;
AndroidUtilities.cancelRunOnUIThread(updateRandomStickerRunnable); AndroidUtilities.cancelRunOnUIThread(updateRandomStickerRunnable);
greetingsView.setSticker(sticker = document); greetingsView.setSticker(sticker = document);
((TextCell) view).setValueSticker(document); ((TextCell) view).setValueSticker(document);
checkDone(true, false); checkDone(true, false);
return true;
}); });
sheet.whenPlusSelected(this::openCustomStickerEditor);
showDialog(sheet); showDialog(sheet);
} else if (item.id == BUTTON_REMOVE) { } else if (item.id == BUTTON_REMOVE) {
titleEdit.setText(""); titleEdit.setText("");
@ -405,7 +392,7 @@ public class BusinessIntroActivity extends UniversalFragment implements Notifica
return ( return (
!TextUtils.equals(titleEdit.getText().toString(), currentTitle == null ? "" : currentTitle) || !TextUtils.equals(titleEdit.getText().toString(), currentTitle == null ? "" : currentTitle) ||
!TextUtils.equals(messageEdit.getText().toString(), currentMessage == null ? "" : currentMessage) || !TextUtils.equals(messageEdit.getText().toString(), currentMessage == null ? "" : currentMessage) ||
(stickerRandom || sticker == null ? 0 : sticker.id) != currentSticker (stickerRandom || sticker == null ? 0 : sticker.id) != currentSticker || (!stickerRandom && inputSticker != null)
); );
} }
@ -452,10 +439,14 @@ public class BusinessIntroActivity extends UniversalFragment implements Notifica
req.intro = new TLRPC.TL_inputBusinessIntro(); req.intro = new TLRPC.TL_inputBusinessIntro();
req.intro.title = titleEdit.getText().toString(); req.intro.title = titleEdit.getText().toString();
req.intro.description = messageEdit.getText().toString(); req.intro.description = messageEdit.getText().toString();
if (!stickerRandom && sticker != null) { if (!stickerRandom && (sticker != null || inputSticker != null)) {
req.intro.flags |= 1; req.intro.flags |= 1;
if (inputSticker != null) {
req.intro.sticker = inputSticker;
} else {
req.intro.sticker = getMessagesController().getInputDocument(sticker); req.intro.sticker = getMessagesController().getInputDocument(sticker);
} }
}
if (userFull != null) { if (userFull != null) {
userFull.flags2 |= 16; userFull.flags2 |= 16;
@ -482,6 +473,9 @@ public class BusinessIntroActivity extends UniversalFragment implements Notifica
doneButtonDrawable.animateToProgress(0f); doneButtonDrawable.animateToProgress(0f);
BulletinFactory.of(this).createErrorBulletin(LocaleController.getString(R.string.UnknownError)).show(); BulletinFactory.of(this).createErrorBulletin(LocaleController.getString(R.string.UnknownError)).show();
} else { } else {
if (inputSticker != null) {
getMessagesController().loadFullUser(getUserConfig().getCurrentUser(), 0, true);
}
finishFragment(); finishFragment();
} }
})); }));
@ -503,4 +497,83 @@ public class BusinessIntroActivity extends UniversalFragment implements Notifica
} }
private void openCustomStickerEditor() {
ContentPreviewViewer.getInstance().setStickerSetForCustomSticker(null);
if (getParentActivity() == null) {
return;
}
createChatAttachView();
chatAttachAlert.getPhotoLayout().loadGalleryPhotos();
chatAttachAlert.setMaxSelectedPhotos(1, false);
chatAttachAlert.setOpenWithFrontFaceCamera(true);
chatAttachAlert.enableStickerMode(this::setCustomSticker);
chatAttachAlert.init();
chatAttachAlert.parentThemeDelegate = null;
if (visibleDialog != null) {
chatAttachAlert.show();
} else {
showDialog(chatAttachAlert);
}
}
private ChatAttachAlert chatAttachAlert;
private void createChatAttachView() {
if (getParentActivity() == null || getContext() == null) {
return;
}
if (chatAttachAlert == null) {
chatAttachAlert = new ChatAttachAlert(getParentActivity(), this, false, false, true, resourceProvider) {
@Override
public void dismissInternal() {
if (chatAttachAlert != null && chatAttachAlert.isShowing()) {
AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid);
}
super.dismissInternal();
}
@Override
public void onDismissAnimationStart() {
if (chatAttachAlert != null) {
chatAttachAlert.setFocusable(false);
}
if (chatAttachAlert != null && chatAttachAlert.isShowing()) {
AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid);
}
}
};
chatAttachAlert.setDelegate(new ChatAttachAlert.ChatAttachViewDelegate() {
@Override
public void didPressedButton(int button, boolean arg, boolean notify, int scheduleDate, boolean forceDocument) {
}
@Override
public void doOnIdle(Runnable runnable) {
NotificationCenter.getInstance(currentAccount).doOnIdle(runnable);
}
});
}
}
private void setCustomSticker(String localPath, TLRPC.InputDocument inputDocument) {
chatAttachAlert.dismiss();
inputStickerPath = localPath;
inputSticker = inputDocument;
stickerRandom = false;
AndroidUtilities.cancelRunOnUIThread(updateRandomStickerRunnable);
greetingsView.setSticker(inputStickerPath);
checkDone(true, false);
if (listView != null && listView.adapter != null) {
listView.adapter.update(true);
}
}
@Override
public void didReceivedNotification(int id, int account, Object... args) {
if (id == NotificationCenter.userInfoDidLoad) {
setValue();
}
}
} }

View file

@ -370,7 +370,7 @@ public class ChatbotsActivity extends BaseFragment {
} }
} }
private void clear() { private void clear(View view) {
selectedBot = null; selectedBot = null;
listView.adapter.update(true); listView.adapter.update(true);
checkDone(true); checkDone(true);

View file

@ -1,6 +1,7 @@
package org.telegram.ui.Business; package org.telegram.ui.Business;
import static org.telegram.messenger.AndroidUtilities.dp; import static org.telegram.messenger.AndroidUtilities.dp;
import static org.telegram.messenger.LocaleController.formatString;
import static org.telegram.messenger.LocaleController.getString; import static org.telegram.messenger.LocaleController.getString;
import android.content.Context; import android.content.Context;
@ -20,6 +21,7 @@ import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.tgnet.AbstractSerializedData; import org.telegram.tgnet.AbstractSerializedData;
import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLObject;
@ -298,8 +300,15 @@ public class OpeningHoursActivity extends BaseFragment implements NotificationCe
if (!days[prevDay].isEmpty() && days[prevDay].get(days[prevDay].size() - 1).end >= 24 * 60) { if (!days[prevDay].isEmpty() && days[prevDay].get(days[prevDay].size() - 1).end >= 24 * 60) {
days[prevDay].get(days[prevDay].size() - 1).end = 24 * 60 - 1; days[prevDay].get(days[prevDay].size() - 1).end = 24 * 60 - 1;
} }
int periodEnd = Math.min(m - start - 1, 24 * 60 * 2 - 1);
ArrayList<Period> nextDay = days[(7 + i + 1) % 7];
if (periodEnd >= 24 * 60 && !nextDay.isEmpty() && nextDay.get(0).start < periodEnd - 24 * 60) {
periodEnd = 24 * 60 + nextDay.get(0).start - 1;
}
days[i].clear(); days[i].clear();
days[i].add(new Period(0, 24 * 60 - 1)); days[i].add(new Period(0, periodEnd));
} else { } else {
int nextDay = (i + 1) % 7; int nextDay = (i + 1) % 7;
if (!days[i].isEmpty() && !days[nextDay].isEmpty()) { if (!days[i].isEmpty() && !days[nextDay].isEmpty()) {
@ -333,6 +342,44 @@ public class OpeningHoursActivity extends BaseFragment implements NotificationCe
return hours; return hours;
} }
public static String toString(int currentAccount, TLRPC.User user, TLRPC.TL_businessWorkHours business_work_hours) {
if (business_work_hours == null) return null;
ArrayList<OpeningHoursActivity.Period>[] days = OpeningHoursActivity.getDaysHours(business_work_hours.weekly_open);
StringBuilder sb = new StringBuilder();
if (user != null) {
sb.append(formatString(R.string.BusinessHoursCopyHeader, UserObject.getUserName(user))).append("\n");
}
for (int i = 0; i < days.length; ++i) {
ArrayList<OpeningHoursActivity.Period> periods = days[i];
String day = DayOfWeek.values()[i].getDisplayName(TextStyle.FULL, LocaleController.getInstance().getCurrentLocale());
day = day.substring(0, 1).toUpperCase() + day.substring(1);
sb.append(day).append(": ");
if (OpeningHoursActivity.isFull(periods)) {
sb.append(LocaleController.getString(R.string.BusinessHoursProfileOpen));
} else if (periods.isEmpty()) {
sb.append(LocaleController.getString(R.string.BusinessHoursProfileClose));
} else {
for (int j = 0; j < periods.size(); ++j) {
if (j > 0) sb.append(", ");
OpeningHoursActivity.Period p = periods.get(j);
sb.append(OpeningHoursActivity.Period.timeToString(p.start));
sb.append(" - ");
sb.append(OpeningHoursActivity.Period.timeToString(p.end));
}
}
sb.append("\n");
}
TLRPC.TL_timezone timezone = TimezonesController.getInstance(currentAccount).findTimezone(business_work_hours.timezone_id);
Calendar calendar = Calendar.getInstance();
int currentUtcOffset = calendar.getTimeZone().getRawOffset() / 1000;
int valueUtcOffset = timezone == null ? 0 : timezone.utc_offset;
int utcOffset = (currentUtcOffset - valueUtcOffset) / 60;
if (utcOffset != 0 && timezone != null) {
sb.append(formatString(R.string.BusinessHoursCopyFooter, TimezonesController.getInstance(currentAccount).getTimezoneName(timezone, true)));
}
return sb.toString();
}
private void processDone() { private void processDone() {
if (doneButtonDrawable.getProgress() > 0f) return; if (doneButtonDrawable.getProgress() > 0f) return;

View file

@ -132,7 +132,7 @@ public class OpeningHoursDayActivity extends BaseFragment {
if (periods.size() >= maxPeriodsCount) { if (periods.size() >= maxPeriodsCount) {
return false; return false;
} }
return periods.isEmpty() || is24() || periods.get(periods.size() - 1).end < max - 2; return periods.isEmpty() || is24() || periods.get(periods.size() - 1).end < Math.min(24 * 60 - 2, max - 2);
} }
private void onClick(UItem item, View view, int position, float x, float y) { private void onClick(UItem item, View view, int position, float x, float y) {

View file

@ -204,7 +204,7 @@ public class ProfileHoursCell extends LinearLayout {
TLRPC.TL_timezone timezone = timezonesController.findTimezone(value.timezone_id); TLRPC.TL_timezone timezone = timezonesController.findTimezone(value.timezone_id);
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
int currentUtcOffset = calendar.getTimeZone().getRawOffset() / 1000; int currentUtcOffset = calendar.getTimeZone().getOffset(System.currentTimeMillis()) / 1000;
int valueUtcOffset = timezone == null ? 0 : timezone.utc_offset; int valueUtcOffset = timezone == null ? 0 : timezone.utc_offset;
int utcOffset = (currentUtcOffset - valueUtcOffset) / 60; int utcOffset = (currentUtcOffset - valueUtcOffset) / 60;
switchText.setVisibility(utcOffset != 0 && !is24x7 ? View.VISIBLE : View.GONE); switchText.setVisibility(utcOffset != 0 && !is24x7 ? View.VISIBLE : View.GONE);
@ -287,15 +287,15 @@ public class ProfileHoursCell extends LinearLayout {
TextView textView = k == 0 ? timeText[i][a] : labelTimeText[a]; TextView textView = k == 0 ? timeText[i][a] : labelTimeText[a];
if (i == 0 && !open_now && k == 1) { if (i == 0 && !open_now && k == 1) {
int opensPeriodTime = -1; int opensPeriodTime = -1;
for (int j = 0; j < weekly_open.size(); ++j) { for (int j = 0; j < adapted_weekly_open.size(); ++j) {
TLRPC.TL_businessWeeklyOpen weekly = weekly_open.get(j); TLRPC.TL_businessWeeklyOpen weekly = adapted_weekly_open.get(j);
if (nowPeriodTime < weekly.start_minute) { if (nowPeriodTime < weekly.start_minute) {
opensPeriodTime = weekly.start_minute; opensPeriodTime = weekly.start_minute;
break; break;
} }
} }
if (opensPeriodTime == -1 && !weekly_open.isEmpty()) { if (opensPeriodTime == -1 && !adapted_weekly_open.isEmpty()) {
opensPeriodTime = weekly_open.get(0).start_minute; opensPeriodTime = adapted_weekly_open.get(0).start_minute;
} }
if (opensPeriodTime == -1) { if (opensPeriodTime == -1) {
textView.setText(getString(R.string.BusinessHoursProfileClose)); textView.setText(getString(R.string.BusinessHoursProfileClose));

View file

@ -148,7 +148,7 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
private LinearLayoutManager layoutManager; private LinearLayoutManager layoutManager;
AlertDialog progressDialog; AlertDialog progressDialog;
private boolean[] selected = new boolean[] { true, true, true, true, true, true, true, true, true, true }; private boolean[] selected = new boolean[] { true, true, true, true, true, true, true, true, true, true, true };
private long databaseSize = -1; private long databaseSize = -1;
private long cacheSize = -1, cacheEmojiSize = -1, cacheTempSize = -1; private long cacheSize = -1, cacheEmojiSize = -1, cacheTempSize = -1;
private long documentsSize = -1; private long documentsSize = -1;
@ -157,6 +157,7 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
private long musicSize = -1; private long musicSize = -1;
private long photoSize = -1; private long photoSize = -1;
private long videoSize = -1; private long videoSize = -1;
private long logsSize = -1;
private long stickersCacheSize = -1; private long stickersCacheSize = -1;
private long totalSize = -1; private long totalSize = -1;
private long totalDeviceSize = -1; private long totalDeviceSize = -1;
@ -247,7 +248,11 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
stickersCacheSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 3); stickersCacheSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 3);
long audioSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), 0); long audioSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), 0);
long storiesSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_STORIES), 0); long storiesSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_STORIES), 0);
final long totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + videoSize + audioSize + photoSize + documentsSize + musicSize + stickersCacheSize + storiesSize; long logsSize = getDirectorySize(AndroidUtilities.getLogsDir(), 1);
if (!BuildVars.DEBUG_VERSION && logsSize < 1024 * 1024 * 256) {
logsSize = 0;
}
final long totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + videoSize + audioSize + photoSize + documentsSize + musicSize + stickersCacheSize + storiesSize + logsSize;
lastTotalSizeCalculatedTime = System.currentTimeMillis(); lastTotalSizeCalculatedTime = System.currentTimeMillis();
if (!canceled) { if (!canceled) {
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
@ -349,6 +354,13 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
if (canceled) { if (canceled) {
return; return;
} }
logsSize = getDirectorySize(AndroidUtilities.getLogsDir(), 1);
if (!BuildVars.DEBUG_VERSION && logsSize < 1024 * 1024 * 256) {
logsSize = 0;
}
if (canceled) {
return;
}
documentsSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 1); documentsSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 1);
documentsSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 1); documentsSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 1);
if (canceled) { if (canceled) {
@ -373,7 +385,7 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
if (canceled) { if (canceled) {
return; return;
} }
totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + videoSize + audioSize + photoSize + documentsSize + musicSize + storiesSize + stickersCacheSize; totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + videoSize + logsSize + audioSize + photoSize + documentsSize + musicSize + storiesSize + stickersCacheSize;
lastTotalSizeCalculatedTime = System.currentTimeMillis(); lastTotalSizeCalculatedTime = System.currentTimeMillis();
File path; File path;
@ -440,13 +452,13 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
private void updateChart() { private void updateChart() {
if (cacheChart != null) { if (cacheChart != null) {
if (!calculating && totalSize > 0) { if (!calculating && totalSize > 0) {
CacheChart.SegmentSize[] segments = new CacheChart.SegmentSize[10]; CacheChart.SegmentSize[] segments = new CacheChart.SegmentSize[11];
for (int i = 0; i < itemInners.size(); ++i) { for (int i = 0; i < itemInners.size(); ++i) {
ItemInner item = itemInners.get(i); ItemInner item = itemInners.get(i);
if (item.viewType == VIEW_TYPE_SECTION) { if (item.viewType == VIEW_TYPE_SECTION) {
if (item.index < 0) { if (item.index < 0) {
if (collapsed) { if (collapsed) {
segments[9] = CacheChart.SegmentSize.of(item.size, selected[9]); segments[10] = CacheChart.SegmentSize.of(item.size, selected[10]);
} }
} else { } else {
segments[item.index] = CacheChart.SegmentSize.of(item.size, selected[item.index]); segments[item.index] = CacheChart.SegmentSize.of(item.size, selected[item.index]);
@ -732,19 +744,22 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
if (cacheTempSize > 0) { if (cacheTempSize > 0) {
sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalMiscellaneousCache), 8, cacheTempSize, Theme.key_statisticChartLine_purple)); sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalMiscellaneousCache), 8, cacheTempSize, Theme.key_statisticChartLine_purple));
} }
if (logsSize > 0) {
sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalLogsCache), 9, logsSize, Theme.key_statisticChartLine_golden));
}
if (!sections.isEmpty()) { if (!sections.isEmpty()) {
Collections.sort(sections, (a, b) -> Long.compare(b.size, a.size)); Collections.sort(sections, (a, b) -> Long.compare(b.size, a.size));
sections.get(sections.size() - 1).last = true; sections.get(sections.size() - 1).last = true;
hasCache = true; hasCache = true;
if (tempSizes == null) { if (tempSizes == null) {
tempSizes = new float[10]; tempSizes = new float[11];
} }
for (int i = 0; i < tempSizes.length; ++i) { for (int i = 0; i < tempSizes.length; ++i) {
tempSizes[i] = (float) size(i); tempSizes[i] = (float) size(i);
} }
if (percents == null) { if (percents == null) {
percents = new int[10]; percents = new int[11];
} }
AndroidUtilities.roundPercents(tempSizes, percents); AndroidUtilities.roundPercents(tempSizes, percents);
@ -758,7 +773,7 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
sum += sections.get(i).size; sum += sections.get(i).size;
sumPercents += percents[sections.get(i).index]; sumPercents += percents[sections.get(i).index];
} }
percents[9] = sumPercents; percents[10] = sumPercents;
itemInners.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalOther), -1, sum, Theme.key_statisticChartLine_golden)); itemInners.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalOther), -1, sum, Theme.key_statisticChartLine_golden));
if (!collapsed) { if (!collapsed) {
itemInners.addAll(sections.subList(MAX_NOT_COLLAPSED, sections.size())); itemInners.addAll(sections.subList(MAX_NOT_COLLAPSED, sections.size()));
@ -964,7 +979,7 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
long clearedSize = 0; long clearedSize = 0;
boolean allItemsClear = true; boolean allItemsClear = true;
final int[] clearDirI = new int[] { 0 }; final int[] clearDirI = new int[] { 0 };
int clearDirCount = (selected[0] ? 2 : 0) + (selected[1] ? 2 : 0) + (selected[2] ? 2 : 0) + (selected[3] ? 2 : 0) + (selected[4] ? 1 : 0) + (selected[5] ? 2 : 0) + (selected[6] ? 1 : 0) + (selected[7] ? 1 : 0) + (selected[8] ? 1 : 0); int clearDirCount = (selected[0] ? 2 : 0) + (selected[1] ? 2 : 0) + (selected[2] ? 2 : 0) + (selected[3] ? 2 : 0) + (selected[4] ? 1 : 0) + (selected[5] ? 2 : 0) + (selected[6] ? 1 : 0) + (selected[7] ? 1 : 0) + (selected[8] ? 1 : 0) + (selected[9] ? 1 : 0);
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
Utilities.Callback<Float> updateProgress = t -> { Utilities.Callback<Float> updateProgress = t -> {
onProgress.run(clearDirI[0] / (float) clearDirCount + (1f / clearDirCount) * MathUtils.clamp(t, 0, 1), false); onProgress.run(clearDirI[0] / (float) clearDirCount + (1f / clearDirCount) * MathUtils.clamp(t, 0, 1), false);
@ -973,7 +988,7 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
final long now = System.currentTimeMillis(); final long now = System.currentTimeMillis();
onProgress.run(clearDirI[0] / (float) clearDirCount, now - time > 250); onProgress.run(clearDirI[0] / (float) clearDirCount, now - time > 250);
}; };
for (int a = 0; a < 9; a++) { for (int a = 0; a < 10; a++) {
if (!selected[a]) { if (!selected[a]) {
allItemsClear = false; allItemsClear = false;
continue; continue;
@ -1011,12 +1026,18 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
clearedSize += cacheTempSize; clearedSize += cacheTempSize;
documentsMusicType = 4; documentsMusicType = 4;
type = FileLoader.MEDIA_DIR_CACHE; type = FileLoader.MEDIA_DIR_CACHE;
} else if (a == 9) {
clearedSize += logsSize;
documentsMusicType = 1;
type = 0;
} }
if (type == -1) { if (type == -1) {
continue; continue;
} }
File file; File file;
if (type == 100) { if (a == 9) {
file = AndroidUtilities.getLogsDir();
} else if (type == 100) {
file = new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"); file = new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache");
} else { } else {
file = FileLoader.checkDirectory(type); file = FileLoader.checkDirectory(type);
@ -1058,7 +1079,9 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
next.run(); next.run();
} }
if (type == FileLoader.MEDIA_DIR_CACHE) { if (a == 9) {
logsSize = getDirectorySize(AndroidUtilities.getLogsDir(), 1);
} else if (type == FileLoader.MEDIA_DIR_CACHE) {
cacheSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 5); cacheSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 5);
cacheTempSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 4); cacheTempSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 4);
imagesCleared = true; imagesCleared = true;
@ -1089,7 +1112,7 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
} }
} }
final boolean imagesClearedFinal = imagesCleared; final boolean imagesClearedFinal = imagesCleared;
totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + videoSize + audioSize + photoSize + documentsSize + musicSize + stickersCacheSize + storiesSize; totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + logsSize + videoSize + audioSize + photoSize + documentsSize + musicSize + stickersCacheSize + storiesSize;
lastTotalSizeCalculatedTime = System.currentTimeMillis(); lastTotalSizeCalculatedTime = System.currentTimeMillis();
Arrays.fill(selected, true); Arrays.fill(selected, true);
@ -1181,13 +1204,14 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
case 6: return stickersCacheSize; case 6: return stickersCacheSize;
case 7: return cacheSize; case 7: return cacheSize;
case 8: return cacheTempSize; case 8: return cacheTempSize;
case 9: return logsSize;
default: return 0; default: return 0;
} }
} }
private int sectionsSelected() { private int sectionsSelected() {
int count = 0; int count = 0;
for (int i = 0; i < 9; ++i) { for (int i = 0; i < 10; ++i) {
if (selected[i] && size(i) > 0) { if (selected[i] && size(i) > 0) {
count++; count++;
} }
@ -2068,7 +2092,8 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
(selected[5] ? storiesSize : 0) + (selected[5] ? storiesSize : 0) +
(selected[6] ? stickersCacheSize : 0) + (selected[6] ? stickersCacheSize : 0) +
(selected[7] ? cacheSize : 0) + (selected[7] ? cacheSize : 0) +
(selected[8] ? cacheTempSize : 0) (selected[8] ? cacheTempSize : 0) +
(selected[9] ? logsSize : 0)
); );
setSize( setSize(
isAllSectionsSelected(), isAllSectionsSelected(),
@ -2581,7 +2606,7 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
final ItemInner item = itemInners.get(position); final ItemInner item = itemInners.get(position);
switch (holder.getItemViewType()) { switch (holder.getItemViewType()) {
case VIEW_TYPE_CHART: case VIEW_TYPE_CHART:
// updateChart(); updateChart();
break; break;
case VIEW_TYPE_CHART_HEADER: case VIEW_TYPE_CHART_HEADER:
if (cacheChartHeader != null && !calculating) { if (cacheChartHeader != null && !calculating) {
@ -2668,7 +2693,6 @@ public class CacheControlActivity extends BaseFragment implements NotificationCe
headerCell.setTopMargin(itemInners.get(position).headerTopMargin); headerCell.setTopMargin(itemInners.get(position).headerTopMargin);
headerCell.setBottomMargin(itemInners.get(position).headerBottomMargin); headerCell.setBottomMargin(itemInners.get(position).headerBottomMargin);
break; break;
} }
} }

View file

@ -113,7 +113,7 @@ public class AccountSelectCell extends FrameLayout {
} else { } else {
TLRPC.Chat chat = (TLRPC.Chat) object; TLRPC.Chat chat = (TLRPC.Chat) object;
avatarDrawable.setInfo(chat); avatarDrawable.setInfo(chat);
infoTextView.setText(chat.title); infoTextView.setText(chat == null ? "" : chat.title);
imageView.setForUserOrChat(chat, avatarDrawable); imageView.setForUserOrChat(chat, avatarDrawable);
} }
} }

View file

@ -76,6 +76,7 @@ import org.telegram.tgnet.tl.TL_stories;
import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.ChannelAdminLogActivity;
import org.telegram.ui.ChatBackgroundDrawable; import org.telegram.ui.ChatBackgroundDrawable;
import org.telegram.ui.Components.AnimatedEmojiDrawable; import org.telegram.ui.Components.AnimatedEmojiDrawable;
import org.telegram.ui.Components.AnimatedEmojiSpan; import org.telegram.ui.Components.AnimatedEmojiSpan;
@ -89,16 +90,19 @@ import org.telegram.ui.Components.Premium.StarParticlesView;
import org.telegram.ui.Components.RLottieDrawable; import org.telegram.ui.Components.RLottieDrawable;
import org.telegram.ui.Components.RadialProgress2; import org.telegram.ui.Components.RadialProgress2;
import org.telegram.ui.Components.RadialProgressView; import org.telegram.ui.Components.RadialProgressView;
import org.telegram.ui.Components.ScaleStateListAnimator;
import org.telegram.ui.Components.TypefaceSpan; import org.telegram.ui.Components.TypefaceSpan;
import org.telegram.ui.Components.URLSpanNoUnderline; import org.telegram.ui.Components.URLSpanNoUnderline;
import org.telegram.ui.Components.spoilers.SpoilerEffect; import org.telegram.ui.Components.spoilers.SpoilerEffect;
import org.telegram.ui.LaunchActivity; import org.telegram.ui.LaunchActivity;
import org.telegram.ui.PhotoViewer; import org.telegram.ui.PhotoViewer;
import org.telegram.ui.ProfileActivity;
import org.telegram.ui.Stories.StoriesUtilities; import org.telegram.ui.Stories.StoriesUtilities;
import org.telegram.ui.Stories.UploadingDotsSpannable; import org.telegram.ui.Stories.UploadingDotsSpannable;
import org.telegram.ui.Stories.recorder.HintView2; import org.telegram.ui.Stories.recorder.HintView2;
import org.telegram.ui.Stories.recorder.PreviewView; import org.telegram.ui.Stories.recorder.PreviewView;
import java.nio.channels.Channel;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -459,6 +463,17 @@ public class ChatActionCell extends BaseCell implements DownloadController.FileD
if (messageObject.type != MessageObject.TYPE_ACTION_WALLPAPER) { if (messageObject.type != MessageObject.TYPE_ACTION_WALLPAPER) {
wallpaperPreviewDrawable = null; wallpaperPreviewDrawable = null;
} }
if (messageObject.actionDeleteGroupEventId != -1) {
ScaleStateListAnimator.apply(this, .02f, 1.2f);
overriddenMaxWidth = Math.max(dp(250), HintView2.cutInFancyHalf(messageObject.messageText, (TextPaint) getThemedPaint(Theme.key_paint_chatActionText)));
ProfileActivity.ShowDrawable showDrawable = ChannelAdminLogActivity.findDrawable(messageObject.messageText);
if (showDrawable != null) {
showDrawable.setView(this);
}
} else {
ScaleStateListAnimator.reset(this);
overriddenMaxWidth = 0;
}
if (messageObject.isStoryMention()) { if (messageObject.isStoryMention()) {
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(messageObject.messageOwner.media.user_id); TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(messageObject.messageOwner.media.user_id);
avatarDrawable.setInfo(currentAccount, user); avatarDrawable.setInfo(currentAccount, user);
@ -1804,7 +1819,7 @@ public class ChatActionCell extends BaseCell implements DownloadController.FileD
int lineWidth = (int) Math.ceil(textLayout.getLineWidth(a)); int lineWidth = (int) Math.ceil(textLayout.getLineWidth(a));
if (a != 0) { if (a != 0) {
int diff = prevLineWidth - lineWidth; int diff = prevLineWidth - lineWidth;
if (diff > 0 && diff <= corner + cornerIn) { if (diff > 0 && diff <= 1.5f * corner + cornerIn) {
lineWidth = prevLineWidth; lineWidth = prevLineWidth;
} }
} }
@ -1814,7 +1829,7 @@ public class ChatActionCell extends BaseCell implements DownloadController.FileD
for (int a = count - 2; a >= 0; a--) { for (int a = count - 2; a >= 0; a--) {
int lineWidth = lineWidths.get(a); int lineWidth = lineWidths.get(a);
int diff = prevLineWidth - lineWidth; int diff = prevLineWidth - lineWidth;
if (diff > 0 && diff <= corner + cornerIn) { if (diff > 0 && diff <= 1.5f * corner + cornerIn) {
lineWidth = prevLineWidth; lineWidth = prevLineWidth;
} }
lineWidths.set(a, lineWidth); lineWidths.set(a, lineWidth);

View file

@ -128,6 +128,7 @@ import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.tgnet.tl.TL_stories; import org.telegram.tgnet.tl.TL_stories;
import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.AvatarSpan;
import org.telegram.ui.ChatActivity; import org.telegram.ui.ChatActivity;
import org.telegram.ui.Components.AnimatedEmojiDrawable; import org.telegram.ui.Components.AnimatedEmojiDrawable;
import org.telegram.ui.Components.AnimatedEmojiSpan; import org.telegram.ui.Components.AnimatedEmojiSpan;
@ -145,6 +146,7 @@ import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.EmptyStubSpan; import org.telegram.ui.Components.EmptyStubSpan;
import org.telegram.ui.Components.FloatSeekBarAccessibilityDelegate; import org.telegram.ui.Components.FloatSeekBarAccessibilityDelegate;
import org.telegram.ui.Components.Forum.MessageTopicButton; import org.telegram.ui.Components.Forum.MessageTopicButton;
import org.telegram.ui.Components.ForwardBackground;
import org.telegram.ui.Components.InfiniteProgress; import org.telegram.ui.Components.InfiniteProgress;
import org.telegram.ui.Components.LinkPath; import org.telegram.ui.Components.LinkPath;
import org.telegram.ui.Components.LinkSpanDrawable; import org.telegram.ui.Components.LinkSpanDrawable;
@ -169,6 +171,7 @@ import org.telegram.ui.Components.SeekBarAccessibilityDelegate;
import org.telegram.ui.Components.SeekBarWaveform; import org.telegram.ui.Components.SeekBarWaveform;
import org.telegram.ui.Components.SlotsDrawable; import org.telegram.ui.Components.SlotsDrawable;
import org.telegram.ui.Components.StaticLayoutEx; import org.telegram.ui.Components.StaticLayoutEx;
import org.telegram.ui.Components.StickerSetLinkIcon;
import org.telegram.ui.Components.TextStyleSpan; import org.telegram.ui.Components.TextStyleSpan;
import org.telegram.ui.Components.TimerParticles; import org.telegram.ui.Components.TimerParticles;
import org.telegram.ui.Components.TranscribeButton; import org.telegram.ui.Components.TranscribeButton;
@ -292,23 +295,8 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
avatarDrawable.setInfo(currentAccount, currentChat); avatarDrawable.setInfo(currentAccount, currentChat);
avatarImage.setForUserOrChat(currentChat, avatarDrawable); avatarImage.setForUserOrChat(currentChat, avatarDrawable);
} else if (messageObject.isSponsored()) { } else if (messageObject.isSponsored()) {
if (messageObject.sponsoredWebPage != null) { if (messageObject.sponsoredPhoto != null) {
avatarDrawable.setInfo(messageObject.sponsoredId[0], messageObject.sponsoredWebPage.site_name, null, null); avatarImage.setImage(ImageLocation.getForPhoto(FileLoader.getClosestPhotoSizeWithSize(messageObject.sponsoredPhoto.sizes, AndroidUtilities.dp(50), false, null, true), messageObject.sponsoredPhoto), "50_50", avatarDrawable, null, null, 0);
TLRPC.Photo photo = messageObject.sponsoredWebPage.photo;
if (photo != null) {
avatarImage.setImage(ImageLocation.getForPhoto(FileLoader.getClosestPhotoSizeWithSize(photo.sizes, AndroidUtilities.dp(50), false, null, true), photo), "50_50", avatarDrawable, null, null, 0);
}
} else if (messageObject.sponsoredChatInvite != null && messageObject.sponsoredChatInvite.chat != null) {
avatarDrawable.setInfo(currentAccount, messageObject.sponsoredChatInvite.chat);
avatarImage.setForUserOrChat(messageObject.sponsoredChatInvite.chat, avatarDrawable);
} else {
avatarDrawable.setInfo(currentAccount, messageObject.sponsoredChatInvite);
if (messageObject.sponsoredChatInvite != null) {
TLRPC.Photo photo = messageObject.sponsoredChatInvite.photo;
if (photo != null) {
avatarImage.setImage(ImageLocation.getForPhoto(FileLoader.getClosestPhotoSizeWithSize(photo.sizes, AndroidUtilities.dp(50), false, null, true), photo), "50_50", avatarDrawable, null, null, 0);
}
}
} }
} else { } else {
currentPhoto = null; currentPhoto = null;
@ -541,7 +529,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
default void didPressOther(ChatMessageCell cell, float otherX, float otherY) { default void didPressOther(ChatMessageCell cell, float otherX, float otherY) {
} }
default void didPressSponsoredClose() { default void didPressSponsoredClose(ChatMessageCell cell) {
} }
default void didPressSponsoredInfo(ChatMessageCell cell, float x, float y) { default void didPressSponsoredInfo(ChatMessageCell cell, float x, float y) {
@ -559,7 +547,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
default void didPressReaction(ChatMessageCell cell, TLRPC.ReactionCount reaction, boolean longpress) { default void didPressReaction(ChatMessageCell cell, TLRPC.ReactionCount reaction, boolean longpress) {
} }
default void didPressVoteButtons(ChatMessageCell cell, ArrayList<TLRPC.TL_pollAnswer> buttons, int showCount, int x, int y) { default void didPressVoteButtons(ChatMessageCell cell, ArrayList<TLRPC.PollAnswer> buttons, int showCount, int x, int y) {
} }
default void didPressInstantButton(ChatMessageCell cell, int type) { default void didPressInstantButton(ChatMessageCell cell, int type) {
@ -765,12 +753,15 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
private boolean prevChosen; private boolean prevChosen;
private boolean correct; private boolean correct;
private StaticLayout title; private StaticLayout title;
private TLRPC.TL_pollAnswer answer; public AnimatedEmojiSpan.EmojiGroupedSpans animatedEmoji;
private TLRPC.PollAnswer answer;
} }
public static final int INSTANT_BUTTON_TYPE_CONTACT_VIEW = 5; public static final int INSTANT_BUTTON_TYPE_CONTACT_VIEW = 5;
public static final int INSTANT_BUTTON_TYPE_CONTACT_SEND_MESSAGE = 30; public static final int INSTANT_BUTTON_TYPE_CONTACT_SEND_MESSAGE = 30;
public static final int INSTANT_BUTTON_TYPE_CONTACT_ADD = 31; public static final int INSTANT_BUTTON_TYPE_CONTACT_ADD = 31;
public static final int INSTANT_BUTTON_TYPE_STICKER_SET = 23;
public static final int INSTANT_BUTTON_TYPE_EMOJI_SET = 24;
private static class InstantViewButton { private static class InstantViewButton {
private int type; private int type;
@ -847,6 +838,8 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
private Paint onceRadialStrokePaint; private Paint onceRadialStrokePaint;
private int onceRadialPaintColor; private int onceRadialPaintColor;
private StickerSetLinkIcon stickerSetIcons;
private boolean disallowLongPress; private boolean disallowLongPress;
private float lastTouchX; private float lastTouchX;
private float lastTouchY; private float lastTouchY;
@ -861,6 +854,8 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
private long lastCheckBoxAnimationTime; private long lastCheckBoxAnimationTime;
public int checkBoxTranslation; public int checkBoxTranslation;
private AvatarSpan forwardAvatar;
private ForwardBackground forwardBg;
public boolean linkPreviewAbove; public boolean linkPreviewAbove;
private boolean isSmallImage; private boolean isSmallImage;
private boolean drawImageButton; private boolean drawImageButton;
@ -1024,6 +1019,8 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
private BitmapDrawable currentPhotoObjectThumbStripped; private BitmapDrawable currentPhotoObjectThumbStripped;
private String currentPhotoFilter; private String currentPhotoFilter;
private String currentPhotoFilterThumb; private String currentPhotoFilterThumb;
private Drawable foreverDrawable;
private int foreverDrawableColor = 0xFFFFFFFF;
private boolean timePressed; private boolean timePressed;
@ -1367,6 +1364,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
public AnimatedEmojiSpan.EmojiGroupedSpans animatedEmojiStack; public AnimatedEmojiSpan.EmojiGroupedSpans animatedEmojiStack;
public AnimatedEmojiSpan.EmojiGroupedSpans animatedEmojiReplyStack; public AnimatedEmojiSpan.EmojiGroupedSpans animatedEmojiReplyStack;
public AnimatedEmojiSpan.EmojiGroupedSpans animatedEmojiDescriptionStack; public AnimatedEmojiSpan.EmojiGroupedSpans animatedEmojiDescriptionStack;
public AnimatedEmojiSpan.EmojiGroupedSpans animatedEmojiPollQuestion;
public ButtonBounce replyBounce, contactBounce; public ButtonBounce replyBounce, contactBounce;
public float replyBounceX, replyBounceY; public float replyBounceX, replyBounceY;
public Drawable replySelector; public Drawable replySelector;
@ -2268,7 +2266,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
final float left = descriptionLayout.getLineLeft(line); final float left = descriptionLayout.getLineLeft(line);
if (left <= checkX && left + descriptionLayout.getLineWidth(line) >= checkX) { if (left <= checkX && left + descriptionLayout.getLineWidth(line) >= checkX) {
Spannable buffer = (Spannable) currentMessageObject.linkDescription; Spannable buffer = (Spannable) (currentMessageObject.isSponsored() ? currentMessageObject.messageText : currentMessageObject.linkDescription);
ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);
boolean ignore = false; boolean ignore = false;
if (link.length == 0 || link[0] instanceof URLSpanBotCommand && !URLSpanBotCommand.enabled) { if (link.length == 0 || link[0] instanceof URLSpanBotCommand && !URLSpanBotCommand.enabled) {
@ -2537,9 +2535,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
Toast.makeText(getContext(), LocaleController.getString("MessageScheduledVote", R.string.MessageScheduledVote), Toast.LENGTH_LONG).show(); Toast.makeText(getContext(), LocaleController.getString("MessageScheduledVote", R.string.MessageScheduledVote), Toast.LENGTH_LONG).show();
} else { } else {
PollButton button = pollButtons.get(pressedVoteButton); PollButton button = pollButtons.get(pressedVoteButton);
TLRPC.TL_pollAnswer answer = button.answer; TLRPC.PollAnswer answer = button.answer;
if (pollVoted || pollClosed) { if (pollVoted || pollClosed) {
ArrayList<TLRPC.TL_pollAnswer> answers = new ArrayList<>(); ArrayList<TLRPC.PollAnswer> answers = new ArrayList<>();
answers.add(answer); answers.add(answer);
delegate.didPressVoteButtons(this, answers, button.count, button.x + AndroidUtilities.dp(50), button.y + namesOffset); delegate.didPressVoteButtons(this, answers, button.count, button.x + AndroidUtilities.dp(50), button.y + namesOffset);
} else { } else {
@ -2559,7 +2557,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
firstCircleLength = true; firstCircleLength = true;
voteCurrentCircleLength = 360; voteCurrentCircleLength = 360;
voteRisingCircleLength = false; voteRisingCircleLength = false;
ArrayList<TLRPC.TL_pollAnswer> answers = new ArrayList<>(); ArrayList<TLRPC.PollAnswer> answers = new ArrayList<>();
answers.add(answer); answers.add(answer);
delegate.didPressVoteButtons(this, answers, -1, 0, 0); delegate.didPressVoteButtons(this, answers, -1, 0, 0);
} }
@ -2829,7 +2827,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} else if (event.getAction() == MotionEvent.ACTION_UP) { } else if (event.getAction() == MotionEvent.ACTION_UP) {
if (closeSponsoredBounce != null && closeSponsoredBounce.isPressed()) { if (closeSponsoredBounce != null && closeSponsoredBounce.isPressed()) {
if (delegate != null) { if (delegate != null) {
delegate.didPressSponsoredClose(); delegate.didPressSponsoredClose(this);
} }
} }
if (closeSponsoredBounce != null) { if (closeSponsoredBounce != null) {
@ -3380,7 +3378,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
private boolean checkBotButtonMotionEvent(MotionEvent event) { private boolean checkBotButtonMotionEvent(MotionEvent event) {
if (botButtons.isEmpty() || currentMessageObject.eventId != 0) { if (botButtons.isEmpty()) {
return false; return false;
} }
@ -3669,6 +3667,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (viaWidth != 0 && x >= forwardNameX + viaNameWidth + AndroidUtilities.dp(4)) { if (viaWidth != 0 && x >= forwardNameX + viaNameWidth + AndroidUtilities.dp(4)) {
forwardBotPressed = true; forwardBotPressed = true;
} else { } else {
if (forwardBg != null) {
forwardBg.setPressed(true, x - forwardNameX, y - forwardNameY);
}
forwardNamePressed = true; forwardNamePressed = true;
} }
result = true; result = true;
@ -3760,7 +3761,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
id = 0; id = 0;
} }
delegate.didPressChannelAvatar(this, chat != null ? chat : currentChat, id, lastTouchX, lastTouchY); delegate.didPressChannelAvatar(this, chat != null ? chat : currentChat, id, lastTouchX, lastTouchY);
} else if (currentMessageObject != null && currentMessageObject.sponsoredChatInvite != null) { } else if (currentMessageObject != null) {
delegate.didPressInstantButton(this, drawInstantViewType); delegate.didPressInstantButton(this, drawInstantViewType);
} }
} }
@ -3784,6 +3785,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} else if (forwardNamePressed) { } else if (forwardNamePressed) {
if (event.getAction() == MotionEvent.ACTION_UP) { if (event.getAction() == MotionEvent.ACTION_UP) {
forwardNamePressed = false; forwardNamePressed = false;
if (forwardBg != null) {
forwardBg.setPressed(false);
}
playSoundEffect(SoundEffectConstants.CLICK); playSoundEffect(SoundEffectConstants.CLICK);
if (delegate != null) { if (delegate != null) {
if (currentForwardChannel != null) { if (currentForwardChannel != null) {
@ -3800,9 +3804,15 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) { } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
forwardNamePressed = false; forwardNamePressed = false;
if (forwardBg != null) {
forwardBg.setPressed(false);
}
} else if (event.getAction() == MotionEvent.ACTION_MOVE) { } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (!(x >= forwardNameX && x <= forwardNameX + forwardedNameWidth && y >= forwardNameY && y <= forwardNameY + forwardHeight)) { if (!(x >= forwardNameX && x <= forwardNameX + forwardedNameWidth && y >= forwardNameY && y <= forwardNameY + forwardHeight)) {
forwardNamePressed = false; forwardNamePressed = false;
if (forwardBg != null) {
forwardBg.setPressed(false);
}
} }
} }
} else if (forwardBotPressed) { } else if (forwardBotPressed) {
@ -3902,7 +3912,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
playSoundEffect(SoundEffectConstants.CLICK); playSoundEffect(SoundEffectConstants.CLICK);
if (delegate != null) { if (delegate != null) {
if (pressedSideButton == SIDE_BUTTON_SPONSORED_CLOSE) { if (pressedSideButton == SIDE_BUTTON_SPONSORED_CLOSE) {
delegate.didPressSponsoredClose(); delegate.didPressSponsoredClose(this);
} else if (pressedSideButton == SIDE_BUTTON_SPONSORED_MORE) { } else if (pressedSideButton == SIDE_BUTTON_SPONSORED_MORE) {
delegate.didPressSponsoredInfo(this, x, y); delegate.didPressSponsoredInfo(this, x, y);
} else if (pressedSideButton == 3) { } else if (pressedSideButton == 3) {
@ -4697,6 +4707,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
ImageLoader.getInstance().removeTestWebFile(currentUrl); ImageLoader.getInstance().removeTestWebFile(currentUrl);
addedForTest = false; addedForTest = false;
} }
if (stickerSetIcons != null) {
stickerSetIcons.detach(this);
}
DownloadController.getInstance(currentAccount).removeLoadingFileObserver(this); DownloadController.getInstance(currentAccount).removeLoadingFileObserver(this);
if (getDelegate() != null && getDelegate().getTextSelectionHelper() != null) { if (getDelegate() != null && getDelegate().getTextSelectionHelper() != null) {
@ -4823,6 +4836,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (channelRecommendationsCell != null) { if (channelRecommendationsCell != null) {
channelRecommendationsCell.onAttachedToWindow(); channelRecommendationsCell.onAttachedToWindow();
} }
if (stickerSetIcons != null) {
stickerSetIcons.attach(this);
}
} }
public void copySpoilerEffect2AttachIndexFrom(ChatMessageCell cell) { public void copySpoilerEffect2AttachIndexFrom(ChatMessageCell cell) {
@ -5057,6 +5073,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
groupChanged = newPosition != currentPosition; groupChanged = newPosition != currentPosition;
} }
if (messageChanged || dataChanged || groupChanged || pollChanged || widthChanged && messageObject.isPoll() || isPhotoDataChanged(messageObject) || pinnedBottom != bottomNear || pinnedTop != topNear) { if (messageChanged || dataChanged || groupChanged || pollChanged || widthChanged && messageObject.isPoll() || isPhotoDataChanged(messageObject) || pinnedBottom != bottomNear || pinnedTop != topNear) {
if (stickerSetIcons != null) {
stickerSetIcons.readyToDie();
}
wasPinned = isPinned; wasPinned = isPinned;
pinnedBottom = bottomNear; pinnedBottom = bottomNear;
pinnedTop = topNear; pinnedTop = topNear;
@ -5519,6 +5538,8 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
TLRPC.Document androidThemeDocument = null; TLRPC.Document androidThemeDocument = null;
TL_stories.StoryItem storyItem = null; TL_stories.StoryItem storyItem = null;
TLRPC.ThemeSettings androidThemeSettings = null; TLRPC.ThemeSettings androidThemeSettings = null;
ArrayList<TLRPC.Document> stickers = null;
boolean stickersTextColor = false;
if (messageObject.isGiveawayOrGiveawayResults()) { if (messageObject.isGiveawayOrGiveawayResults()) {
hasLinkPreview = true; hasLinkPreview = true;
} }
@ -5531,22 +5552,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
drawInstantView = true; drawInstantView = true;
hasLinkPreview = true; hasLinkPreview = true;
instantViewButtonText = messageObject.sponsoredButtonText; instantViewButtonText = messageObject.sponsoredButtonText;
if (messageObject.sponsoredBotApp != null) {
drawInstantViewType = 15;
} else if (messageObject.sponsoredWebPage != null) {
drawInstantViewType = 16;
} else if (messageObject.sponsoredChannelPost != 0) {
drawInstantViewType = 12;
} else {
drawInstantViewType = 1; drawInstantViewType = 1;
long id = MessageObject.getPeerId(messageObject.messageOwner.from_id);
if (id > 0) {
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(id);
if (user != null && user.bot) {
drawInstantViewType = 10;
}
}
}
} else if (messageObject.isGiveawayOrGiveawayResults()) { } else if (messageObject.isGiveawayOrGiveawayResults()) {
drawInstantView = true; drawInstantView = true;
drawInstantViewType = 19; drawInstantViewType = 19;
@ -5698,6 +5704,25 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} catch (Exception ignore) { } catch (Exception ignore) {
} }
} else if ("telegram_stickerset".equals(webpageType)) {
TLRPC.TL_webPageAttributeStickerSet attr = null;
for (int i = 0; i < webpage.attributes.size(); ++i) {
if (webpage.attributes.get(i) instanceof TLRPC.TL_webPageAttributeStickerSet) {
attr = (TLRPC.TL_webPageAttributeStickerSet) webpage.attributes.get(i);
break;
}
}
drawInstantView = true;
if (attr != null && attr.emojis) {
drawInstantViewType = 24;
} else {
drawInstantViewType = 23;
}
isSmallImage = true;
if (attr != null) {
stickers = attr.stickers;
stickersTextColor = attr.text_color;
}
} }
} else if (siteName != null) { } else if (siteName != null) {
siteName = siteName.toLowerCase(); siteName = siteName.toLowerCase();
@ -5840,27 +5865,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
photo = null; photo = null;
author = null; author = null;
document = null; document = null;
if (messageObject.sponsoredBotApp != null) { photo = messageObject.sponsoredPhoto;
photo = messageObject.sponsoredBotApp.photo;
} else if (messageObject.sponsoredWebPage != null) {
photo = messageObject.sponsoredWebPage.photo;
} else if (messageObject.sponsoredChatInvite != null && messageObject.sponsoredChatInvite.chat != null) {
peerPhoto = messageObject.sponsoredChatInvite.chat;
currentPhotoLocation = ImageLocation.getForChat(messageObject.sponsoredChatInvite.chat, ImageLocation.TYPE_BIG);
currentPhotoThumbLocation = ImageLocation.getForChat(messageObject.sponsoredChatInvite.chat, ImageLocation.TYPE_SMALL);
} else if (messageObject.sponsoredShowPeerPhoto) {
peerPhoto = messageObject.getFromPeerObject();
if (peerPhoto instanceof TLRPC.User) {
currentPhotoLocation = ImageLocation.getForUser((TLRPC.User) peerPhoto, ImageLocation.TYPE_BIG);
currentPhotoThumbLocation = ImageLocation.getForUser((TLRPC.User) peerPhoto, ImageLocation.TYPE_SMALL);
} else if (peerPhoto instanceof TLRPC.Chat) {
currentPhotoLocation = ImageLocation.getForChat((TLRPC.Chat) peerPhoto, ImageLocation.TYPE_BIG);
currentPhotoThumbLocation = ImageLocation.getForChat((TLRPC.Chat) peerPhoto, ImageLocation.TYPE_SMALL);
}
}
if (photo == null && messageObject.sponsoredChatInvite != null) {
photo = messageObject.sponsoredChatInvite.photo;
}
duration = 0; duration = 0;
type = null; type = null;
isSmallImage = photo != null || peerPhoto != null; isSmallImage = photo != null || peerPhoto != null;
@ -5928,9 +5933,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
"telegram_user".equals(type) || "telegram_channel".equals(type) || "telegram_user".equals(type) || "telegram_channel".equals(type) ||
"telegram_megagroup".equals(type) || "telegram_voicechat".equals(type) || "telegram_megagroup".equals(type) || "telegram_voicechat".equals(type) ||
"telegram_livestream".equals(type) || "telegram_channel_boost".equals(type) || "telegram_group_boost".equals(type); "telegram_livestream".equals(type) || "telegram_channel_boost".equals(type) || "telegram_group_boost".equals(type);
smallImage = !slideshow && (!drawInstantView || drawInstantViewType == 1 || drawInstantViewType == 2 || drawInstantViewType == 9 || drawInstantViewType == 11 || drawInstantViewType == 13 || drawInstantViewType == 18 || drawInstantViewType == 20 || drawInstantViewType == 22) && document == null && isSmallImageType; smallImage = !slideshow && (!drawInstantView || drawInstantViewType == 1 || drawInstantViewType == 2 || drawInstantViewType == 9 || drawInstantViewType == 11 || drawInstantViewType == 13 || drawInstantViewType == 18 || drawInstantViewType == 20 || drawInstantViewType == 22) && document == null && isSmallImageType || (drawInstantViewType == 23 || drawInstantViewType == 24) && stickers != null && !stickers.isEmpty();
TLRPC.MessageMedia media = MessageObject.getMedia(messageObject.messageOwner); TLRPC.MessageMedia media = MessageObject.getMedia(messageObject.messageOwner);
if (media != null) { if (media != null && !(drawInstantViewType == 23 || drawInstantViewType == 24)) {
if (media.force_large_media) { if (media.force_large_media) {
smallImage = false; smallImage = false;
} }
@ -5939,7 +5944,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
} }
linkPreviewAbove = currentMessageObject.messageOwner != null && currentMessageObject.messageOwner.invert_media; linkPreviewAbove = currentMessageObject.messageOwner != null && currentMessageObject.messageOwner.invert_media;
isSmallImage = smallImage && type != null && currentMessageObject.photoThumbs != null; isSmallImage = smallImage && type != null && currentMessageObject.photoThumbs != null || (drawInstantViewType == 23 || drawInstantViewType == 24) && stickers != null && !stickers.isEmpty();
} else if (hasInvoicePreview) { } else if (hasInvoicePreview) {
TLRPC.TL_messageMediaInvoice invoice = (TLRPC.TL_messageMediaInvoice) MessageObject.getMedia(messageObject.messageOwner); TLRPC.TL_messageMediaInvoice invoice = (TLRPC.TL_messageMediaInvoice) MessageObject.getMedia(messageObject.messageOwner);
site_name = MessageObject.getMedia(messageObject.messageOwner).title; site_name = MessageObject.getMedia(messageObject.messageOwner).title;
@ -6476,7 +6481,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
if (documentAttachType != DOCUMENT_ATTACH_TYPE_MUSIC && documentAttachType != DOCUMENT_ATTACH_TYPE_AUDIO && documentAttachType != DOCUMENT_ATTACH_TYPE_DOCUMENT) { if (documentAttachType != DOCUMENT_ATTACH_TYPE_MUSIC && documentAttachType != DOCUMENT_ATTACH_TYPE_AUDIO && documentAttachType != DOCUMENT_ATTACH_TYPE_DOCUMENT) {
if (currentPhotoObject != null || currentPhotoLocation != null || webDocument != null || documentAttachType == DOCUMENT_ATTACH_TYPE_WALLPAPER || documentAttachType == DOCUMENT_ATTACH_TYPE_THEME) { if (currentPhotoObject != null || currentPhotoLocation != null || webDocument != null || documentAttachType == DOCUMENT_ATTACH_TYPE_WALLPAPER || documentAttachType == DOCUMENT_ATTACH_TYPE_THEME || (drawInstantViewType == 23 || drawInstantViewType == 24) && stickers != null && !stickers.isEmpty()) {
drawImageButton = photo != null && !smallImage || type != null && (type.equals("photo") || type.equals("document") && documentAttachType != DOCUMENT_ATTACH_TYPE_STICKER || type.equals("gif") || documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO || documentAttachType == DOCUMENT_ATTACH_TYPE_WALLPAPER); drawImageButton = photo != null && !smallImage || type != null && (type.equals("photo") || type.equals("document") && documentAttachType != DOCUMENT_ATTACH_TYPE_STICKER || type.equals("gif") || documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO || documentAttachType == DOCUMENT_ATTACH_TYPE_WALLPAPER);
if (isSmallImage) { if (isSmallImage) {
drawImageButton = false; drawImageButton = false;
@ -6599,7 +6604,21 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
currentPhotoFilter = String.format(Locale.US, "%d_%d", w, h); currentPhotoFilter = String.format(Locale.US, "%d_%d", w, h);
currentPhotoFilterThumb = String.format(Locale.US, "%d_%d_b", w, h); currentPhotoFilterThumb = String.format(Locale.US, "%d_%d_b", w, h);
if (webDocument != null) { if ((drawInstantViewType == 23 || drawInstantViewType == 24) && stickers != null && !stickers.isEmpty()) {
if (stickerSetIcons == null || !stickerSetIcons.equals(stickers)) {
if (stickerSetIcons != null) {
stickerSetIcons.detach(this);
}
stickerSetIcons = new StickerSetLinkIcon(currentAccount, currentMessageObject.isOutOwner(), stickers, stickersTextColor);
if (attachedToWindow) {
stickerSetIcons.attach(this);
}
}
if (stickerSetIcons != null) {
stickerSetIcons.keepAlive();
}
photoImage.setImageBitmap(stickerSetIcons);
} else if (webDocument != null) {
/*TODO*/ /*TODO*/
photoImage.setImage(ImageLocation.getForWebFile(webDocument), currentPhotoFilter, null, null, webDocument.size, null, messageObject, 1); photoImage.setImage(ImageLocation.getForWebFile(webDocument), currentPhotoFilter, null, null, webDocument.size, null, messageObject, 1);
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_WALLPAPER) { } else if (documentAttachType == DOCUMENT_ATTACH_TYPE_WALLPAPER) {
@ -7086,7 +7105,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (pollVoted) { if (pollVoted) {
messageObject.checkedVotes.clear(); messageObject.checkedVotes.clear();
} }
titleLayout = new StaticLayout(Emoji.replaceEmoji(media.poll.question, Theme.chat_audioTitlePaint.getFontMetricsInt(), AndroidUtilities.dp(16), false), Theme.chat_audioTitlePaint, maxWidth + AndroidUtilities.dp(2) - getExtraTextX() * 2, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); CharSequence questionText = new SpannableStringBuilder(media.poll.question.text);
questionText = Emoji.replaceEmoji(questionText, Theme.chat_audioTitlePaint.getFontMetricsInt(), AndroidUtilities.dp(16), false);
if (media.poll.question.entities != null) {
questionText = MessageObject.replaceAnimatedEmoji(questionText, media.poll.question.entities, Theme.chat_audioTitlePaint.getFontMetricsInt(), true);
MessageObject.addEntitiesToText(questionText, media.poll.question.entities, currentMessageObject.isOutOwner(), false, false, false);
}
titleLayout = new StaticLayout(questionText, Theme.chat_audioTitlePaint, maxWidth + AndroidUtilities.dp(2) - getExtraTextX() * 2, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
animatedEmojiPollQuestion = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, false, animatedEmojiPollQuestion, titleLayout);
boolean titleRtl = false; boolean titleRtl = false;
if (titleLayout != null) { if (titleLayout != null) {
for (int a = 0, N = titleLayout.getLineCount(); a < N; a++) { for (int a = 0, N = titleLayout.getLineCount(); a < N; a++) {
@ -7226,9 +7252,18 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
boolean hasDifferent = false; boolean hasDifferent = false;
int previousPercent = 0; int previousPercent = 0;
for (int a = 0, N = media.poll.answers.size(); a < N; a++) { for (int a = 0, N = media.poll.answers.size(); a < N; a++) {
TLRPC.PollAnswer pollAnswer = media.poll.answers.get(a);
CharSequence answerText = new SpannableStringBuilder(pollAnswer.text.text);
answerText = Emoji.replaceEmoji(answerText, Theme.chat_audioTitlePaint.getFontMetricsInt(), AndroidUtilities.dp(16), false);
if (pollAnswer.text.entities != null) {
answerText = MessageObject.replaceAnimatedEmoji(answerText, pollAnswer.text.entities, Theme.chat_audioPerformerPaint.getFontMetricsInt(), true);
MessageObject.addEntitiesToText(answerText, pollAnswer.text.entities, currentMessageObject.isOutOwner(), false, false, false);
}
PollButton button = new PollButton(); PollButton button = new PollButton();
button.answer = media.poll.answers.get(a); button.answer = pollAnswer;
button.title = new StaticLayout(Emoji.replaceEmoji(button.answer.text, Theme.chat_audioPerformerPaint.getFontMetricsInt(), AndroidUtilities.dp(15), false), Theme.chat_audioPerformerPaint, maxWidth - AndroidUtilities.dp(33), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); button.title = new StaticLayout(answerText, Theme.chat_audioPerformerPaint, maxWidth - AndroidUtilities.dp(33), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
button.animatedEmoji = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, false, button.animatedEmoji, button.title);
button.y = height + AndroidUtilities.dp(52); button.y = height + AndroidUtilities.dp(52);
button.height = button.title.getHeight(); button.height = button.title.getHeight();
pollButtons.add(button); pollButtons.add(button);
@ -8937,7 +8972,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (!mediaBackground && !currentMessageObject.isOutOwner()) { if (!mediaBackground && !currentMessageObject.isOutOwner()) {
bl = nearRad; bl = nearRad;
} }
if (currentMessageObject.type == MessageObject.TYPE_GEO && MessageObject.getMedia(currentMessageObject) instanceof TLRPC.TL_messageMediaVenue) { if (currentMessageObject.type == MessageObject.TYPE_GEO && (MessageObject.getMedia(currentMessageObject) instanceof TLRPC.TL_messageMediaVenue || !locationExpired && MessageObject.getMedia(currentMessageObject) instanceof TLRPC.TL_messageMediaGeoLive)) {
br = bl = nearRad; br = bl = nearRad;
} }
if (documentAttachType == DOCUMENT_ATTACH_TYPE_STORY) { if (documentAttachType == DOCUMENT_ATTACH_TYPE_STORY) {
@ -8946,6 +8981,10 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
photoImage.setRoundRadius(tl, tr, br, bl); photoImage.setRoundRadius(tl, tr, br, bl);
} }
updateAnimatedEmojis(); updateAnimatedEmojis();
if (stickerSetIcons != null && stickerSetIcons.die()) {
stickerSetIcons.detach(this);
stickerSetIcons = null;
}
} }
if (messageIdChanged) { if (messageIdChanged) {
currentUrl = null; currentUrl = null;
@ -9155,6 +9194,10 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (topicButton != null) { if (topicButton != null) {
topicButton.resetClick(); topicButton.resetClick();
} }
forwardNamePressed = false;
if (forwardBg != null) {
forwardBg.setPressed(false);
}
if (pressedEmoji != null) { if (pressedEmoji != null) {
// hadLongPress = true; // hadLongPress = true;
// if (delegate.didPressAnimatedEmoji(this, pressedEmoji)) { // if (delegate.didPressAnimatedEmoji(this, pressedEmoji)) {
@ -10056,10 +10099,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
private boolean isCurrentLocationTimeExpired(MessageObject messageObject) { private boolean isCurrentLocationTimeExpired(MessageObject messageObject) {
if (MessageObject.getMedia(currentMessageObject.messageOwner).period % 60 == 0) { final int period = MessageObject.getMedia(currentMessageObject.messageOwner).period;
return Math.abs(ConnectionsManager.getInstance(currentAccount).getCurrentTime() - messageObject.messageOwner.date) > MessageObject.getMedia(messageObject.messageOwner).period; final int currentTime = ConnectionsManager.getInstance(currentAccount).getCurrentTime();
if (period == 0x7fffffff) {
return false;
} else if (period % 60 == 0) {
return Math.abs(currentTime - messageObject.messageOwner.date) > period;
} else { } else {
return Math.abs(ConnectionsManager.getInstance(currentAccount).getCurrentTime() - messageObject.messageOwner.date) > MessageObject.getMedia(messageObject.messageOwner).period - 5; return Math.abs(currentTime - messageObject.messageOwner.date) > period - 5;
} }
} }
@ -10232,52 +10279,56 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (instantViewButtonText != null) { if (instantViewButtonText != null) {
str = instantViewButtonText; str = instantViewButtonText;
} else if (drawInstantViewType == 12) { } else if (drawInstantViewType == 12) {
str = LocaleController.getString("OpenChannelPost", R.string.OpenChannelPost); str = LocaleController.getString(R.string.OpenChannelPost);
} else if (drawInstantViewType == 1) { } else if (drawInstantViewType == 1) {
str = LocaleController.getString("OpenChannel", R.string.OpenChannel); str = LocaleController.getString(R.string.OpenChannel);
} else if (drawInstantViewType == 13) { } else if (drawInstantViewType == 13) {
str = LocaleController.getString("SendMessage", R.string.SendMessage).toUpperCase(); str = LocaleController.getString(R.string.SendMessage).toUpperCase();
} else if (drawInstantViewType == 10) { } else if (drawInstantViewType == 10) {
str = LocaleController.getString("OpenBot", R.string.OpenBot); str = LocaleController.getString(R.string.OpenBot);
} else if (drawInstantViewType == 2) { } else if (drawInstantViewType == 2) {
str = LocaleController.getString("OpenGroup", R.string.OpenGroup); str = LocaleController.getString(R.string.OpenGroup);
} else if (drawInstantViewType == 3) { } else if (drawInstantViewType == 3) {
str = LocaleController.getString("OpenMessage", R.string.OpenMessage); str = LocaleController.getString(R.string.OpenMessage);
} else if (drawInstantViewType == 5) { } else if (drawInstantViewType == 5) {
str = LocaleController.getString("ViewContact", R.string.ViewContact); str = LocaleController.getString(R.string.ViewContact);
} else if (drawInstantViewType == 6) { } else if (drawInstantViewType == 6) {
str = LocaleController.getString("OpenBackground", R.string.OpenBackground); str = LocaleController.getString(R.string.OpenBackground);
} else if (drawInstantViewType == 7) { } else if (drawInstantViewType == 7) {
str = LocaleController.getString("OpenTheme", R.string.OpenTheme); str = LocaleController.getString(R.string.OpenTheme);
} else if (drawInstantViewType == 8) { } else if (drawInstantViewType == 8) {
if (pollVoted || pollClosed) { if (pollVoted || pollClosed) {
str = LocaleController.getString("PollViewResults", R.string.PollViewResults); str = LocaleController.getString(R.string.PollViewResults);
} else { } else {
str = LocaleController.getString("PollSubmitVotes", R.string.PollSubmitVotes); str = LocaleController.getString(R.string.PollSubmitVotes);
} }
} else if (drawInstantViewType == 9 || drawInstantViewType == 11) { } else if (drawInstantViewType == 9 || drawInstantViewType == 11) {
TLRPC.TL_webPage webPage = (TLRPC.TL_webPage) MessageObject.getMedia(currentMessageObject.messageOwner).webpage; TLRPC.TL_webPage webPage = (TLRPC.TL_webPage) MessageObject.getMedia(currentMessageObject.messageOwner).webpage;
if (webPage != null && webPage.url.contains("voicechat=")) { if (webPage != null && webPage.url.contains("voicechat=")) {
str = LocaleController.getString("VoipGroupJoinAsSpeaker", R.string.VoipGroupJoinAsSpeaker); str = LocaleController.getString(R.string.VoipGroupJoinAsSpeaker);
} else { } else {
str = LocaleController.getString("VoipGroupJoinAsLinstener", R.string.VoipGroupJoinAsLinstener); str = LocaleController.getString(R.string.VoipGroupJoinAsLinstener);
} }
} else if (drawInstantViewType == 14) { } else if (drawInstantViewType == 14) {
str = LocaleController.getString("ViewChatList", R.string.ViewChatList).toUpperCase(); str = LocaleController.getString(R.string.ViewChatList).toUpperCase();
} else if (drawInstantViewType == 15) { } else if (drawInstantViewType == 15) {
str = LocaleController.getString(R.string.BotWebAppInstantViewOpen).toUpperCase(); str = LocaleController.getString(R.string.BotWebAppInstantViewOpen).toUpperCase();
} else if (drawInstantViewType == 16) { } else if (drawInstantViewType == 16) {
str = LocaleController.getString("OpenLink").toUpperCase(); str = LocaleController.getString(R.string.OpenLink).toUpperCase();
} else if (drawInstantViewType == 17) { } else if (drawInstantViewType == 17) {
str = LocaleController.getString("ViewStory").toUpperCase(); str = LocaleController.getString(R.string.ViewStory).toUpperCase();
} else if (drawInstantViewType == 18 || drawInstantViewType == 22) { } else if (drawInstantViewType == 18 || drawInstantViewType == 22) {
str = LocaleController.getString("BoostLinkButton", R.string.BoostLinkButton); str = LocaleController.getString(R.string.BoostLinkButton);
} else if (drawInstantViewType == 19) { } else if (drawInstantViewType == 19) {
str = LocaleController.getString("BoostingHowItWork", R.string.BoostingHowItWork); str = LocaleController.getString(R.string.BoostingHowItWork);
} else if (drawInstantViewType == 20) { } else if (drawInstantViewType == 20) {
str = LocaleController.getString(R.string.OpenGift); str = LocaleController.getString(R.string.OpenGift);
} else if (drawInstantViewType == 21) { } else if (drawInstantViewType == 21) {
str = LocaleController.getString(R.string.AppUpdate); str = LocaleController.getString(R.string.AppUpdate);
} else if (drawInstantViewType == 23) {
str = LocaleController.getString(R.string.OpenStickerSet);
} else if (drawInstantViewType == 24) {
str = LocaleController.getString(R.string.OpenEmojiSet);
} else { } else {
str = LocaleController.getString(R.string.InstantView); str = LocaleController.getString(R.string.InstantView);
} }
@ -11990,6 +12041,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
linkLine = new ReplyMessageLine(this); linkLine = new ReplyMessageLine(this);
} }
Theme.chat_replyNamePaint.setColor(linkLine.check(currentMessageObject, currentUser, currentChat, resourcesProvider, ReplyMessageLine.TYPE_LINK)); Theme.chat_replyNamePaint.setColor(linkLine.check(currentMessageObject, currentUser, currentChat, resourcesProvider, ReplyMessageLine.TYPE_LINK));
linkLine.setEmojiAlpha(drawInstantViewType == 23 || drawInstantViewType == 24 ? 0.5f : 1f);
final boolean drawPhotoImageBefore = drawInstantView && (drawInstantViewType != 9 && drawInstantViewType != 2 && drawInstantViewType != 13 && drawInstantViewType != 11 && drawInstantViewType != 1 && drawInstantViewType != 18 && drawInstantViewType != 22) || drawInstantViewType == 6 && imageBackgroundColor != 0; final boolean drawPhotoImageBefore = drawInstantView && (drawInstantViewType != 9 && drawInstantViewType != 2 && drawInstantViewType != 13 && drawInstantViewType != 11 && drawInstantViewType != 1 && drawInstantViewType != 18 && drawInstantViewType != 22) || drawInstantViewType == 6 && imageBackgroundColor != 0;
final boolean drawPhotoImageAfter = !drawInstantView || drawInstantViewType == 9 || drawInstantViewType == 2 || drawInstantViewType == 11 || drawInstantViewType == 13 || drawInstantViewType == 1 || drawInstantViewType == 18 || drawInstantViewType == 22 || isSmallImage; final boolean drawPhotoImageAfter = !drawInstantView || drawInstantViewType == 9 || drawInstantViewType == 2 || drawInstantViewType == 11 || drawInstantViewType == 13 || drawInstantViewType == 1 || drawInstantViewType == 18 || drawInstantViewType == 22 || isSmallImage;
@ -14884,33 +14936,50 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (messageObject.type == MessageObject.TYPE_STORY || currentForwardUser != null || currentForwardChannel != null || currentForwardName != null) { if (messageObject.type == MessageObject.TYPE_STORY || currentForwardUser != null || currentForwardChannel != null || currentForwardName != null) {
String forwardedString; String forwardedString;
CharSequence lastLine; CharSequence lastLine;
if (forwardAvatar == null) {
forwardAvatar = new AvatarSpan(this, currentAccount);
forwardAvatar.translate(0, dp(-.33f));
}
forwardAvatar.setSize((1.23f * ((int) Theme.chat_forwardNamePaint.getTextSize())) / AndroidUtilities.density);
if (messageObject.type == MessageObject.TYPE_STORY) { if (messageObject.type == MessageObject.TYPE_STORY) {
currentForwardNameString = forwardedString = LocaleController.getString("ForwardedStory", R.string.ForwardedStory); currentForwardNameString = forwardedString = LocaleController.getString(R.string.ForwardedStory);
long storyDialogId = DialogObject.getPeerDialogId(messageObject.messageOwner.media.peer); long storyDialogId = DialogObject.getPeerDialogId(messageObject.messageOwner.media.peer);
if (storyDialogId > 0) { if (storyDialogId > 0) {
currentForwardUser = MessagesController.getInstance(currentAccount).getUser(storyDialogId); forwardAvatar.setUser(currentForwardUser = MessagesController.getInstance(currentAccount).getUser(storyDialogId));
} else { } else {
currentForwardChannel = MessagesController.getInstance(currentAccount).getChat(-storyDialogId); forwardAvatar.setChat(currentForwardChannel = MessagesController.getInstance(currentAccount).getChat(-storyDialogId));
} }
boolean includeAvatar = true;
String name = getNameFromDialogId(storyDialogId); String name = getNameFromDialogId(storyDialogId);
if (storyDialogId < 0 && currentForwardChannel == null) { if (storyDialogId < 0 && currentForwardChannel == null) {
name = LocaleController.getString("ChannelPrivate", R.string.ChannelPrivate); name = LocaleController.getString("ChannelPrivate", R.string.ChannelPrivate);
includeAvatar = false;
}
lastLine = new SpannableStringBuilder((includeAvatar ? "A " : "") + name);
((SpannableStringBuilder) lastLine).setSpan(new TypefaceSpan(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)), 0, lastLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
if (includeAvatar) {
((SpannableStringBuilder) lastLine).setSpan(forwardAvatar, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} }
lastLine = AndroidUtilities.replaceTags(LocaleController.formatString("ForwardedStoryFrom", R.string.ForwardedStoryFrom, name));
forwardedNameWidth = getMaxNameWidth(); forwardedNameWidth = getMaxNameWidth();
} else { } else {
boolean includeAvatar = true;
if (currentForwardChannel != null) { if (currentForwardChannel != null) {
if (currentForwardUser != null) { if (currentForwardUser != null) {
currentForwardNameString = String.format("%s (%s)", currentForwardChannel.title, UserObject.getUserName(currentForwardUser)); currentForwardNameString = String.format("%s (%s)", currentForwardChannel.title, UserObject.getUserName(currentForwardUser));
forwardAvatar.setUser(currentForwardUser);
} else if (!TextUtils.isEmpty(messageObject.messageOwner.fwd_from.post_author)) { } else if (!TextUtils.isEmpty(messageObject.messageOwner.fwd_from.post_author)) {
currentForwardNameString = String.format("%s (%s)", currentForwardChannel.title, messageObject.messageOwner.fwd_from.post_author); currentForwardNameString = String.format("%s (%s)", currentForwardChannel.title, messageObject.messageOwner.fwd_from.post_author);
forwardAvatar.setChat(currentForwardChannel);
} else { } else {
currentForwardNameString = currentForwardChannel.title; currentForwardNameString = currentForwardChannel.title;
forwardAvatar.setChat(currentForwardChannel);
} }
} else if (currentForwardUser != null) { } else if (currentForwardUser != null) {
currentForwardNameString = UserObject.getUserName(currentForwardUser); currentForwardNameString = UserObject.getUserName(currentForwardUser);
forwardAvatar.setUser(currentForwardUser);
} else { } else {
currentForwardNameString = currentForwardName; currentForwardNameString = currentForwardName;
includeAvatar = false;
} }
forwardedNameWidth = getMaxNameWidth(); forwardedNameWidth = getMaxNameWidth();
@ -14918,17 +14987,8 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (hasPsaHint) { if (hasPsaHint) {
forwardedNameWidth -= AndroidUtilities.dp(36); forwardedNameWidth -= AndroidUtilities.dp(36);
} }
String from = LocaleController.getString("From", R.string.From); CharSequence name = TextUtils.ellipsize((includeAvatar ? "A " : "") + currentForwardNameString.replace('\n', ' '), Theme.chat_replyNamePaint, forwardedNameWidth - viaWidth - dp(includeAvatar ? 17.33f : 0), TextUtils.TruncateAt.END);
String fromFormattedString = LocaleController.getString("FromFormatted", R.string.FromFormatted); String fromString = name.toString();
int idx = fromFormattedString.indexOf("%1$s");
int fromWidth = (int) Math.ceil(Theme.chat_forwardNamePaint.measureText(from + " "));
CharSequence name = TextUtils.ellipsize(currentForwardNameString.replace('\n', ' '), Theme.chat_replyNamePaint, forwardedNameWidth - fromWidth - viaWidth, TextUtils.TruncateAt.END);
String fromString;
try {
fromString = String.format(fromFormattedString, name);
} catch (Exception e) {
fromString = name.toString();
}
SpannableStringBuilder stringBuilder; SpannableStringBuilder stringBuilder;
if (viaString != null) { if (viaString != null) {
@ -14936,11 +14996,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
viaNameWidth = (int) Math.ceil(Theme.chat_forwardNamePaint.measureText(fromString)); viaNameWidth = (int) Math.ceil(Theme.chat_forwardNamePaint.measureText(fromString));
stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)), stringBuilder.length() - viaUsername.length() - 1, stringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)), stringBuilder.length() - viaUsername.length() - 1, stringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else { } else {
stringBuilder = new SpannableStringBuilder(String.format(fromFormattedString, name)); stringBuilder = new SpannableStringBuilder(fromString);
} }
forwardNameCenterX = fromWidth + (int) Math.ceil(Theme.chat_forwardNamePaint.measureText(name, 0, name.length())) / 2; if (includeAvatar && stringBuilder.length() > 1) {
if (idx >= 0 && (currentForwardName == null || messageObject.messageOwner.fwd_from.from_id != null)) { stringBuilder.setSpan(forwardAvatar, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)), idx, idx + name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); }
forwardNameCenterX = (int) Math.ceil(Theme.chat_forwardNamePaint.measureText(name, 0, name.length())) / 2;
if (currentForwardName == null || messageObject.messageOwner.fwd_from.from_id != null) {
stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)), 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} }
lastLine = stringBuilder; lastLine = stringBuilder;
} }
@ -14953,6 +15016,10 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
forwardedNameLayout[1] = new StaticLayout(lastLine, Theme.chat_forwardNamePaint, forwardedNameWidth + AndroidUtilities.dp(2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); forwardedNameLayout[1] = new StaticLayout(lastLine, Theme.chat_forwardNamePaint, forwardedNameWidth + AndroidUtilities.dp(2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
lastLine = TextUtils.ellipsize(AndroidUtilities.replaceTags(forwardedString), Theme.chat_forwardNamePaint, forwardedNameWidth, TextUtils.TruncateAt.END); lastLine = TextUtils.ellipsize(AndroidUtilities.replaceTags(forwardedString), Theme.chat_forwardNamePaint, forwardedNameWidth, TextUtils.TruncateAt.END);
forwardedNameLayout[0] = new StaticLayout(lastLine, Theme.chat_forwardNamePaint, forwardedNameWidth + AndroidUtilities.dp(2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); forwardedNameLayout[0] = new StaticLayout(lastLine, Theme.chat_forwardNamePaint, forwardedNameWidth + AndroidUtilities.dp(2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (forwardBg == null) {
forwardBg = new ForwardBackground(this);
}
forwardBg.set(forwardedNameLayout, !currentMessageObject.isOutOwner() && !(drawNameLayout && nameLayout != null) && pinnedTop);
forwardedNameWidth = Math.max((int) Math.ceil(forwardedNameLayout[0].getLineWidth(0)), (int) Math.ceil(forwardedNameLayout[1].getLineWidth(0))); forwardedNameWidth = Math.max((int) Math.ceil(forwardedNameLayout[0].getLineWidth(0)), (int) Math.ceil(forwardedNameLayout[1].getLineWidth(0)));
if (hasPsaHint) { if (hasPsaHint) {
forwardedNameWidth += AndroidUtilities.dp(36); forwardedNameWidth += AndroidUtilities.dp(36);
@ -15249,30 +15316,39 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
if (currentForwardUser != null || currentForwardChannel != null || currentForwardName != null) { if (currentForwardUser != null || currentForwardChannel != null || currentForwardName != null) {
if (forwardAvatar == null) {
forwardAvatar = new AvatarSpan(this, currentAccount);
forwardAvatar.translate(0, dp(-.33f));
}
forwardAvatar.setSize((1.23f * ((int) Theme.chat_forwardNamePaint.getTextSize())) / AndroidUtilities.density);
boolean includeAvatar = true;
if (currentForwardChannel != null) { if (currentForwardChannel != null) {
if (currentForwardUser != null) { if (currentForwardUser != null) {
currentForwardNameString = String.format("%s (%s)", currentForwardChannel.title, UserObject.getUserName(currentForwardUser)); currentForwardNameString = String.format("%s (%s)", currentForwardChannel.title, UserObject.getUserName(currentForwardUser));
forwardAvatar.setUser(currentForwardUser);
} else { } else {
currentForwardNameString = currentForwardChannel.title; currentForwardNameString = currentForwardChannel.title;
forwardAvatar.setChat(currentForwardChannel);
} }
} else if (currentForwardUser != null) { } else if (currentForwardUser != null) {
currentForwardNameString = UserObject.getUserName(currentForwardUser); currentForwardNameString = UserObject.getUserName(currentForwardUser);
forwardAvatar.setUser(currentForwardUser);
} else { } else {
currentForwardNameString = currentForwardName; currentForwardNameString = currentForwardName;
includeAvatar = false;
} }
name = getForwardedMessageText(messageObject); name = getForwardedMessageText(messageObject);
String from = LocaleController.getString("From", R.string.From);
String fromFormattedString = LocaleController.getString("FromFormatted", R.string.FromFormatted);
int idx = fromFormattedString.indexOf("%1$s");
int fromWidth = (int) Math.ceil(Theme.chat_replyNamePaint.measureText(from + " "));
CharSequence text = currentForwardNameString == null ? "" : currentForwardNameString.replace('\n', ' '); CharSequence text = currentForwardNameString == null ? "" : currentForwardNameString.replace('\n', ' ');
CharSequence ellipsizedText = TextUtils.ellipsize(text, Theme.chat_replyNamePaint, maxWidth - fromWidth, TextUtils.TruncateAt.END); CharSequence ellipsizedText = TextUtils.ellipsize((includeAvatar ? "A " : "") + text, Theme.chat_replyNamePaint, maxWidth - dp(includeAvatar ? 17.33f : 0), TextUtils.TruncateAt.END);
SpannableStringBuilder stringBuilder = new SpannableStringBuilder(String.format(fromFormattedString, ellipsizedText)); SpannableStringBuilder stringBuilder = new SpannableStringBuilder(ellipsizedText);
if (idx >= 0 && (currentForwardName == null || messageObject.messageOwner.fwd_from.from_id != null)) { if (includeAvatar && stringBuilder.length() > 1) {
stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), idx, idx + ellipsizedText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); stringBuilder.setSpan(forwardAvatar, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (currentForwardName == null || messageObject.messageOwner.fwd_from.from_id != null) {
stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)), 0, ellipsizedText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} }
stringFinalText = TextUtils.ellipsize(stringBuilder, textPaint, maxWidth, TextUtils.TruncateAt.END); stringFinalText = TextUtils.ellipsize(stringBuilder, textPaint, maxWidth, TextUtils.TruncateAt.END);
forwardNameCenterX = fromWidth + (int) Math.ceil(Theme.chat_replyNamePaint.measureText(ellipsizedText, 0, ellipsizedText.length())) / 2; forwardNameCenterX = (int) Math.ceil(Theme.chat_replyNamePaint.measureText(ellipsizedText, 0, ellipsizedText.length())) / 2;
} }
} }
CharSequence stringFinalName = name; CharSequence stringFinalName = name;
@ -15442,19 +15518,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} else if (currentChat != null) { } else if (currentChat != null) {
return currentChat.title; return currentChat.title;
} else if (currentMessageObject != null && currentMessageObject.isSponsored()) { } else if (currentMessageObject != null && currentMessageObject.isSponsored()) {
if (currentMessageObject.sponsoredBotApp != null) { return currentMessageObject.sponsoredTitle;
return currentMessageObject.sponsoredBotApp.title;
}
if (currentMessageObject.sponsoredWebPage != null) {
return currentMessageObject.sponsoredWebPage.site_name;
}
if (currentMessageObject.sponsoredChatInvite != null && currentMessageObject.sponsoredChatInvite.title != null) {
return currentMessageObject.sponsoredChatInvite.title;
}
if (currentMessageObject.sponsoredChatInvite != null && currentMessageObject.sponsoredChatInvite.chat != null && currentMessageObject.sponsoredChatInvite.chat.title != null) {
return currentMessageObject.sponsoredChatInvite.chat.title;
}
return "";
} }
return "DELETED"; return "DELETED";
} }
@ -15479,7 +15543,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
return forwardedString; return forwardedString;
} else { } else {
return LocaleController.getString("ForwardedMessage", R.string.ForwardedMessage); return LocaleController.getString(R.string.ForwardedFrom);
} }
} }
@ -15619,12 +15683,43 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
@Override @Override
public int getBoundsLeft() { public int getBoundsLeft() {
return Math.max(0, getBackgroundDrawableLeft() - (needDrawAvatar() ? dp(currentPosition != null ? 73 : (currentMessageObject != null && currentMessageObject.isRepostPreview ? 42 : 63)) : 0) - (currentMessageObject != null && currentMessageObject.isOutOwner() && (checkNeedDrawShareButton(currentMessageObject) || useTranscribeButton) ? dp(48) : 0)); boolean isOut = currentMessageObject != null && currentMessageObject.isOutOwner();
int avatarWidth = needDrawAvatar() ? dp(currentPosition != null ? 73 : (currentMessageObject != null && currentMessageObject.isRepostPreview ? 42 : 63)) : 0;
int shareButtonWidth = (isOut && (checkNeedDrawShareButton(currentMessageObject) || useTranscribeButton) ? dp(48) : 0);
int buttonMostLeft = Integer.MAX_VALUE;
if (botButtons != null) {
int addX;
if (currentMessageObject != null && currentMessageObject.isOutOwner()) {
addX = getMeasuredWidth() - widthForButtons - AndroidUtilities.dp(10);
} else {
addX = backgroundDrawableLeft + AndroidUtilities.dp(mediaBackground || drawPinnedBottom ? 1 : 7);
}
for (int i = 0; i < botButtons.size(); ++i) {
BotButton btn = botButtons.get(i);
buttonMostLeft = Math.max(buttonMostLeft, addX + btn.x);
}
}
return Math.max(0, Math.min(buttonMostLeft, getBackgroundDrawableLeft() - avatarWidth - shareButtonWidth));
} }
@Override @Override
public int getBoundsRight() { public int getBoundsRight() {
return getBackgroundDrawableRight() + (currentMessageObject != null && !currentMessageObject.isOutOwner() && (checkNeedDrawShareButton(currentMessageObject) || useTranscribeButton) ? dp(48) : 0); boolean isIn = currentMessageObject != null && !currentMessageObject.isOutOwner();
int shareButtonWidth = (isIn && (checkNeedDrawShareButton(currentMessageObject) || useTranscribeButton) ? dp(48) : 0);
int buttonMostRight = 0;
if (botButtons != null) {
int addX;
if (currentMessageObject != null && currentMessageObject.isOutOwner()) {
addX = getMeasuredWidth() - widthForButtons - AndroidUtilities.dp(10);
} else {
addX = backgroundDrawableLeft + AndroidUtilities.dp(mediaBackground || drawPinnedBottom ? 1 : 7);
}
for (int i = 0; i < botButtons.size(); ++i) {
BotButton btn = botButtons.get(i);
buttonMostRight = Math.max(buttonMostRight, addX + btn.x + btn.width);
}
}
return Math.max(getBackgroundDrawableRight() + shareButtonWidth, buttonMostRight);
} }
@SuppressLint("WrongCall") @SuppressLint("WrongCall")
@ -16469,16 +16564,13 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
currentMessageObject.overrideLinkColor >= 0 || currentMessageObject.overrideLinkColor >= 0 ||
currentMessageObject.isFromUser() && currentUser != null || currentMessageObject.isFromUser() && currentUser != null ||
currentMessageObject.isFromChannel() && currentChat != null || currentMessageObject.isFromChannel() && currentChat != null ||
currentMessageObject.isSponsored() && currentMessageObject.sponsoredChatInvite instanceof TLRPC.TL_chatInvite || currentMessageObject.sponsoredColor != null && currentMessageObject.sponsoredColor.color != -1
currentMessageObject.isSponsored() && currentMessageObject.sponsoredChatInvite != null && currentMessageObject.sponsoredChatInvite.chat != null
) { ) {
int colorId; int colorId;
if (currentMessageObject.overrideLinkColor >= 0) { if (currentMessageObject.overrideLinkColor >= 0) {
colorId = currentMessageObject.overrideLinkColor; colorId = currentMessageObject.overrideLinkColor;
} else if (currentMessageObject.isSponsored() && currentMessageObject.sponsoredChatInvite instanceof TLRPC.TL_chatInvite) { } else if (currentMessageObject.sponsoredColor != null) {
colorId = currentMessageObject.sponsoredChatInvite.color; colorId = currentMessageObject.sponsoredColor.color;
} else if (currentMessageObject.isSponsored() && currentMessageObject.sponsoredChatInvite != null && currentMessageObject.sponsoredChatInvite.chat != null) {
colorId = ChatObject.getColorId(currentMessageObject.sponsoredChatInvite.chat);
} else if (currentMessageObject.isFromUser() && currentUser != null) { } else if (currentMessageObject.isFromUser() && currentUser != null) {
colorId = UserObject.getColorId(currentUser); colorId = UserObject.getColorId(currentUser);
} else { } else {
@ -17063,17 +17155,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} else if ( } else if (
currentMessageObject.overrideLinkColor >= 0 || currentMessageObject.overrideLinkColor >= 0 ||
currentMessageObject.isFromUser() && currentUser != null || currentMessageObject.isFromUser() && currentUser != null ||
currentMessageObject.isFromChannel() && currentChat != null || currentMessageObject.isFromChannel() && currentChat != null
currentMessageObject.isSponsored() && currentMessageObject.sponsoredChatInvite instanceof TLRPC.TL_chatInvite ||
currentMessageObject.isSponsored() && currentMessageObject.sponsoredChatInvite != null && currentMessageObject.sponsoredChatInvite.chat != null
) { ) {
int colorId; int colorId;
if (currentMessageObject.overrideLinkColor >= 0) { if (currentMessageObject.overrideLinkColor >= 0) {
colorId = currentMessageObject.overrideLinkColor; colorId = currentMessageObject.overrideLinkColor;
} else if (currentMessageObject.isSponsored() && currentMessageObject.sponsoredChatInvite instanceof TLRPC.TL_chatInvite) {
colorId = currentMessageObject.sponsoredChatInvite.color;
} else if (currentMessageObject.isSponsored() && currentMessageObject.sponsoredChatInvite != null && currentMessageObject.sponsoredChatInvite.chat != null) {
colorId = ChatObject.getColorId(currentMessageObject.sponsoredChatInvite.chat);
} else if (currentMessageObject.isFromUser() && currentUser != null) { } else if (currentMessageObject.isFromUser() && currentUser != null) {
colorId = UserObject.getColorId(currentUser); colorId = UserObject.getColorId(currentUser);
} else { } else {
@ -17298,8 +17384,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} else { } else {
rect.set((int) forwardNameXLocal - AndroidUtilities.dp(7), forwardNameY - AndroidUtilities.dp(6), (int) forwardNameXLocal - AndroidUtilities.dp(7) + backWidth, forwardNameY + forwardHeight + AndroidUtilities.dp(6)); rect.set((int) forwardNameXLocal - AndroidUtilities.dp(7), forwardNameY - AndroidUtilities.dp(6), (int) forwardNameXLocal - AndroidUtilities.dp(7) + backWidth, forwardNameY + forwardHeight + AndroidUtilities.dp(6));
} }
applyServiceShaderMatrix();
int oldAlpha1 = -1, oldAlpha2 = -1; int oldAlpha1 = -1, oldAlpha2 = -1;
if (hasReply || forwardBg == null) {
applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop);
if (animatingAlpha != 1f || replyForwardAlpha != 1f) { if (animatingAlpha != 1f || replyForwardAlpha != 1f) {
oldAlpha1 = getThemedPaint(Theme.key_paint_chatActionBackground).getAlpha(); oldAlpha1 = getThemedPaint(Theme.key_paint_chatActionBackground).getAlpha();
getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha((int) (oldAlpha1 * animatingAlpha * replyForwardAlpha)); getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha((int) (oldAlpha1 * animatingAlpha * replyForwardAlpha));
@ -17312,6 +17399,26 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), Theme.chat_actionBackgroundGradientDarkenPaint); canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), Theme.chat_actionBackgroundGradientDarkenPaint);
} }
} else {
applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX() + forwardNameXLocal, viewTop + forwardNameY);
canvas.save();
canvas.translate(forwardNameXLocal, forwardNameY);
final float s = forwardBg.bounce.getScale(.02f);
canvas.scale(s, s, forwardBg.cx, forwardBg.cy);
if (animatingAlpha != 1f || replyForwardAlpha != 1f) {
oldAlpha1 = getThemedPaint(Theme.key_paint_chatActionBackground).getAlpha();
getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha((int) (oldAlpha1 * animatingAlpha * replyForwardAlpha));
}
canvas.drawPath(forwardBg.path, getThemedPaint(Theme.key_paint_chatActionBackground));
if (hasGradientService()) {
if (animatingAlpha != 1f || replyForwardAlpha != 1f) {
oldAlpha2 = Theme.chat_actionBackgroundGradientDarkenPaint.getAlpha();
Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha((int) (oldAlpha2 * animatingAlpha * replyForwardAlpha));
}
canvas.drawPath(forwardBg.path, Theme.chat_actionBackgroundGradientDarkenPaint);
}
canvas.restore();
}
if (oldAlpha1 >= 0) { if (oldAlpha1 >= 0) {
getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha(oldAlpha1); getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha(oldAlpha1);
} }
@ -17319,7 +17426,13 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha(oldAlpha2); Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha(oldAlpha2);
} }
} else { } else {
forwardNameY = AndroidUtilities.dp(10) + (drawNameLayout ? AndroidUtilities.dp(5) + (int) Theme.chat_namePaint.getTextSize() : 0) + (drawTopic && topicButton != null ? topicButton.height() + AndroidUtilities.dp(7 + (currentMessageObject.type != MessageObject.TYPE_TEXT ? 3 : 0)) : 0); forwardNameY = AndroidUtilities.dp(7) + (drawNameLayout ? AndroidUtilities.dp(6) + (int) Theme.chat_namePaint.getTextSize() : 0) + (drawTopic && topicButton != null ? topicButton.height() + AndroidUtilities.dp(7 + (currentMessageObject.type != MessageObject.TYPE_TEXT ? 3 : 0)) : 0);
if (!drawNameLayout && (currentMessageObject.type == MessageObject.TYPE_GIF || currentMessageObject.type == MessageObject.TYPE_PHOTO || currentMessageObject.type == MessageObject.TYPE_VIDEO || currentMessageObject.type == MessageObject.TYPE_STORY)) {
forwardNameY += dp(2);
}
if (!drawNameLayout && currentMessageObject.type == MessageObject.TYPE_TEXT && !drawPinnedTop) {
forwardNameY += dp(2);
}
forwardHeight = AndroidUtilities.dp(4) + (int) Theme.chat_forwardNamePaint.getTextSize() * 2; forwardHeight = AndroidUtilities.dp(4) + (int) Theme.chat_forwardNamePaint.getTextSize() * 2;
Theme.chat_forwardNamePaint.setColor(getThemedColor(hasPsaHint ? Theme.key_chat_inPsaNameText : Theme.key_chat_inForwardedNameText)); Theme.chat_forwardNamePaint.setColor(getThemedColor(hasPsaHint ? Theme.key_chat_inPsaNameText : Theme.key_chat_inForwardedNameText));
if (currentMessageObject.isOutOwner()) { if (currentMessageObject.isOutOwner()) {
@ -17355,14 +17468,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
if (currentMessageObject.isOutOwner()) { if (currentMessageObject.isOutOwner()) {
if (currentMessageObject.needDrawForwarded()) { if (currentMessageObject.needDrawForwarded()) {
forwardNameXLocal = forwardNameX = backgroundDrawableLeft + AndroidUtilities.dp(11) + getExtraTextX(); forwardNameXLocal = forwardNameX = backgroundDrawableLeft + AndroidUtilities.dp(10) + getExtraTextX();
forwardNameXLocal += transitionParams.deltaLeft; forwardNameXLocal += transitionParams.deltaLeft;
} else { } else {
forwardNameXLocal = transitionParams.animateForwardNameX; forwardNameXLocal = transitionParams.animateForwardNameX;
} }
} else { } else {
if (currentMessageObject.needDrawForwarded()) { if (currentMessageObject.needDrawForwarded()) {
forwardNameXLocal = forwardNameX = backgroundDrawableLeft + AndroidUtilities.dp(mediaBackground || drawPinnedBottom ? 11 : 17) + getExtraTextX(); forwardNameXLocal = forwardNameX = backgroundDrawableLeft + AndroidUtilities.dp(mediaBackground || drawPinnedBottom ? 10 : 16) + getExtraTextX();
} else { } else {
forwardNameXLocal = transitionParams.animateForwardNameX; forwardNameXLocal = transitionParams.animateForwardNameX;
} }
@ -17388,9 +17501,21 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
} }
canvas.save();
canvas.translate(forwardNameXLocal, forwardNameY);
if (forwardBg != null) {
final float s = forwardBg.bounce.getScale(.02f);
canvas.scale(s, s, forwardBg.cx, forwardBg.cy);
if (currentMessageObject.type == MessageObject.TYPE_ROUND_VIDEO || currentMessageObject.isAnyKindOfSticker()) {
forwardBg.setColor(Theme.multAlpha(Theme.getColor(Theme.key_listSelector, resourcesProvider), 1.35f));
} else {
forwardBg.setColor(Theme.multAlpha(Theme.chat_forwardNamePaint.getColor(), .15f));
}
forwardBg.draw(canvas);
}
for (int a = 0; a < 2; a++) { for (int a = 0; a < 2; a++) {
canvas.save(); canvas.save();
canvas.translate(forwardNameXLocal - forwardNameOffsetX[a], forwardNameY + (forwardHeight / 2f + 2) * a); canvas.translate(-forwardNameOffsetX[a], (forwardHeight / 2f + dp(1.33f)) * a);
if (animatingAlpha != 1f || replyForwardAlpha != 1f) { if (animatingAlpha != 1f || replyForwardAlpha != 1f) {
int oldAlpha = forwardedNameLayoutLocal[a].getPaint().getAlpha(); int oldAlpha = forwardedNameLayoutLocal[a].getPaint().getAlpha();
forwardedNameLayoutLocal[a].getPaint().setAlpha((int) (oldAlpha * animatingAlpha * replyForwardAlpha)); forwardedNameLayoutLocal[a].getPaint().setAlpha((int) (oldAlpha * animatingAlpha * replyForwardAlpha));
@ -17401,6 +17526,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
canvas.restore(); canvas.restore();
} }
canvas.restore();
if (clipContent) { if (clipContent) {
canvas.restore(); canvas.restore();
} }
@ -17569,9 +17695,10 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
forwardNameX = replyStartX - replyTextOffset + offset + (needReplyImage ? offset + AndroidUtilities.dp(25) : 0); forwardNameX = replyStartX - replyTextOffset + offset + (needReplyImage ? offset + AndroidUtilities.dp(25) : 0);
if ((currentPosition == null || currentPosition.minY == 0 && currentPosition.minX == 0) && !(enterTransitionInProgress && !currentMessageObject.isVoice())) { if ((currentPosition == null || currentPosition.minY == 0 && currentPosition.minX == 0) && !(enterTransitionInProgress && !currentMessageObject.isVoice())) {
int restoreToCount = -1; int restoreToCount = -1;
if (getAlpha() * replyForwardAlpha != 1f) { float _alpha = (transitionParams.ignoreAlpha ? 1f : getAlpha()) * replyForwardAlpha;
if (_alpha != 1f) {
AndroidUtilities.rectTmp.set(0, 0, getWidth(), getHeight()); AndroidUtilities.rectTmp.set(0, 0, getWidth(), getHeight());
restoreToCount = canvas.saveLayerAlpha(AndroidUtilities.rectTmp, (int) (0xFF * getAlpha() * replyForwardAlpha), Canvas.ALL_SAVE_FLAG); restoreToCount = canvas.saveLayerAlpha(AndroidUtilities.rectTmp, (int) (0xFF * _alpha), Canvas.ALL_SAVE_FLAG);
} }
float leftRad, rightRad, bottomRad = Math.min(4f, SharedConfig.bubbleRadius); float leftRad, rightRad, bottomRad = Math.min(4f, SharedConfig.bubbleRadius);
@ -19685,12 +19812,17 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
StaticLayout docTitleLayout = this.docTitleLayout; StaticLayout docTitleLayout = this.docTitleLayout;
StaticLayout infoLayout = this.infoLayout; StaticLayout infoLayout = this.infoLayout;
float alpha = 1f; float alpha = 1f;
boolean forever = false;
if (transitionParams.animateLocationIsExpired) { if (transitionParams.animateLocationIsExpired) {
progress = transitionParams.lastDrawLocationExpireProgress; progress = transitionParams.lastDrawLocationExpireProgress;
text = transitionParams.lastDrawLocationExpireText; text = transitionParams.lastDrawLocationExpireText;
docTitleLayout = transitionParams.lastDrawDocTitleLayout; docTitleLayout = transitionParams.lastDrawDocTitleLayout;
infoLayout = transitionParams.lastDrawInfoLayout; infoLayout = transitionParams.lastDrawInfoLayout;
alpha = 1f - transitionParams.animateChangeProgress; alpha = 1f - transitionParams.animateChangeProgress;
} else if (MessageObject.getMedia(currentMessageObject.messageOwner).period == 0x7fffffff) {
forever = true;
progress = 1.0f;
text = "";
} else { } else {
progress = 1.0f - Math.abs(ConnectionsManager.getInstance(currentAccount).getCurrentTime() - currentMessageObject.messageOwner.date) / (float) MessageObject.getMedia(currentMessageObject.messageOwner).period; progress = 1.0f - Math.abs(ConnectionsManager.getInstance(currentAccount).getCurrentTime() - currentMessageObject.messageOwner.date) / (float) MessageObject.getMedia(currentMessageObject.messageOwner).period;
text = LocaleController.formatLocationLeftTime(Math.abs(MessageObject.getMedia(currentMessageObject.messageOwner).period - (ConnectionsManager.getInstance(currentAccount).getCurrentTime() - currentMessageObject.messageOwner.date))); text = LocaleController.formatLocationLeftTime(Math.abs(MessageObject.getMedia(currentMessageObject.messageOwner).period - (ConnectionsManager.getInstance(currentAccount).getCurrentTime() - currentMessageObject.messageOwner.date)));
@ -19721,8 +19853,29 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
Theme.chat_radialProgress2Paint.setAlpha((int) (255 * alpha)); Theme.chat_radialProgress2Paint.setAlpha((int) (255 * alpha));
canvas.drawArc(rect, -90, -360 * progress, false, Theme.chat_radialProgress2Paint); canvas.drawArc(rect, -90, -360 * progress, false, Theme.chat_radialProgress2Paint);
if (forever) {
if (foreverDrawable == null) {
foreverDrawable = getContext().getResources().getDrawable(R.drawable.filled_location_forever).mutate();
}
if (Theme.chat_livePaint.getColor() != foreverDrawableColor) {
foreverDrawable.setColorFilter(new PorterDuffColorFilter(foreverDrawableColor = Theme.chat_livePaint.getColor(), PorterDuff.Mode.SRC_IN));
}
foreverDrawable.setBounds(
(int) rect.centerX() - foreverDrawable.getIntrinsicWidth() / 2,
(int) rect.centerY() - foreverDrawable.getIntrinsicHeight() / 2,
(int) rect.centerX() + foreverDrawable.getIntrinsicWidth() / 2,
(int) rect.centerY() + foreverDrawable.getIntrinsicHeight() / 2
);
foreverDrawable.draw(canvas);
} else {
float w = Theme.chat_livePaint.measureText(text); float w = Theme.chat_livePaint.measureText(text);
int len = text.length();
final float s2 = (len > 4 ? .75f : (len > 3 ? .85f : 1f));
canvas.save();
canvas.scale(s2, s2, rect.centerX(), rect.centerY());
canvas.drawText(text, rect.centerX() - w / 2, cy + AndroidUtilities.dp(4), Theme.chat_livePaint); canvas.drawText(text, rect.centerX() - w / 2, cy + AndroidUtilities.dp(4), Theme.chat_livePaint);
canvas.restore();
}
if (docTitleLayout != null && infoLayout != null) { if (docTitleLayout != null && infoLayout != null) {
canvas.save(); canvas.save();
@ -19895,6 +20048,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
canvas.save(); canvas.save();
canvas.translate(x + getExtraTextX(), AndroidUtilities.dp(15) + namesOffset); canvas.translate(x + getExtraTextX(), AndroidUtilities.dp(15) + namesOffset);
titleLayout.draw(canvas); titleLayout.draw(canvas);
AnimatedEmojiSpan.drawAnimatedEmojis(canvas, titleLayout, animatedEmojiPollQuestion, 0, null, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(1, titleLayout.getPaint().getColor()));
canvas.restore(); canvas.restore();
} }
int y = (titleLayout != null ? titleLayout.getHeight() : 0) + AndroidUtilities.dp(20) + namesOffset; int y = (titleLayout != null ? titleLayout.getHeight() : 0) + AndroidUtilities.dp(20) + namesOffset;
@ -20025,6 +20179,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
canvas.save(); canvas.save();
canvas.translate(x + AndroidUtilities.dp(35), button.y + namesOffset); canvas.translate(x + AndroidUtilities.dp(35), button.y + namesOffset);
button.title.draw(canvas); button.title.draw(canvas);
AnimatedEmojiSpan.drawAnimatedEmojis(canvas, button.title, button.animatedEmoji, 0, null, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(1, button.title.getPaint().getColor()));
int alpha = (int) (animatePollAnswerAlpha ? 255 * Math.min((pollUnvoteInProgress ? 1.0f - pollAnimationProgress : pollAnimationProgress) / 0.3f, 1.0f) : 255); int alpha = (int) (animatePollAnswerAlpha ? 255 * Math.min((pollUnvoteInProgress ? 1.0f - pollAnimationProgress : pollAnimationProgress) / 0.3f, 1.0f) : 255);
if (pollVoted || pollClosed || animatePollAnswerAlpha) { if (pollVoted || pollClosed || animatePollAnswerAlpha) {
if (lastPoll.quiz && pollVoted && button.chosen) { if (lastPoll.quiz && pollVoted && button.chosen) {
@ -20930,7 +21085,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
if (lastPoll != null) { if (lastPoll != null) {
sb.append(", "); sb.append(", ");
sb.append(lastPoll.question); sb.append(lastPoll.question.text);
sb.append(", "); sb.append(", ");
String title; String title;
if (pollClosed) { if (pollClosed) {
@ -21585,7 +21740,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} }
PollButton button = pollButtons.get(buttonIndex); PollButton button = pollButtons.get(buttonIndex);
if (delegate != null) { if (delegate != null) {
ArrayList<TLRPC.TL_pollAnswer> answers = new ArrayList<>(); ArrayList<TLRPC.PollAnswer> answers = new ArrayList<>();
answers.add(button.answer); answers.add(button.answer);
delegate.didPressVoteButtons(ChatMessageCell.this, answers, -1, 0, 0); delegate.didPressVoteButtons(ChatMessageCell.this, answers, -1, 0, 0);
} }

View file

@ -8,6 +8,9 @@
package org.telegram.ui.Cells; package org.telegram.ui.Cells;
import static org.telegram.messenger.AndroidUtilities.dp;
import android.annotation.SuppressLint;
import android.content.Context; import android.content.Context;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.PorterDuff; import android.graphics.PorterDuff;
@ -19,14 +22,28 @@ import android.view.Gravity;
import android.view.View; import android.view.View;
import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.Emoji; import org.telegram.messenger.Emoji;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R; 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.ActionBar.Theme;
import org.telegram.ui.Components.AnimatedTextView;
import org.telegram.ui.Components.AvatarDrawable;
import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.CheckBox2; import org.telegram.ui.Components.CheckBox2;
import org.telegram.ui.Components.CheckBoxSquare; import org.telegram.ui.Components.CheckBoxSquare;
import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.CubicBezierInterpolator;
@ -40,20 +57,31 @@ public class CheckBoxCell extends FrameLayout {
TYPE_CHECK_BOX_ENTER_PHONE = 2, TYPE_CHECK_BOX_ENTER_PHONE = 2,
TYPE_CHECK_BOX_UNKNOWN = 3, TYPE_CHECK_BOX_UNKNOWN = 3,
TYPE_CHECK_BOX_ROUND = 4, TYPE_CHECK_BOX_ROUND = 4,
TYPE_CHECK_BOX_URL = 5; TYPE_CHECK_BOX_URL = 5,
TYPE_CHECK_BOX_USER_GROUP = 6,
TYPE_CHECK_BOX_USER = 7,
TYPE_CHECK_BOX_ROUND_GROUP = 8;
public int itemId;
private final Theme.ResourcesProvider resourcesProvider; private final Theme.ResourcesProvider resourcesProvider;
private final LinkSpanDrawable.LinksTextView textView; private LinkSpanDrawable.LinksTextView linksTextView;
private AnimatedTextView animatedTextView;
private View textView;
private final TextView valueTextView; private final TextView valueTextView;
private final View checkBox; private final View checkBox;
private CheckBoxSquare checkBoxSquare; private CheckBoxSquare checkBoxSquare;
private CheckBox2 checkBoxRound; private CheckBox2 checkBoxRound;
private View collapsedArrow; private View collapsedArrow;
private CollapseButton collapseButton;
private BackupImageView avatarImageView;
private AvatarDrawable avatarDrawable;
private final int currentType; private final int currentType;
private final int checkBoxSize; private final int checkBoxSize;
private boolean needDivider; private boolean needDivider;
private boolean isMultiline; private boolean isMultiline;
private boolean textAnimated;
public CheckBoxCell(Context context, int type) { public CheckBoxCell(Context context, int type) {
this(context, type, 17, null); this(context, type, 17, null);
@ -64,11 +92,52 @@ public class CheckBoxCell extends FrameLayout {
} }
public CheckBoxCell(Context context, int type, int padding, Theme.ResourcesProvider resourcesProvider) { public CheckBoxCell(Context context, int type, int padding, Theme.ResourcesProvider resourcesProvider) {
this(context, type, padding, false, resourcesProvider);
}
public CheckBoxCell(Context context, int type, int padding, boolean textAnimated, Theme.ResourcesProvider resourcesProvider) {
super(context); super(context);
this.resourcesProvider = resourcesProvider; this.resourcesProvider = resourcesProvider;
this.currentType = type; this.currentType = type;
this.textAnimated = textAnimated;
textView = new LinkSpanDrawable.LinksTextView(context) { if (textAnimated) {
animatedTextView = new AnimatedTextView(context) {
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
updateCollapseArrowTranslation();
}
};
NotificationCenter.listenEmojiLoading(animatedTextView);
animatedTextView.setEllipsizeByGradient(true);
animatedTextView.setRightPadding(dp(8));
animatedTextView.getDrawable().setHacks(true, true, false);
animatedTextView.setTag(getThemedColor(type == TYPE_CHECK_BOX_DEFAULT || type == TYPE_CHECK_BOX_URL ? Theme.key_dialogTextBlack : Theme.key_windowBackgroundWhiteBlackText));
animatedTextView.setTextSize(dp(16));
if (type == TYPE_CHECK_BOX_USER) {
animatedTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM));
}
if (type == TYPE_CHECK_BOX_UNKNOWN) {
animatedTextView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
addView(animatedTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 29, 0, 0, 0));
animatedTextView.setPadding(0, 0, 0, dp(3));
} else {
animatedTextView.setRightPadding(dp(padding));
animatedTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
if (type == TYPE_CHECK_BOX_ENTER_PHONE) {
addView(animatedTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, (LocaleController.isRTL ? 8 : 29), 0, (LocaleController.isRTL ? 29 : 8), 0));
} else {
int offset = isCheckboxRound() ? 56 : 46;
if (type == TYPE_CHECK_BOX_USER) {
offset += 39;
}
addView(animatedTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, (LocaleController.isRTL ? padding : offset + (padding - 17)), 0, (LocaleController.isRTL ? offset + (padding - 17) : padding), 0));
}
}
textView = animatedTextView;
} else {
linksTextView = new LinkSpanDrawable.LinksTextView(context) {
@Override @Override
protected void onDraw(Canvas canvas) { protected void onDraw(Canvas canvas) {
super.onDraw(canvas); super.onDraw(canvas);
@ -81,25 +150,33 @@ public class CheckBoxCell extends FrameLayout {
super.setText(text, type); super.setText(text, type);
} }
}; };
NotificationCenter.listenEmojiLoading(textView); NotificationCenter.listenEmojiLoading(linksTextView);
textView.setTag(getThemedColor(type == TYPE_CHECK_BOX_DEFAULT || type == TYPE_CHECK_BOX_URL ? Theme.key_dialogTextBlack : Theme.key_windowBackgroundWhiteBlackText)); linksTextView.setTag(getThemedColor(type == TYPE_CHECK_BOX_DEFAULT || type == TYPE_CHECK_BOX_URL ? Theme.key_dialogTextBlack : Theme.key_windowBackgroundWhiteBlackText));
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); linksTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
textView.setLines(1); linksTextView.setLines(1);
textView.setMaxLines(1); linksTextView.setMaxLines(1);
textView.setSingleLine(true); linksTextView.setSingleLine(true);
textView.setEllipsize(TextUtils.TruncateAt.END); linksTextView.setEllipsize(TextUtils.TruncateAt.END);
if (type == TYPE_CHECK_BOX_UNKNOWN) { if (type == TYPE_CHECK_BOX_USER) {
textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); linksTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM));
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 29, 0, 0, 0));
textView.setPadding(0, 0, 0, AndroidUtilities.dp(3));
} else {
textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
if (type == TYPE_CHECK_BOX_ENTER_PHONE) {
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, (LocaleController.isRTL ? 8 : 29), 0, (LocaleController.isRTL ? 29 : 8), 0));
} else {
int offset = type == TYPE_CHECK_BOX_ROUND ? 56 : 46;
addView(textView, LayoutHelper.createFrame(type == TYPE_CHECK_BOX_ROUND ? LayoutHelper.WRAP_CONTENT : LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, (LocaleController.isRTL ? padding : offset + (padding - 17)), 0, (LocaleController.isRTL ? offset + (padding - 17) : padding), 0));
} }
if (type == TYPE_CHECK_BOX_UNKNOWN) {
linksTextView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
addView(linksTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 29, 0, 0, 0));
linksTextView.setPadding(0, 0, 0, dp(3));
} else {
linksTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
if (type == TYPE_CHECK_BOX_ENTER_PHONE) {
addView(linksTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, (LocaleController.isRTL ? 8 : 29), 0, (LocaleController.isRTL ? 29 : 8), 0));
} else {
int offset = isCheckboxRound() ? 56 : 46;
if (type == TYPE_CHECK_BOX_USER) {
offset += 39;
}
addView(linksTextView, LayoutHelper.createFrame(isCheckboxRound() ? LayoutHelper.WRAP_CONTENT : LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, (LocaleController.isRTL ? padding : offset + (padding - 17)), 0, (LocaleController.isRTL ? offset + (padding - 17) : padding), 0));
}
}
textView = linksTextView;
} }
valueTextView = new TextView(context); valueTextView = new TextView(context);
@ -112,7 +189,7 @@ public class CheckBoxCell extends FrameLayout {
valueTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL); valueTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL);
addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP, padding, 0, padding, 0)); addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP, padding, 0, padding, 0));
if (type == TYPE_CHECK_BOX_ROUND) { if (isCheckboxRound()) {
checkBox = checkBoxRound = new CheckBox2(context, 21, resourcesProvider); checkBox = checkBoxRound = new CheckBox2(context, 21, resourcesProvider);
checkBoxRound.setDrawUnchecked(true); checkBoxRound.setDrawUnchecked(true);
checkBoxRound.setChecked(true, false); checkBoxRound.setChecked(true, false);
@ -132,18 +209,43 @@ public class CheckBoxCell extends FrameLayout {
addView(checkBox, LayoutHelper.createFrame(checkBoxSize, checkBoxSize, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 0 : padding), 16, (LocaleController.isRTL ? padding : 0), 0)); addView(checkBox, LayoutHelper.createFrame(checkBoxSize, checkBoxSize, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 0 : padding), 16, (LocaleController.isRTL ? padding : 0), 0));
} }
} }
if (type == TYPE_CHECK_BOX_USER_GROUP) {
collapseButton = new CollapseButton(context, R.drawable.msg_folders_groups);
addView(collapseButton, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.END | Gravity.CENTER_VERTICAL, padding, 0, padding - 11, 0));
} else if (type == TYPE_CHECK_BOX_ROUND_GROUP) {
collapseButton = new CollapseButton(context, 0);
addView(collapseButton, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.END | Gravity.CENTER_VERTICAL, padding, 0, padding - 11, 0));
} else if (type == TYPE_CHECK_BOX_USER) {
avatarDrawable = new AvatarDrawable();
avatarImageView = new BackupImageView(context);
avatarImageView.setRoundRadius(dp(17));
addView(avatarImageView, LayoutHelper.createFrameRelatively(34, 34, Gravity.START | Gravity.CENTER_VERTICAL, 56, 0, 0, 0));
}
updateTextColor(); updateTextColor();
} }
public boolean isCheckboxRound() {
return currentType == TYPE_CHECK_BOX_ROUND || currentType == TYPE_CHECK_BOX_ROUND_GROUP || currentType == TYPE_CHECK_BOX_USER_GROUP || currentType == TYPE_CHECK_BOX_USER;
}
public void allowMultiline() { public void allowMultiline() {
textView.setLines(3); if (textAnimated) {
textView.setMaxLines(3); return;
textView.setSingleLine(false); }
linksTextView.setLines(3);
linksTextView.setMaxLines(3);
linksTextView.setSingleLine(false);
} }
public void updateTextColor() { public void updateTextColor() {
textView.setTextColor(getThemedColor(currentType == TYPE_CHECK_BOX_DEFAULT || currentType == TYPE_CHECK_BOX_URL ? Theme.key_dialogTextBlack : Theme.key_windowBackgroundWhiteBlackText)); if (textAnimated) {
textView.setLinkTextColor(getThemedColor(currentType == TYPE_CHECK_BOX_DEFAULT || currentType == TYPE_CHECK_BOX_URL ? Theme.key_dialogTextLink : Theme.key_windowBackgroundWhiteLinkText)); animatedTextView.setTextColor(getThemedColor(currentType == TYPE_CHECK_BOX_DEFAULT || currentType == TYPE_CHECK_BOX_URL ? Theme.key_dialogTextBlack : Theme.key_windowBackgroundWhiteBlackText));
} else {
linksTextView.setTextColor(getThemedColor(currentType == TYPE_CHECK_BOX_DEFAULT || currentType == TYPE_CHECK_BOX_URL ? Theme.key_dialogTextBlack : Theme.key_windowBackgroundWhiteBlackText));
linksTextView.setLinkTextColor(getThemedColor(currentType == TYPE_CHECK_BOX_DEFAULT || currentType == TYPE_CHECK_BOX_URL ? Theme.key_dialogTextLink : Theme.key_windowBackgroundWhiteLinkText));
}
valueTextView.setTextColor(getThemedColor(currentType == TYPE_CHECK_BOX_DEFAULT || currentType == TYPE_CHECK_BOX_URL ? Theme.key_dialogTextBlue : Theme.key_windowBackgroundWhiteValueText)); valueTextView.setTextColor(getThemedColor(currentType == TYPE_CHECK_BOX_DEFAULT || currentType == TYPE_CHECK_BOX_URL ? Theme.key_dialogTextBlue : Theme.key_windowBackgroundWhiteValueText));
} }
@ -210,9 +312,9 @@ public class CheckBoxCell extends FrameLayout {
float translateX; float translateX;
if (LocaleController.isRTL) { if (LocaleController.isRTL) {
translateX = textView.getRight() - textWidth - AndroidUtilities.dp(20); translateX = textView.getRight() - textWidth - dp(20);
} else { } else {
translateX = textView.getLeft() + textWidth + AndroidUtilities.dp(4); translateX = textView.getLeft() + textWidth + dp(4);
} }
collapsedArrow.setTranslationX(translateX); collapsedArrow.setTranslationX(translateX);
} }
@ -221,47 +323,66 @@ public class CheckBoxCell extends FrameLayout {
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec);
if (currentType == TYPE_CHECK_BOX_UNKNOWN) { if (currentType == TYPE_CHECK_BOX_UNKNOWN) {
valueTextView.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(10), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(50), MeasureSpec.EXACTLY)); valueTextView.measure(MeasureSpec.makeMeasureSpec(dp(10), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(dp(50), MeasureSpec.EXACTLY));
textView.measure(MeasureSpec.makeMeasureSpec(width - AndroidUtilities.dp(34), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(50), MeasureSpec.AT_MOST)); textView.measure(MeasureSpec.makeMeasureSpec(width - dp(34), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(dp(50), MeasureSpec.AT_MOST));
checkBox.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(checkBoxSize), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(checkBoxSize), MeasureSpec.EXACTLY)); checkBox.measure(MeasureSpec.makeMeasureSpec(dp(checkBoxSize), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(dp(checkBoxSize), MeasureSpec.EXACTLY));
setMeasuredDimension(textView.getMeasuredWidth() + AndroidUtilities.dp(29), AndroidUtilities.dp(50)); setMeasuredDimension(textView.getMeasuredWidth() + dp(29), dp(50));
} else if (isMultiline) { } else if (isMultiline) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
} else { } else {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), AndroidUtilities.dp(50) + (needDivider ? 1 : 0)); setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), dp(50) + (needDivider ? 1 : 0));
int availableWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - AndroidUtilities.dp(currentType == TYPE_CHECK_BOX_ROUND ? 60 : 34); int availableWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - dp(isCheckboxRound() ? 60 : 34);
if (textAnimated) {
availableWidth += (int) animatedTextView.getRightPadding();
}
if (currentType == TYPE_CHECK_BOX_USER) {
availableWidth -= dp(34);
}
if (valueTextView.getLayoutParams() instanceof MarginLayoutParams) { if (valueTextView.getLayoutParams() instanceof MarginLayoutParams) {
availableWidth -= ((MarginLayoutParams) valueTextView.getLayoutParams()).rightMargin; availableWidth -= ((MarginLayoutParams) valueTextView.getLayoutParams()).rightMargin;
} }
int takenSpace = 0;
valueTextView.measure(MeasureSpec.makeMeasureSpec(availableWidth / 2, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); valueTextView.measure(MeasureSpec.makeMeasureSpec(availableWidth / 2, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
if (textView.getLayoutParams().width == LayoutHelper.MATCH_PARENT) { takenSpace += valueTextView.getMeasuredWidth();
textView.measure(MeasureSpec.makeMeasureSpec(availableWidth - (int) Math.abs(textView.getTranslationX()) - valueTextView.getMeasuredWidth() - AndroidUtilities.dp(8), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST)); if (collapseButton != null) {
} else { collapseButton.measure(MeasureSpec.makeMeasureSpec(availableWidth / 2, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
textView.measure(MeasureSpec.makeMeasureSpec(availableWidth - (int) Math.abs(textView.getTranslationX()) - valueTextView.getMeasuredWidth() - AndroidUtilities.dp(8), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST)); takenSpace += collapseButton.getMeasuredWidth() - dp(11);
} }
checkBox.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(checkBoxSize), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(checkBoxSize), MeasureSpec.EXACTLY)); if (textView.getLayoutParams().width == LayoutHelper.MATCH_PARENT) {
textView.measure(MeasureSpec.makeMeasureSpec(availableWidth - (int) Math.abs(textView.getTranslationX()) - takenSpace - dp(8), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST));
} else {
textView.measure(MeasureSpec.makeMeasureSpec(availableWidth - (int) Math.abs(textView.getTranslationX()) - takenSpace - dp(8), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST));
}
if (avatarImageView != null) {
avatarImageView.measure(MeasureSpec.makeMeasureSpec(dp(34), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(dp(34), MeasureSpec.EXACTLY));
}
checkBox.measure(MeasureSpec.makeMeasureSpec(dp(checkBoxSize), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(dp(checkBoxSize), MeasureSpec.EXACTLY));
} }
if (click1Container != null) { if (click1Container != null) {
MarginLayoutParams margin = (MarginLayoutParams) click1Container.getLayoutParams(); MarginLayoutParams margin = (MarginLayoutParams) click1Container.getLayoutParams();
click1Container.measure(MeasureSpec.makeMeasureSpec(width - margin.leftMargin - margin.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(50), MeasureSpec.EXACTLY)); click1Container.measure(MeasureSpec.makeMeasureSpec(width - margin.leftMargin - margin.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(dp(50), MeasureSpec.EXACTLY));
} }
if (click2Container != null) { if (click2Container != null) {
click2Container.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(56), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(50), MeasureSpec.EXACTLY)); click2Container.measure(MeasureSpec.makeMeasureSpec(dp(56), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(dp(50), MeasureSpec.EXACTLY));
} }
if (collapsedArrow != null) { if (collapsedArrow != null) {
collapsedArrow.measure( collapsedArrow.measure(
MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(16), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(dp(16), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(16), MeasureSpec.EXACTLY) MeasureSpec.makeMeasureSpec(dp(16), MeasureSpec.EXACTLY)
); );
} }
} }
public void setTextColor(int color) { public void setTextColor(int color) {
textView.setTextColor(color); if (textAnimated) {
animatedTextView.setTextColor(color);
} else {
linksTextView.setTextColor(color);
}
} }
public void setText(CharSequence text, String value, boolean checked, boolean divider) { public void setText(CharSequence text, String value, boolean checked, boolean divider) {
@ -269,7 +390,12 @@ public class CheckBoxCell extends FrameLayout {
} }
public void setText(CharSequence text, String value, boolean checked, boolean divider, boolean animated) { public void setText(CharSequence text, String value, boolean checked, boolean divider, boolean animated) {
textView.setText(text); if (textAnimated) {
text = Emoji.replaceEmoji(text, animatedTextView.getPaint().getFontMetricsInt(), false);
animatedTextView.setText(text, animated);
} else {
linksTextView.setText(text);
}
if (checkBoxRound != null) { if (checkBoxRound != null) {
checkBoxRound.setChecked(checked, animated); checkBoxRound.setChecked(checked, animated);
} else { } else {
@ -280,12 +406,35 @@ public class CheckBoxCell extends FrameLayout {
setWillNotDraw(!divider); setWillNotDraw(!divider);
} }
public void setUserOrChat(TLObject userOrChat) {
avatarDrawable.setInfo(userOrChat);
avatarImageView.setForUserOrChat(userOrChat, avatarDrawable);
CharSequence name;
if (userOrChat instanceof TLRPC.User) {
name = UserObject.getUserName((TLRPC.User) userOrChat);
} else {
name = ContactsController.formatName(userOrChat);
}
if (userOrChat instanceof TLRPC.User && ((TLRPC.User) userOrChat).id == MessagesController.getInstance(UserConfig.selectedAccount).telegramAntispamUserId) {
name = LocaleController.getString(R.string.ChannelAntiSpamUser);
}
if (textAnimated) {
name = Emoji.replaceEmoji(name, animatedTextView.getPaint().getFontMetricsInt(), false);
animatedTextView.setText(name);
} else {
linksTextView.setText(name);
}
}
public void setPad(int pad) { public void setPad(int pad) {
int offset = AndroidUtilities.dp(pad * 40 * (LocaleController.isRTL ? -1 : 1)); int offset = dp(pad * 40 * (LocaleController.isRTL ? -1 : 1));
if (checkBox != null) { if (checkBox != null) {
checkBox.setTranslationX(offset); checkBox.setTranslationX(offset);
} }
textView.setTranslationX(offset); textView.setTranslationX(offset);
if (avatarImageView != null) {
avatarImageView.setTranslationX(offset);
}
if (click1Container != null) { if (click1Container != null) {
click1Container.setTranslationX(offset); click1Container.setTranslationX(offset);
} }
@ -299,30 +448,33 @@ public class CheckBoxCell extends FrameLayout {
} }
public void setMultiline(boolean value) { public void setMultiline(boolean value) {
if (textAnimated) {
return;
}
isMultiline = value; isMultiline = value;
LayoutParams layoutParams = (LayoutParams) textView.getLayoutParams(); LayoutParams layoutParams = (LayoutParams) textView.getLayoutParams();
LayoutParams layoutParams1 = (LayoutParams) checkBox.getLayoutParams(); LayoutParams layoutParams1 = (LayoutParams) checkBox.getLayoutParams();
if (isMultiline) { if (isMultiline) {
textView.setLines(0); linksTextView.setLines(0);
textView.setMaxLines(0); linksTextView.setMaxLines(0);
textView.setSingleLine(false); linksTextView.setSingleLine(false);
textView.setEllipsize(null); linksTextView.setEllipsize(null);
if (currentType != TYPE_CHECK_BOX_URL) { if (currentType != TYPE_CHECK_BOX_URL) {
layoutParams.height = LayoutParams.WRAP_CONTENT; layoutParams.height = LayoutParams.WRAP_CONTENT;
layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP; layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP;
layoutParams.topMargin = AndroidUtilities.dp(14); layoutParams.topMargin = dp(14);
layoutParams.bottomMargin = AndroidUtilities.dp(10); layoutParams.bottomMargin = dp(10);
} }
} else { } else {
textView.setLines(1); linksTextView.setLines(1);
textView.setMaxLines(1); linksTextView.setMaxLines(1);
textView.setSingleLine(true); linksTextView.setSingleLine(true);
textView.setEllipsize(TextUtils.TruncateAt.END); linksTextView.setEllipsize(TextUtils.TruncateAt.END);
textView.setPadding(0, 0, 0, 0); textView.setPadding(0, 0, 0, 0);
layoutParams.height = LayoutParams.MATCH_PARENT; layoutParams.height = LayoutParams.MATCH_PARENT;
layoutParams.topMargin = 0; layoutParams.topMargin = 0;
layoutParams1.topMargin = AndroidUtilities.dp(15); layoutParams1.topMargin = dp(15);
} }
textView.setLayoutParams(layoutParams); textView.setLayoutParams(layoutParams);
checkBox.setLayoutParams(layoutParams1); checkBox.setLayoutParams(layoutParams1);
@ -353,7 +505,11 @@ public class CheckBoxCell extends FrameLayout {
} }
public TextView getTextView() { public TextView getTextView() {
return textView; return linksTextView;
}
public AnimatedTextView getAnimatedTextView() {
return animatedTextView;
} }
public TextView getValueTextView() { public TextView getValueTextView() {
@ -383,7 +539,10 @@ public class CheckBoxCell extends FrameLayout {
@Override @Override
protected void onDraw(Canvas canvas) { protected void onDraw(Canvas canvas) {
if (needDivider) { if (needDivider) {
int offset = AndroidUtilities.dp(currentType == TYPE_CHECK_BOX_ROUND ? 60 : 20) + (int) Math.abs(textView.getTranslationX()); int offset = dp(isCheckboxRound() ? 60 : 20) + (int) Math.abs(textView.getTranslationX());
if (currentType == TYPE_CHECK_BOX_USER) {
offset += dp(39);
}
canvas.drawLine(LocaleController.isRTL ? 0 : offset, getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? offset : 0), getMeasuredHeight() - 1, Theme.dividerPaint); canvas.drawLine(LocaleController.isRTL ? 0 : offset, getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? offset : 0), getMeasuredHeight() - 1, Theme.dividerPaint);
} }
} }
@ -407,4 +566,74 @@ public class CheckBoxCell extends FrameLayout {
public boolean hasIcon() { public boolean hasIcon() {
return checkBoxRound.hasIcon(); return checkBoxRound.hasIcon();
} }
public void setCollapseButton(boolean collapsed, CharSequence text, View.OnClickListener onClick) {
if (collapseButton != null) {
collapseButton.set(collapsed, text);
if (onClick != null) {
collapseButton.setOnClickListener(onClick);
}
}
}
public class CollapseButton extends LinearLayout {
@Nullable
private ImageView iconView;
private final AnimatedTextView textView;
private final View collapsedArrow;
@SuppressLint("UseCompatLoadingForDrawables")
public CollapseButton(@NonNull Context context, int iconResId) {
super(context);
final int color = getThemedColor(Theme.key_windowBackgroundWhiteBlackText);
if (iconResId != 0) {
iconView = new ImageView(context);
iconView.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
iconView.setImageResource(iconResId);
}
textView = new AnimatedTextView(context, false, true, false);
textView.setTextSize(dp(13));
textView.setTextColor(color);
textView.setIncludeFontPadding(false);
textView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM));
collapsedArrow = new View(context);
Drawable drawable = getContext().getResources().getDrawable(R.drawable.arrow_more).mutate();
drawable.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
collapsedArrow.setBackground(drawable);
if (LocaleController.isRTL) {
addView(collapsedArrow, LayoutHelper.createLinear(16, 16, Gravity.CENTER_VERTICAL, 11, 0, 3, 0));
addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 16, Gravity.CENTER_VERTICAL, 0, 0, iconView == null ? 11 : 3, 0));
if (iconView != null) {
addView(iconView, LayoutHelper.createLinear(16, 16, Gravity.CENTER_VERTICAL, 0, 0, 11, 0));
}
} else {
if (iconView != null) {
addView(iconView, LayoutHelper.createLinear(16, 16, Gravity.CENTER_VERTICAL, 11, 0, 3, 0));
}
addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 16, Gravity.CENTER_VERTICAL, iconView == null ? 11 : 0, 0, 3, 0));
addView(collapsedArrow, LayoutHelper.createLinear(16, 16, Gravity.CENTER_VERTICAL, 0, 0, 11, 0));
}
setBackground(Theme.createRadSelectorDrawable(getThemedColor(Theme.key_listSelector), 16, 16));
setClickable(true);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(dp(32), MeasureSpec.EXACTLY));
}
public void set(boolean collapsed, CharSequence text) {
textView.cancelAnimation();
textView.setText(text);
collapsedArrow.animate().cancel();
collapsedArrow.animate().rotation(collapsed ? 0 : 180).setDuration(340).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).start();
}
}
} }

View file

@ -0,0 +1,76 @@
package org.telegram.ui.Cells;
import static org.telegram.messenger.AndroidUtilities.dp;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.AnimatedTextView;
import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.LayoutHelper;
@SuppressLint("ViewConstructor")
public class CollapseTextCell extends FrameLayout {
public final AnimatedTextView textView;
private View collapsedArrow;
private Theme.ResourcesProvider resourcesProvider;
@SuppressLint("UseCompatLoadingForDrawables")
public CollapseTextCell(Context context, Theme.ResourcesProvider resourcesProvider) {
super(context);
this.resourcesProvider = resourcesProvider;
textView = new AnimatedTextView(context);
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider));
textView.setTextSize(dp(14));
textView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
textView.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
textView.setOnWidthUpdatedListener(this::updateCollapseArrowTranslation);
addView(textView, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 21, 0, 38, 3));
collapsedArrow = new View(context);
Drawable drawable = getContext().getResources().getDrawable(R.drawable.arrow_more).mutate();
drawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider), PorterDuff.Mode.MULTIPLY));
collapsedArrow.setBackground(drawable);
addView(collapsedArrow, LayoutHelper.createFrameRelatively(14, 14, Gravity.START | Gravity.CENTER_VERTICAL, 21, 1, 0, 3));
}
public void set(CharSequence text, boolean collapsed) {
textView.setText(text);
collapsedArrow.animate().cancel();
collapsedArrow.animate().rotation(collapsed ? 0 : 180).setDuration(340).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).start();
}
public void setColor(int colorKey) {
int color = Theme.getColor(colorKey, resourcesProvider);
textView.setTextColor(color);
collapsedArrow.getBackground().setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(dp(46), MeasureSpec.EXACTLY));
updateCollapseArrowTranslation();
}
private void updateCollapseArrowTranslation() {
float textWidth = textView.getDrawable().getCurrentWidth();
float translateX = textWidth + dp(1);
if (LocaleController.isRTL) {
collapsedArrow.setTranslationX(-translateX);
} else {
collapsedArrow.setTranslationX(translateX);
}
}
}

View file

@ -1619,7 +1619,14 @@ public class DialogCell extends BaseCell implements StoriesListPlaceProvider.Ava
messageString = LocaleController.getString("BoostingGiveawayResults", R.string.BoostingGiveawayResults); messageString = LocaleController.getString("BoostingGiveawayResults", R.string.BoostingGiveawayResults);
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media;
messageString = "\uD83D\uDCCA " + mediaPoll.poll.question; 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) { } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
messageString = "\uD83C\uDFAE " + message.messageOwner.media.game.title; messageString = "\uD83C\uDFAE " + message.messageOwner.media.game.title;
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice) { } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice) {
@ -5064,14 +5071,28 @@ public class DialogCell extends BaseCell implements StoriesListPlaceProvider.Ava
} }
} else if (message.messageOwner.media != null && !message.isMediaEmpty()) { } else if (message.messageOwner.media != null && !message.isMediaEmpty()) {
currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex]; currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
String innerMessage; CharSequence innerMessage;
int colorKey = Theme.key_chats_attachMessage; int colorKey = Theme.key_chats_attachMessage;
if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) { if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media; TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media;
if (Build.VERSION.SDK_INT >= 18) { if (Build.VERSION.SDK_INT >= 18) {
innerMessage = String.format("\uD83D\uDCCA \u2068%s\u2069", mediaPoll.poll.question); 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 { } else {
innerMessage = String.format("\uD83D\uDCCA %s", mediaPoll.poll.question); 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) { } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
if (Build.VERSION.SDK_INT >= 18) { if (Build.VERSION.SDK_INT >= 18) {
@ -5098,7 +5119,9 @@ public class DialogCell extends BaseCell implements StoriesListPlaceProvider.Ava
innerMessage = msgText.toString(); innerMessage = msgText.toString();
colorKey = Theme.key_chats_actionMessage; colorKey = Theme.key_chats_actionMessage;
} }
innerMessage = innerMessage.replace('\n', ' '); if (innerMessage instanceof String) {
innerMessage = ((String) innerMessage).replace('\n', ' ');
}
CharSequence message = innerMessage; CharSequence message = innerMessage;
if (applyThumbs) { if (applyThumbs) {
message = applyThumbs(innerMessage); message = applyThumbs(innerMessage);

View file

@ -148,8 +148,8 @@ public class EditTextCell extends FrameLayout {
} }
editText.setPadding(dp(21), dp(15), dp((maxLength > 0 ? 42 : 0) + 21), dp(15)); editText.setPadding(dp(21), dp(15), dp((maxLength > 0 ? 42 : 0) + 21), dp(15));
editText.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); editText.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP);
editText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_CLASS_TEXT | (multiline ? InputType.TYPE_TEXT_FLAG_MULTI_LINE : 0) | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); editText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_CLASS_TEXT | (multiline ? InputType.TYPE_TEXT_FLAG_MULTI_LINE : 0) | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
editText.setRawInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); editText.setRawInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
editText.setHint(hint); editText.setHint(hint);
editText.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); editText.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
editText.setCursorSize(dp(19)); editText.setCursorSize(dp(19));

View file

@ -98,7 +98,7 @@ public class GraySectionCell extends FrameLayout {
rightTextView.setOnClickListener(null); rightTextView.setOnClickListener(null);
} }
public void setText(String left, String right, OnClickListener onClickListener) { public void setText(CharSequence left, CharSequence right, OnClickListener onClickListener) {
textView.setText(left); textView.setText(left);
rightTextView.setText(right, false); rightTextView.setText(right, false);
rightTextView.setOnClickListener(onClickListener); rightTextView.setOnClickListener(onClickListener);

View file

@ -26,19 +26,24 @@ import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.ui.ActionBar.SimpleTextView; import org.telegram.ui.ActionBar.SimpleTextView;
import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.AnimatedTextView;
import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LayoutHelper;
import java.util.ArrayList; import java.util.ArrayList;
public class HeaderCell extends FrameLayout { public class HeaderCell extends FrameLayout {
public int id;
protected int padding; protected int padding;
protected int bottomMargin; protected int bottomMargin;
private TextView textView; private TextView textView;
private AnimatedTextView animatedTextView;
private SimpleTextView textView2; private SimpleTextView textView2;
private int height = 40; private int height = 40;
private final Theme.ResourcesProvider resourcesProvider; private final Theme.ResourcesProvider resourcesProvider;
private boolean animated;
public HeaderCell(Context context) { public HeaderCell(Context context) {
this(context, Theme.key_windowBackgroundWhiteBlueHeader, 21, 15, false, null); this(context, Theme.key_windowBackgroundWhiteBlueHeader, 21, 15, false, null);
@ -65,11 +70,26 @@ public class HeaderCell extends FrameLayout {
} }
public HeaderCell(Context context, int textColorKey, int padding, int topMargin, int bottomMargin, boolean text2, Theme.ResourcesProvider resourcesProvider) { public HeaderCell(Context context, int textColorKey, int padding, int topMargin, int bottomMargin, boolean text2, Theme.ResourcesProvider resourcesProvider) {
this(context, textColorKey, padding, topMargin, bottomMargin, text2, false, resourcesProvider);
}
public HeaderCell(Context context, int textColorKey, int padding, int topMargin, int bottomMargin, boolean text2, boolean animated, Theme.ResourcesProvider resourcesProvider) {
super(context); super(context);
this.resourcesProvider = resourcesProvider; this.resourcesProvider = resourcesProvider;
this.padding = padding; this.padding = padding;
this.bottomMargin = bottomMargin; this.bottomMargin = bottomMargin;
this.animated = animated;
if (animated) {
animatedTextView = new AnimatedTextView(getContext());
animatedTextView.setTextSize(AndroidUtilities.dp(15));
animatedTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM));
animatedTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
animatedTextView.setTextColor(getThemedColor(textColorKey));
animatedTextView.setTag(textColorKey);
animatedTextView.getDrawable().setHacks(true, true, false);
addView(animatedTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, height - topMargin, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, padding, topMargin, padding, text2 ? 0 : bottomMargin));
} else {
textView = new TextView(getContext()); textView = new TextView(getContext());
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
textView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); textView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM));
@ -79,6 +99,7 @@ public class HeaderCell extends FrameLayout {
textView.setTextColor(getThemedColor(textColorKey)); textView.setTextColor(getThemedColor(textColorKey));
textView.setTag(textColorKey); textView.setTag(textColorKey);
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, padding, topMargin, padding, text2 ? 0 : bottomMargin)); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, padding, topMargin, padding, text2 ? 0 : bottomMargin));
}
if (text2) { if (text2) {
textView2 = new SimpleTextView(getContext()); textView2 = new SimpleTextView(getContext());
@ -120,17 +141,30 @@ public class HeaderCell extends FrameLayout {
} }
public void setTextSize(float dip) { public void setTextSize(float dip) {
if (animated) {
animatedTextView.setTextSize(AndroidUtilities.dp(dip));
} else {
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, dip); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, dip);
} }
}
public void setTextColor(int color) { public void setTextColor(int color) {
textView.setTextColor(color); textView.setTextColor(color);
} }
public void setText(CharSequence text) { public void setText(CharSequence text) {
setText(text, false);
}
public void setText(CharSequence text, boolean animate) {
if (this.animated) {
animatedTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
animatedTextView.setText(text, animate);
} else {
textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
textView.setText(text); textView.setText(text);
} }
}
public void setText2(CharSequence text) { public void setText2(CharSequence text) {
if (textView2 == null) { if (textView2 == null) {

View file

@ -8,6 +8,8 @@
package org.telegram.ui.Cells; package org.telegram.ui.Cells;
import static org.telegram.messenger.AndroidUtilities.dp;
import android.content.Context; import android.content.Context;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.PorterDuff; import android.graphics.PorterDuff;
@ -15,6 +17,7 @@ import android.graphics.PorterDuffColorFilter;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.Gravity; import android.view.Gravity;
import android.view.View;
import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.ImageView; import android.widget.ImageView;
@ -25,13 +28,16 @@ import org.telegram.messenger.LocaleController;
import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.AnimatedTextView;
import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.Switch; import org.telegram.ui.Components.Switch;
public class NotificationsCheckCell extends FrameLayout { public class NotificationsCheckCell extends FrameLayout {
private TextView textView; private TextView textView;
private TextView valueTextView; private AnimatedTextView valueTextView;
private TextView multilineValueTextView;
@SuppressWarnings("FieldCanBeLocal") @SuppressWarnings("FieldCanBeLocal")
private ImageView imageView; private ImageView imageView;
private Switch checkBox; private Switch checkBox;
@ -78,16 +84,26 @@ public class NotificationsCheckCell extends FrameLayout {
textView.setEllipsize(TextUtils.TruncateAt.END); textView.setEllipsize(TextUtils.TruncateAt.END);
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 80 : (withImage ? 64 : padding), 13 + (currentHeight - 70) / 2, LocaleController.isRTL ? (withImage ? 64 : padding) : 80, 0)); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 80 : (withImage ? 64 : padding), 13 + (currentHeight - 70) / 2, LocaleController.isRTL ? (withImage ? 64 : padding) : 80, 0));
valueTextView = new TextView(context); valueTextView = new AnimatedTextView(context);
valueTextView.setAnimationProperties(.55f, 0, 320, CubicBezierInterpolator.EASE_OUT_QUINT);
valueTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2, resourcesProvider)); valueTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2, resourcesProvider));
valueTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); valueTextView.setTextSize(dp(13));
valueTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); valueTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
valueTextView.setLines(1);
valueTextView.setMaxLines(1);
valueTextView.setSingleLine(true);
valueTextView.setPadding(0, 0, 0, 0); valueTextView.setPadding(0, 0, 0, 0);
valueTextView.setEllipsize(TextUtils.TruncateAt.END); valueTextView.setEllipsizeByGradient(true);
addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 80 : (withImage ? 64 : padding), 38 - (withImage ? 2 : 0) + (currentHeight - 70) / 2, LocaleController.isRTL ? (withImage ? 64 : padding) : 80, 0)); addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 80 : (withImage ? 64 : padding), 38 - 9 - (withImage ? 2 : 0) + (currentHeight - 70) / 2, LocaleController.isRTL ? (withImage ? 64 : padding) : 80, 0));
multilineValueTextView = new TextView(context);
multilineValueTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2, resourcesProvider));
multilineValueTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
multilineValueTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
multilineValueTextView.setLines(0);
multilineValueTextView.setMaxLines(0);
multilineValueTextView.setSingleLine(false);
multilineValueTextView.setEllipsize(null);
multilineValueTextView.setPadding(0, 0, 0, 0);
multilineValueTextView.setVisibility(View.GONE);
addView(multilineValueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 80 : (withImage ? 64 : padding), 38 - (withImage ? 2 : 0) + (currentHeight - 70) / 2, LocaleController.isRTL ? (withImage ? 64 : padding) : 80, 0));
checkBox = new Switch(context, resourcesProvider) { checkBox = new Switch(context, resourcesProvider) {
@Override @Override
@ -113,7 +129,7 @@ public class NotificationsCheckCell extends FrameLayout {
if (isMultiline) { if (isMultiline) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
} else { } else {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(currentHeight), MeasureSpec.EXACTLY)); super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(dp(currentHeight), MeasureSpec.EXACTLY));
} }
} }
@ -130,38 +146,46 @@ public class NotificationsCheckCell extends FrameLayout {
} }
public void setTextAndValueAndIconAndCheck(CharSequence text, CharSequence value, int iconResId, boolean checked, int iconType, boolean multiline, boolean divider) { public void setTextAndValueAndIconAndCheck(CharSequence text, CharSequence value, int iconResId, boolean checked, int iconType, boolean multiline, boolean divider) {
setTextAndValueAndIconAndCheck(text, value, iconResId, checked, iconType, multiline, divider, false);
}
public void setTextAndValueAndIconAndCheck(CharSequence text, CharSequence value, int iconResId, boolean checked, int iconType, boolean multiline, boolean divider, boolean animated) {
textView.setText(text); textView.setText(text);
valueTextView.setText(value);
if (imageView != null) { if (imageView != null) {
imageView.setImageResource(iconResId); imageView.setImageResource(iconResId);
imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogIcon), PorterDuff.Mode.MULTIPLY)); imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogIcon), PorterDuff.Mode.MULTIPLY));
} }
checkBox.setChecked(checked, iconType, animationsEnabled); checkBox.setChecked(checked, iconType, animationsEnabled);
valueTextView.setVisibility(VISIBLE);
needDivider = divider;
setMultiline(multiline); setMultiline(multiline);
if (isMultiline) {
multilineValueTextView.setText(value);
} else {
valueTextView.setText(value, animated);
}
(isMultiline ? multilineValueTextView : valueTextView).setVisibility(VISIBLE);
checkBox.setContentDescription(text); checkBox.setContentDescription(text);
needDivider = divider;
} }
public void setMultiline(boolean multiline) { public void setMultiline(boolean multiline) {
isMultiline = multiline; isMultiline = multiline;
if (multiline) { if (multiline) {
valueTextView.setLines(0); multilineValueTextView.setVisibility(View.VISIBLE);
valueTextView.setMaxLines(0); valueTextView.setVisibility(View.GONE);
valueTextView.setSingleLine(false); multilineValueTextView.setPadding(0, 0, 0, dp(14));
valueTextView.setEllipsize(null);
valueTextView.setPadding(0, 0, 0, AndroidUtilities.dp(14));
} else { } else {
valueTextView.setLines(1); multilineValueTextView.setVisibility(View.GONE);
valueTextView.setMaxLines(1); valueTextView.setVisibility(View.VISIBLE);
valueTextView.setSingleLine(true);
valueTextView.setEllipsize(TextUtils.TruncateAt.END);
valueTextView.setPadding(0, 0, 0, 0); valueTextView.setPadding(0, 0, 0, 0);
} }
} }
public void setValue(CharSequence value) { public void setValue(CharSequence value) {
valueTextView.setText(value); if (isMultiline) {
multilineValueTextView.setText(value);
} else {
valueTextView.setText(value, true);
}
} }
public void setDrawLine(boolean value) { public void setDrawLine(boolean value) {
@ -184,17 +208,17 @@ public class NotificationsCheckCell extends FrameLayout {
protected void onDraw(Canvas canvas) { protected void onDraw(Canvas canvas) {
if (needDivider) { if (needDivider) {
canvas.drawLine( canvas.drawLine(
LocaleController.isRTL ? 0 : AndroidUtilities.dp(imageView != null ? 64 : 20), LocaleController.isRTL ? 0 : dp(imageView != null ? 64 : 20),
getMeasuredHeight() - 1, getMeasuredHeight() - 1,
getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(imageView != null ? 64 : 20) : 0), getMeasuredWidth() - (LocaleController.isRTL ? dp(imageView != null ? 64 : 20) : 0),
getMeasuredHeight() - 1, getMeasuredHeight() - 1,
Theme.dividerPaint Theme.dividerPaint
); );
} }
if (drawLine) { if (drawLine) {
int x = LocaleController.isRTL ? AndroidUtilities.dp(76) : getMeasuredWidth() - AndroidUtilities.dp(76) - 1; int x = LocaleController.isRTL ? dp(76) : getMeasuredWidth() - dp(76) - 1;
int y = (getMeasuredHeight() - AndroidUtilities.dp(22)) / 2; int y = (getMeasuredHeight() - dp(22)) / 2;
canvas.drawRect(x, y, x + 2, y + AndroidUtilities.dp(22), Theme.dividerPaint); canvas.drawRect(x, y, x + 2, y + dp(22), Theme.dividerPaint);
} }
} }
@ -208,10 +232,17 @@ public class NotificationsCheckCell extends FrameLayout {
info.setClassName("android.widget.Switch"); info.setClassName("android.widget.Switch");
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append(textView.getText()); sb.append(textView.getText());
if (isMultiline) {
if (multilineValueTextView != null && !TextUtils.isEmpty(multilineValueTextView.getText())) {
sb.append("\n");
sb.append(multilineValueTextView.getText());
}
} else {
if (valueTextView != null && !TextUtils.isEmpty(valueTextView.getText())) { if (valueTextView != null && !TextUtils.isEmpty(valueTextView.getText())) {
sb.append("\n"); sb.append("\n");
sb.append(valueTextView.getText()); sb.append(valueTextView.getText());
} }
}
info.setContentDescription(sb); info.setContentDescription(sb);
info.setCheckable(true); info.setCheckable(true);
info.setChecked(checkBox.isChecked()); info.setChecked(checkBox.isChecked());

View file

@ -13,6 +13,7 @@ import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet; import android.animation.AnimatorSet;
import android.animation.ObjectAnimator; import android.animation.ObjectAnimator;
import android.animation.ValueAnimator; import android.animation.ValueAnimator;
import android.content.ContentUris;
import android.content.Context; import android.content.Context;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.Canvas; import android.graphics.Canvas;
@ -23,10 +24,12 @@ import android.graphics.Rect;
import android.graphics.RectF; import android.graphics.RectF;
import android.graphics.Region; import android.graphics.Region;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.SystemClock; import android.os.SystemClock;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Size;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.Gravity; import android.view.Gravity;
import android.view.MotionEvent; import android.view.MotionEvent;
@ -44,6 +47,7 @@ import androidx.core.math.MathUtils;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageLocation;
import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.ImageReceiver;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
@ -60,6 +64,8 @@ import org.telegram.ui.Components.spoilers.SpoilerEffect;
import org.telegram.ui.Components.spoilers.SpoilerEffect2; import org.telegram.ui.Components.spoilers.SpoilerEffect2;
import org.telegram.ui.PhotoViewer; import org.telegram.ui.PhotoViewer;
import java.io.IOException;
public class PhotoAttachPhotoCell extends FrameLayout { public class PhotoAttachPhotoCell extends FrameLayout {
private BackupImageView imageView; private BackupImageView imageView;

View file

@ -8,13 +8,19 @@
package org.telegram.ui.Cells; package org.telegram.ui.Cells;
import static org.telegram.messenger.AndroidUtilities.dp;
import android.animation.Animator; import android.animation.Animator;
import android.animation.AnimatorSet; import android.animation.AnimatorSet;
import android.animation.ObjectAnimator; import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context; import android.content.Context;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.PorterDuff; import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.util.TypedValue; import android.util.TypedValue;
@ -27,19 +33,28 @@ import android.view.inputmethod.InputConnection;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.ImageView; import android.widget.ImageView;
import androidx.annotation.NonNull;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.SimpleTextView; import org.telegram.ui.ActionBar.SimpleTextView;
import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.AnimatedEmojiDrawable;
import org.telegram.ui.Components.ChatActivityEnterViewAnimatedIconView;
import org.telegram.ui.Components.CheckBox2; import org.telegram.ui.Components.CheckBox2;
import org.telegram.ui.Components.EditTextBoldCursor; import org.telegram.ui.Components.EditTextBoldCursor;
import org.telegram.ui.Components.EditTextCaption; import org.telegram.ui.Components.EditTextCaption;
import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.SuggestEmojiView;
import java.util.ArrayList; import java.util.ArrayList;
public class PollEditTextCell extends FrameLayout { public class PollEditTextCell extends FrameLayout implements SuggestEmojiView.AnchorViewDelegate {
public static final int TYPE_DEFAULT = 0;
public static final int TYPE_EMOJI = 1;
private EditTextBoldCursor textView; private EditTextBoldCursor textView;
private ImageView deleteImageView; private ImageView deleteImageView;
@ -50,16 +65,22 @@ public class PollEditTextCell extends FrameLayout {
private boolean needDivider; private boolean needDivider;
private AnimatorSet checkBoxAnimation; private AnimatorSet checkBoxAnimation;
private boolean alwaysShowText2; private boolean alwaysShowText2;
private ChatActivityEnterViewAnimatedIconView emojiButton;
private ValueAnimator valueAnimator;
public PollEditTextCell(Context context, OnClickListener onDelete) { public PollEditTextCell(Context context, OnClickListener onDelete) {
this(context, false, onDelete); this(context, false, TYPE_DEFAULT, onDelete);
} }
public PollEditTextCell(Context context, boolean caption, OnClickListener onDelete) { public PollEditTextCell(Context context, boolean caption, int type, OnClickListener onDelete) {
super(context); super(context);
if (caption) {
textView = new EditTextCaption(context, null) { textView = new EditTextCaption(context, null) {
@Override
protected int emojiCacheType() {
return AnimatedEmojiDrawable.CACHE_TYPE_ALERT_PREVIEW;
}
@Override @Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) { public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
InputConnection conn = super.onCreateInputConnection(outAttrs); InputConnection conn = super.onCreateInputConnection(outAttrs);
@ -86,6 +107,18 @@ public class PollEditTextCell extends FrameLayout {
return super.onTouchEvent(event); return super.onTouchEvent(event);
} }
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
if (type == TYPE_EMOJI) {
if (focused && emojiButton.getVisibility() == View.GONE) {
setEmojiButtonVisibility(true);
} else if (!focused && emojiButton.getVisibility() == View.VISIBLE) {
setEmojiButtonVisibility(false);
}
}
}
@Override @Override
public ActionMode startActionMode(ActionMode.Callback callback, int type) { public ActionMode startActionMode(ActionMode.Callback callback, int type) {
ActionMode actionMode = super.startActionMode(callback, type); ActionMode actionMode = super.startActionMode(callback, type);
@ -101,38 +134,10 @@ public class PollEditTextCell extends FrameLayout {
} }
}; };
((EditTextCaption) textView).setAllowTextEntitiesIntersection(true); ((EditTextCaption) textView).setAllowTextEntitiesIntersection(true);
} else {
textView = new EditTextBoldCursor(context) {
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
InputConnection conn = super.onCreateInputConnection(outAttrs);
if (showNextButton) {
outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
}
return conn;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
onEditTextDraw(this, canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled()) {
return false;
}
if (event.getAction() == MotionEvent.ACTION_UP) {
onFieldTouchUp(this);
}
return super.onTouchEvent(event);
}
};
}
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
textView.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText)); textView.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
textView.setMaxLines(type == TYPE_EMOJI ? 4 : Integer.MAX_VALUE);
// textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); // textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
textView.setBackgroundDrawable(null); textView.setBackgroundDrawable(null);
textView.setImeOptions(textView.getImeOptions() | EditorInfo.IME_FLAG_NO_EXTRACT_UI); textView.setImeOptions(textView.getImeOptions() | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
@ -140,7 +145,8 @@ public class PollEditTextCell extends FrameLayout {
textView.setPadding(AndroidUtilities.dp(4), AndroidUtilities.dp(10), AndroidUtilities.dp(4), AndroidUtilities.dp(11)); textView.setPadding(AndroidUtilities.dp(4), AndroidUtilities.dp(10), AndroidUtilities.dp(4), AndroidUtilities.dp(11));
if (onDelete != null) { if (onDelete != null) {
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 58 : 64, 0, !LocaleController.isRTL ? 58 : 64, 0)); int endMargin = type == TYPE_EMOJI ? 102: 58;
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, LocaleController.isRTL ? endMargin : 64, 0, !LocaleController.isRTL ? endMargin : 64, 0));
moveImageView = new ImageView(context); moveImageView = new ImageView(context);
moveImageView.setFocusable(false); moveImageView.setFocusable(false);
@ -179,7 +185,27 @@ public class PollEditTextCell extends FrameLayout {
onCheckBoxClick(PollEditTextCell.this, !checkBox.isChecked()); onCheckBoxClick(PollEditTextCell.this, !checkBox.isChecked());
}); });
} else { } else {
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, 19, 0, 19, 0)); int endMargin = type == TYPE_EMOJI ? 80: 19;
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, LocaleController.isRTL ? endMargin : 19, 0, LocaleController.isRTL ? 19 : endMargin, 0));
}
if (type == TYPE_EMOJI) {
emojiButton = new ChatActivityEnterViewAnimatedIconView(context);
emojiButton.setAlpha(0.80f);
emojiButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteGrayIcon), PorterDuff.Mode.SRC_IN));
emojiButton.setState(ChatActivityEnterViewAnimatedIconView.State.SMILE, false);
int padding = dp(9.5f);
emojiButton.setPadding(padding, padding, padding, padding);
emojiButton.setVisibility(View.GONE);
int endMargin = deleteImageView == null ? 3 : 48;
addView(emojiButton, LayoutHelper.createFrame(48, 48, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT), LocaleController.isRTL ? endMargin : 0, 0, LocaleController.isRTL ? 0 : endMargin, 0));
if (Build.VERSION.SDK_INT >= 21) {
emojiButton.setBackground(Theme.createSelectorDrawable(Theme.getColor(Theme.key_stickers_menuSelector)));
}
emojiButton.setOnClickListener(view -> {
onEmojiButtonClicked(this);
});
emojiButton.setContentDescription(LocaleController.getString("Emoji", R.string.Emoji));
} }
} }
@ -197,6 +223,9 @@ public class PollEditTextCell extends FrameLayout {
if (deleteImageView != null) { if (deleteImageView != null) {
deleteImageView.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48), MeasureSpec.EXACTLY)); deleteImageView.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48), MeasureSpec.EXACTLY));
} }
if (emojiButton != null) {
emojiButton.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48), MeasureSpec.EXACTLY));
}
if (moveImageView != null) { if (moveImageView != null) {
moveImageView.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48), MeasureSpec.EXACTLY)); moveImageView.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48), MeasureSpec.EXACTLY));
} }
@ -211,9 +240,13 @@ public class PollEditTextCell extends FrameLayout {
right = 42; right = 42;
} else if (deleteImageView == null) { } else if (deleteImageView == null) {
right = 70; right = 70;
} else {
if (emojiButton != null) {
right = 174;
} else { } else {
right = 122; right = 122;
} }
}
textView.measure(MeasureSpec.makeMeasureSpec(width - getPaddingLeft() - getPaddingRight() - AndroidUtilities.dp(right), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); textView.measure(MeasureSpec.makeMeasureSpec(width - getPaddingLeft() - getPaddingRight() - AndroidUtilities.dp(right), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = textView.getMeasuredHeight(); int h = textView.getMeasuredHeight();
setMeasuredDimension(width, Math.max(AndroidUtilities.dp(50), textView.getMeasuredHeight()) + (needDivider ? 1 : 0)); setMeasuredDimension(width, Math.max(AndroidUtilities.dp(50), textView.getMeasuredHeight()) + (needDivider ? 1 : 0));
@ -335,6 +368,10 @@ public class PollEditTextCell extends FrameLayout {
setWillNotDraw(!divider); setWillNotDraw(!divider);
} }
public ChatActivityEnterViewAnimatedIconView getEmojiButton() {
return emojiButton;
}
public void setEnabled(boolean value, ArrayList<Animator> animators) { public void setEnabled(boolean value, ArrayList<Animator> animators) {
setEnabled(value); setEnabled(value);
} }
@ -343,6 +380,10 @@ public class PollEditTextCell extends FrameLayout {
} }
protected void onEmojiButtonClicked(PollEditTextCell cell) {
}
public void setText2(String text) { public void setText2(String text) {
if (textView2 == null) { if (textView2 == null) {
return; return;
@ -354,10 +395,94 @@ public class PollEditTextCell extends FrameLayout {
return textView2; return textView2;
} }
private void setEmojiButtonVisibility(boolean visible) {
if (valueAnimator != null) {
valueAnimator.cancel();
}
if (visible) {
emojiButton.setVisibility(View.VISIBLE);
emojiButton.setScaleX(0f);
emojiButton.setScaleY(0f);
emojiButton.setAlpha(0f);
}
valueAnimator = ValueAnimator.ofFloat(visible ? 0 : 1, visible ? 1 : 0);
valueAnimator.addUpdateListener(animation -> {
float value = (Float) animation.getAnimatedValue();
emojiButton.setScaleX(value);
emojiButton.setScaleY(value);
emojiButton.setAlpha(Math.max(value, 0.80f));
if (textView2 != null && deleteImageView == null && textView2.getVisibility() == View.VISIBLE) {
textView2.setTranslationY(AndroidUtilities.dp(26) * value);
}
});
valueAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(@NonNull Animator animation) {
}
@Override
public void onAnimationEnd(@NonNull Animator animation) {
if (!visible) {
emojiButton.setVisibility(View.GONE);
} else {
emojiButton.setScaleX(1f);
emojiButton.setScaleY(1f);
emojiButton.setAlpha(0.80f);
}
}
@Override
public void onAnimationCancel(@NonNull Animator animation) {
}
@Override
public void onAnimationRepeat(@NonNull Animator animation) {
}
});
valueAnimator.setDuration(200L);
valueAnimator.start();
}
@Override @Override
protected void onDraw(Canvas canvas) { protected void onDraw(Canvas canvas) {
if (needDivider && drawDivider()) { if (needDivider && drawDivider()) {
canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(moveImageView != null ? 63 : 20), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(moveImageView != null ? 63 : 20) : 0), getMeasuredHeight() - 1, Theme.dividerPaint); canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(moveImageView != null ? 63 : 20), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(moveImageView != null ? 63 : 20) : 0), getMeasuredHeight() - 1, Theme.dividerPaint);
} }
} }
@Override
public BaseFragment getParentFragment() {
return null;
}
@Override
public void setFieldText(CharSequence text) {
textView.setText(text);
}
@Override
public void addTextChangedListener(TextWatcher watcher) {
textView.addTextChangedListener(watcher);
}
@Override
public EditTextBoldCursor getEditField() {
return textView;
}
@Override
public CharSequence getFieldText() {
if (textView.length() > 0) {
return textView.getText();
}
return null;
}
@Override
public Editable getEditText() {
return textView.getText();
}
} }

View file

@ -25,6 +25,7 @@ import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserConfig;
import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer; import org.telegram.tgnet.NativeByteBuffer;
@ -53,7 +54,7 @@ public class ProfileChannelCell extends FrameLayout {
private final TextView headerView; private final TextView headerView;
private final AnimatedTextView subscribersView; private final AnimatedTextView subscribersView;
private final DialogCell dialogCell; public final DialogCell dialogCell;
public ProfileChannelCell(BaseFragment fragment) { public ProfileChannelCell(BaseFragment fragment) {
super(fragment.getContext()); super(fragment.getContext());
@ -67,7 +68,7 @@ public class ProfileChannelCell extends FrameLayout {
headerView = new TextView(context); headerView = new TextView(context);
headerView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); headerView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM));
headerView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); headerView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
headerView.setText("Channel"); headerView.setText(LocaleController.getString(R.string.ProfileChannel));
headerLayout.addView(headerView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP)); headerLayout.addView(headerView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP));
subscribersView = new ClickableAnimatedTextView(context); subscribersView = new ClickableAnimatedTextView(context);
@ -80,6 +81,7 @@ public class ProfileChannelCell extends FrameLayout {
headerLayout.addView(subscribersView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 17, Gravity.LEFT | Gravity.TOP, 4, 2, 4, 0)); headerLayout.addView(subscribersView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 17, Gravity.LEFT | Gravity.TOP, 4, 2, 4, 0));
dialogCell = new DialogCell(null, context, false, true, UserConfig.selectedAccount, resourcesProvider); dialogCell = new DialogCell(null, context, false, true, UserConfig.selectedAccount, resourcesProvider);
dialogCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
dialogCell.setDialogCellDelegate(new DialogCell.DialogCellDelegate() { dialogCell.setDialogCellDelegate(new DialogCell.DialogCellDelegate() {
@Override @Override
public void onButtonClicked(DialogCell dialogCell) { public void onButtonClicked(DialogCell dialogCell) {
@ -149,8 +151,8 @@ public class ProfileChannelCell extends FrameLayout {
private final LoadingDrawable loadingDrawable; private final LoadingDrawable loadingDrawable;
@Override @Override
protected void onDraw(Canvas canvas) { protected void dispatchDraw(Canvas canvas) {
super.onDraw(canvas); super.dispatchDraw(canvas);
float loading = loadingAlpha.set(this.loading); float loading = loadingAlpha.set(this.loading);
if (loading > 0) { if (loading > 0) {

View file

@ -29,6 +29,8 @@ public class RadioColorCell extends FrameLayout {
private RadioButton radioButton; private RadioButton radioButton;
private final Theme.ResourcesProvider resourcesProvider; private final Theme.ResourcesProvider resourcesProvider;
public int heightDp = 50;
public RadioColorCell(Context context) { public RadioColorCell(Context context) {
this(context, null); this(context, null);
} }
@ -69,7 +71,7 @@ public class RadioColorCell extends FrameLayout {
} }
super.onMeasure( super.onMeasure(
MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(50) + (text2View.getVisibility() == View.VISIBLE ? AndroidUtilities.dp(4) + text2View.getMeasuredHeight() : 0), MeasureSpec.EXACTLY) MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(heightDp) + (text2View.getVisibility() == View.VISIBLE ? AndroidUtilities.dp(4) + text2View.getMeasuredHeight() : 0), MeasureSpec.EXACTLY)
); );
} }

View file

@ -185,7 +185,7 @@ public class ReactedUserHolderView extends FrameLayout {
dialogId = user.id; dialogId = user.id;
titleView.setText(UserObject.getUserName(user)); titleView.setText(UserObject.getUserName(user));
} else { } else {
dialogId = chat.id; dialogId = -chat.id;
titleView.setText(chat.title); titleView.setText(chat.title);
} }

View file

@ -8,16 +8,23 @@
package org.telegram.ui.Cells; package org.telegram.ui.Cells;
import static org.telegram.messenger.AndroidUtilities.dp;
import android.content.Context; import android.content.Context;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff; import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffColorFilter;
import android.graphics.RectF; import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.view.Gravity; import android.view.Gravity;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.ImageView; import android.widget.ImageView;
import androidx.annotation.NonNull;
import org.checkerframework.checker.units.qual.A;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.LocationController; import org.telegram.messenger.LocationController;
@ -25,7 +32,10 @@ import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserConfig;
import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.ConnectionsManager;
import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.AnimatedFloat;
import org.telegram.ui.Components.AnimatedTextView;
import org.telegram.ui.Components.CombinedDrawable; import org.telegram.ui.Components.CombinedDrawable;
import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.ActionBar.SimpleTextView; import org.telegram.ui.ActionBar.SimpleTextView;
import org.telegram.ui.Components.ShareLocationDrawable; import org.telegram.ui.Components.ShareLocationDrawable;
@ -39,7 +49,9 @@ public class SendLocationCell extends FrameLayout {
private long dialogId; private long dialogId;
private RectF rect; private RectF rect;
private boolean live; private boolean live;
private boolean liveDisable;
private final Theme.ResourcesProvider resourcesProvider; private final Theme.ResourcesProvider resourcesProvider;
public boolean useDivider;
private Runnable invalidateRunnable = new Runnable() { private Runnable invalidateRunnable = new Runnable() {
@Override @Override
@ -50,49 +62,56 @@ public class SendLocationCell extends FrameLayout {
} }
}; };
public SendLocationCell(Context context, boolean live, Theme.ResourcesProvider resourcesProvider) { public SendLocationCell(Context context, boolean live, boolean liveDisable, Theme.ResourcesProvider resourcesProvider) {
super(context); super(context);
this.resourcesProvider = resourcesProvider; this.resourcesProvider = resourcesProvider;
this.live = live; this.live = live;
this.liveDisable = liveDisable;
imageView = new ImageView(context); imageView = new ImageView(context);
addView(imageView, LayoutHelper.createFrame(46, 46, Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 13, 0, LocaleController.isRTL ? 13 : 0, 0));
setBackground(Theme.AdaptiveRipple.rect());
imageView.setTag(live ? Theme.key_location_sendLiveLocationBackground + Theme.key_location_sendLiveLocationIcon : Theme.key_location_sendLocationBackground + Theme.key_location_sendLocationIcon);
Drawable circle = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), getThemedColor(live ? Theme.key_location_sendLiveLocationBackground : Theme.key_location_sendLocationBackground), getThemedColor(live ? Theme.key_location_sendLiveLocationBackground : Theme.key_location_sendLocationBackground));
if (live) {
rect = new RectF();
Drawable drawable = new ShareLocationDrawable(context, 4);
drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_sendLiveLocationIcon), PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(circle, drawable);
combinedDrawable.setCustomSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42));
imageView.setBackgroundDrawable(combinedDrawable);
AndroidUtilities.runOnUIThread(invalidateRunnable, 1000);
setWillNotDraw(false);
} else {
Drawable drawable = getResources().getDrawable(R.drawable.pin).mutate();
drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_sendLocationIcon), PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(circle, drawable);
combinedDrawable.setCustomSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42));
combinedDrawable.setIconSize(AndroidUtilities.dp(24), AndroidUtilities.dp(24));
imageView.setBackgroundDrawable(combinedDrawable);
}
addView(imageView, LayoutHelper.createFrame(42, 42, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 15, 12, LocaleController.isRTL ? 15 : 0, 0));
titleTextView = new SimpleTextView(context); titleTextView = new SimpleTextView(context);
titleTextView.setTextSize(16); titleTextView.setTextSize(16);
titleTextView.setTag(live ? Theme.key_location_sendLiveLocationText : Theme.key_location_sendLocationText);
titleTextView.setTextColor(getThemedColor(live ? Theme.key_location_sendLiveLocationText : Theme.key_location_sendLocationText));
titleTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); titleTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
addView(titleTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 20, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 16 : 73, 12, LocaleController.isRTL ? 73 : 16, 0)); addView(titleTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 20, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 16 : 73, 9.33f, LocaleController.isRTL ? 73 : 16, 0));
accurateTextView = new SimpleTextView(context); accurateTextView = new SimpleTextView(context);
accurateTextView.setTextSize(14); accurateTextView.setTextSize(14);
accurateTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3)); accurateTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3));
accurateTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); accurateTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
addView(accurateTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 20, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 16 : 73, 37, LocaleController.isRTL ? 73 : 16, 0)); addView(accurateTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 20, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 16 : 73, 33, LocaleController.isRTL ? 73 : 16, 0));
updateImage();
setWillNotDraw(false);
}
private void updateImage() {
titleTextView.setTag(live ? liveDisable ? Theme.key_text_RedBold : Theme.key_location_sendLiveLocationText : Theme.key_location_sendLocationText);
titleTextView.setTextColor(getThemedColor(live ? liveDisable ? Theme.key_text_RedBold : Theme.key_location_sendLiveLocationText : Theme.key_location_sendLocationText));
imageView.setTag(live ? liveDisable ? Theme.key_color_red : Theme.key_location_sendLiveLocationBackground + Theme.key_location_sendLiveLocationIcon : Theme.key_location_sendLocationBackground + Theme.key_location_sendLocationIcon);
Drawable circle = Theme.createSimpleSelectorCircleDrawable(dp(46), getThemedColor(live ? liveDisable ? Theme.key_color_red : Theme.key_location_sendLiveLocationBackground : Theme.key_location_sendLocationBackground), getThemedColor(live ? liveDisable ? Theme.key_color_red : Theme.key_location_sendLiveLocationBackground : Theme.key_location_sendLocationBackground));
if (live) {
rect = new RectF();
Drawable drawable = new ShareLocationDrawable(getContext(), liveDisable ? ShareLocationDrawable.TYPE_DISABLE : ShareLocationDrawable.TYPE_ADD);
drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_sendLiveLocationIcon), PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(circle, drawable);
combinedDrawable.setCustomSize(dp(46), dp(46));
imageView.setBackgroundDrawable(combinedDrawable);
if (!liveDisable) {
AndroidUtilities.cancelRunOnUIThread(invalidateRunnable);
AndroidUtilities.runOnUIThread(invalidateRunnable, 1000);
}
} else {
Drawable drawable = getResources().getDrawable(R.drawable.pin).mutate();
drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_sendLocationIcon), PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(circle, drawable);
combinedDrawable.setCustomSize(dp(46), dp(46));
combinedDrawable.setIconSize(dp(24), dp(24));
imageView.setBackgroundDrawable(combinedDrawable);
}
} }
private ImageView getImageView() { private ImageView getImageView() {
@ -113,7 +132,7 @@ public class SendLocationCell extends FrameLayout {
@Override @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(66), MeasureSpec.EXACTLY)); super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(dp(60), MeasureSpec.EXACTLY));
} }
@Override @Override
@ -126,6 +145,7 @@ public class SendLocationCell extends FrameLayout {
protected void onAttachedToWindow() { protected void onAttachedToWindow() {
super.onAttachedToWindow(); super.onAttachedToWindow();
if (rect != null) { if (rect != null) {
AndroidUtilities.cancelRunOnUIThread(invalidateRunnable);
AndroidUtilities.runOnUIThread(invalidateRunnable, 1000); AndroidUtilities.runOnUIThread(invalidateRunnable, 1000);
} }
} }
@ -145,41 +165,93 @@ public class SendLocationCell extends FrameLayout {
private void checkText() { private void checkText() {
LocationController.SharingLocationInfo info = LocationController.getInstance(currentAccount).getSharingLocationInfo(dialogId); LocationController.SharingLocationInfo info = LocationController.getInstance(currentAccount).getSharingLocationInfo(dialogId);
if (info != null) { if (info != null) {
setText(LocaleController.getString("StopLiveLocation", R.string.StopLiveLocation), LocaleController.formatLocationUpdateDate(info.messageObject.messageOwner.edit_date != 0 ? info.messageObject.messageOwner.edit_date : info.messageObject.messageOwner.date)); if (liveDisable) {
setText(LocaleController.getString(R.string.StopLiveLocation), LocaleController.formatLocationUpdateDate(info.messageObject.messageOwner.edit_date != 0 ? info.messageObject.messageOwner.edit_date : info.messageObject.messageOwner.date));
} else {
setText(LocaleController.getString(R.string.SharingLiveLocation), LocaleController.getString(R.string.SharingLiveLocationAdd));
}
} else { } else {
setText(LocaleController.getString("SendLiveLocation", R.string.SendLiveLocation), LocaleController.getString("SendLiveLocationInfo", R.string.SendLiveLocationInfo)); setText(LocaleController.getString("SendLiveLocation", R.string.SendLiveLocation), LocaleController.getString("SendLiveLocationInfo", R.string.SendLiveLocationInfo));
} }
} }
private final AnimatedFloat progress = new AnimatedFloat(this, 350, CubicBezierInterpolator.EASE_OUT_QUINT);
private final AnimatedFloat progressAlpha = new AnimatedFloat(this, 350, CubicBezierInterpolator.EASE_OUT_QUINT);
private final AnimatedFloat progressScale = new AnimatedFloat(this, 350, CubicBezierInterpolator.EASE_OUT_QUINT);
private final AnimatedTextView.AnimatedTextDrawable textDrawable = new AnimatedTextView.AnimatedTextDrawable(false, true, false);
{
textDrawable.setAnimationProperties(.3f, 0, 320, CubicBezierInterpolator.EASE_OUT_QUINT);
textDrawable.setTextSize(dp(12));
textDrawable.setTypeface(Typeface.DEFAULT_BOLD);
textDrawable.setGravity(Gravity.CENTER);
textDrawable.setCallback(this);
}
@Override
protected boolean verifyDrawable(@NonNull Drawable who) {
return who == textDrawable || super.verifyDrawable(who);
}
@Override @Override
protected void onDraw(Canvas canvas) { protected void onDraw(Canvas canvas) {
LocationController.SharingLocationInfo currentInfo = LocationController.getInstance(currentAccount).getSharingLocationInfo(dialogId); if (useDivider) {
if (currentInfo == null) { Paint dividerPaint = Theme.getThemePaint(Theme.key_paint_divider, resourcesProvider);
if (dividerPaint != null) {
canvas.drawRect(LocaleController.isRTL ? 0 : dp(73), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? dp(73) : 0), getMeasuredHeight(), dividerPaint);
}
}
if (liveDisable) {
return; return;
} }
LocationController.SharingLocationInfo currentInfo = LocationController.getInstance(currentAccount).getSharingLocationInfo(dialogId);
float progress = this.progress.get();
float alpha;
int currentTime = ConnectionsManager.getInstance(currentAccount).getCurrentTime(); int currentTime = ConnectionsManager.getInstance(currentAccount).getCurrentTime();
if (currentInfo.stopTime < currentTime) { if (currentInfo != null && currentInfo.stopTime >= currentTime && currentInfo.period != 0x7FFFFFFF) {
progress = Math.abs(currentInfo.stopTime - currentTime) / (float) currentInfo.period;
alpha = this.progressAlpha.set(true);
} else {
alpha = this.progressAlpha.set(false);
}
if (alpha <= 0) {
return; return;
} }
float progress = Math.abs(currentInfo.stopTime - currentTime) / (float) currentInfo.period;
if (LocaleController.isRTL) { if (LocaleController.isRTL) {
rect.set(AndroidUtilities.dp(13), AndroidUtilities.dp(18), AndroidUtilities.dp(43), AndroidUtilities.dp(48)); rect.set(dp(13), getMeasuredHeight() / 2f - dp(15), dp(43), getMeasuredHeight() / 2f + dp(15));
} else { } else {
rect.set(getMeasuredWidth() - AndroidUtilities.dp(43), AndroidUtilities.dp(18), getMeasuredWidth() - AndroidUtilities.dp(13), AndroidUtilities.dp(48)); rect.set(getMeasuredWidth() - dp(43), getMeasuredHeight() / 2f - dp(15), getMeasuredWidth() - dp(13), getMeasuredHeight() / 2f + dp(15));
} }
canvas.save();
final float s = AndroidUtilities.lerp(.6f, 1f, alpha);
canvas.scale(s, s, rect.centerX(), rect.centerY());
int color = getThemedColor(Theme.key_location_liveLocationProgress); int color = getThemedColor(Theme.key_location_liveLocationProgress);
Theme.chat_radialProgress2Paint.setColor(color); Theme.chat_radialProgress2Paint.setColor(color);
Theme.chat_livePaint.setColor(color);
canvas.drawArc(rect, -90, -360 * progress, false, Theme.chat_radialProgress2Paint); int a = Theme.chat_radialProgress2Paint.getAlpha();
Theme.chat_radialProgress2Paint.setAlpha((int) (.20f * a * alpha));
canvas.drawArc(rect, -90, 360, false, Theme.chat_radialProgress2Paint);
Theme.chat_radialProgress2Paint.setAlpha((int) (a * alpha));
canvas.drawArc(rect, -90, -360 * this.progress.set(progress), false, Theme.chat_radialProgress2Paint);
Theme.chat_radialProgress2Paint.setAlpha(a);
String text = LocaleController.formatLocationLeftTime(Math.abs(currentInfo.stopTime - currentTime)); if (currentInfo != null) {
textDrawable.setText(LocaleController.formatLocationLeftTime(Math.abs(currentInfo.stopTime - currentTime)));
}
int len = textDrawable.getText().length();
final float s2 = progressScale.set(len > 4 ? .75f : (len > 3 ? .85f : 1f));
canvas.scale(s2, s2, rect.centerX(), rect.centerY());
textDrawable.setTextColor(color);
textDrawable.setAlpha((int) (0xFF * alpha));
textDrawable.setBounds((int) rect.left, (int) (rect.centerY() - dp(12 + 1)), (int) rect.right, (int) (rect.centerY() + dp(12)));
textDrawable.draw(canvas);
float size = Theme.chat_livePaint.measureText(text); canvas.restore();
canvas.drawText(text, rect.centerX() - size / 2, AndroidUtilities.dp(37), Theme.chat_livePaint);
} }
private int getThemedColor(int key) { private int getThemedColor(int key) {

View file

@ -6,6 +6,7 @@ import android.text.Spanned;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.Gravity; import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
@ -19,12 +20,15 @@ import org.telegram.messenger.UserConfig;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.LinkSpanDrawable;
import org.telegram.ui.Components.ScaleStateListAnimator;
import org.telegram.ui.Components.URLSpanNoUnderline; import org.telegram.ui.Components.URLSpanNoUnderline;
public class SettingsSuggestionCell extends LinearLayout { public class SettingsSuggestionCell extends LinearLayout {
public final static int TYPE_PHONE = 0; public final static int TYPE_PHONE = 0;
public final static int TYPE_PASSWORD = 1; public final static int TYPE_PASSWORD = 1;
public final static int TYPE_GRACE = 2;
private TextView textView; private TextView textView;
private TextView detailTextView; private TextView detailTextView;
@ -49,22 +53,23 @@ public class SettingsSuggestionCell extends LinearLayout {
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader, resourcesProvider)); textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader, resourcesProvider));
addView(textView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 21, 15, 21, 0)); addView(textView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 21, 15, 21, 0));
detailTextView = new TextView(context); detailTextView = new LinkSpanDrawable.LinksTextView(context, resourcesProvider);
detailTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2, resourcesProvider)); detailTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider));
detailTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); detailTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
detailTextView.setLinkTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkText, resourcesProvider)); detailTextView.setLinkTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkText, resourcesProvider));
detailTextView.setHighlightColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkSelection, resourcesProvider)); detailTextView.setHighlightColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkSelection, resourcesProvider));
detailTextView.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy()); detailTextView.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy());
detailTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); detailTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
addView(detailTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 21, 8, 21, 0)); addView(detailTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 21, 14, 21, 0));
LinearLayout linearLayout = new LinearLayout(context); LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(HORIZONTAL); linearLayout.setOrientation(HORIZONTAL);
addView(linearLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 40, 21, 17, 21, 20)); addView(linearLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 44, 21, 16, 21, 15));
for (int a = 0; a < 2; a++) { for (int a = 0; a < 2; a++) {
TextView textView = new TextView(context); TextView textView = new TextView(context);
textView.setBackground(Theme.AdaptiveRipple.filledRectByKey(Theme.key_featuredStickers_addButton, 4)); textView.setBackground(Theme.AdaptiveRipple.filledRectByKey(Theme.key_featuredStickers_addButton, 8));
ScaleStateListAnimator.apply(textView, 0.02f, 1.5f);
textView.setLines(1); textView.setLines(1);
textView.setSingleLine(true); textView.setSingleLine(true);
textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setGravity(Gravity.CENTER_HORIZONTAL);
@ -72,8 +77,8 @@ public class SettingsSuggestionCell extends LinearLayout {
textView.setGravity(Gravity.CENTER); textView.setGravity(Gravity.CENTER);
textView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText, resourcesProvider)); textView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText, resourcesProvider));
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM));
linearLayout.addView(textView, LayoutHelper.createLinear(0, 40, 0.5f, a == 0 ? 0 : 4, 0, a == 0 ? 4 : 0, 0)); linearLayout.addView(textView, LayoutHelper.createLinear(0, 44, 0.5f, a == 0 ? 0 : 4, 0, a == 0 ? 4 : 0, 0));
if (a == 0) { if (a == 0) {
yesButton = textView; yesButton = textView;
yesButton.setOnClickListener(v -> onYesClick(currentType)); yesButton.setOnClickListener(v -> onYesClick(currentType));
@ -104,12 +109,19 @@ public class SettingsSuggestionCell extends LinearLayout {
} }
detailTextView.setText(builder); detailTextView.setText(builder);
yesButton.setText(LocaleController.getString("CheckPhoneNumberYes", R.string.CheckPhoneNumberYes)); yesButton.setText(LocaleController.getString("CheckPhoneNumberYes", R.string.CheckPhoneNumberYes));
noButton.setVisibility(View.VISIBLE);
noButton.setText(LocaleController.getString("CheckPhoneNumberNo", R.string.CheckPhoneNumberNo)); noButton.setText(LocaleController.getString("CheckPhoneNumberNo", R.string.CheckPhoneNumberNo));
} else if (type == TYPE_PASSWORD) { } else if (type == TYPE_PASSWORD) {
textView.setText(LocaleController.getString("YourPasswordHeader", R.string.YourPasswordHeader)); textView.setText(LocaleController.getString("YourPasswordHeader", R.string.YourPasswordHeader));
detailTextView.setText(LocaleController.getString("YourPasswordRemember", R.string.YourPasswordRemember)); detailTextView.setText(LocaleController.getString("YourPasswordRemember", R.string.YourPasswordRemember));
yesButton.setText(LocaleController.getString("YourPasswordRememberYes", R.string.YourPasswordRememberYes)); yesButton.setText(LocaleController.getString("YourPasswordRememberYes", R.string.YourPasswordRememberYes));
noButton.setVisibility(View.VISIBLE);
noButton.setText(LocaleController.getString("YourPasswordRememberNo", R.string.YourPasswordRememberNo)); noButton.setText(LocaleController.getString("YourPasswordRememberNo", R.string.YourPasswordRememberNo));
} else if (type == TYPE_GRACE) {
textView.setText(LocaleController.getString(R.string.GraceSuggestionTitle));
detailTextView.setText(LocaleController.getString(R.string.GraceSuggestionMessage));
yesButton.setText(LocaleController.getString(R.string.GraceSuggestionButton));
noButton.setVisibility(View.GONE);
} }
} }

View file

@ -8,6 +8,7 @@ import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator; import android.animation.ValueAnimator;
import android.content.Context; import android.content.Context;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Color; import android.graphics.Color;
import android.graphics.Paint; import android.graphics.Paint;
@ -58,6 +59,9 @@ import org.telegram.ui.Components.spoilers.SpoilerEffect2;
import org.telegram.ui.PhotoViewer; import org.telegram.ui.PhotoViewer;
import org.telegram.ui.Stories.StoryWidgetsImageDecorator; import org.telegram.ui.Stories.StoryWidgetsImageDecorator;
import org.telegram.ui.Stories.recorder.DominantColors; import org.telegram.ui.Stories.recorder.DominantColors;
import org.telegram.ui.Stories.recorder.StoryPrivacyBottomSheet;
import java.util.HashMap;
public class SharedPhotoVideoCell2 extends FrameLayout { public class SharedPhotoVideoCell2 extends FrameLayout {
@ -77,6 +81,10 @@ public class SharedPhotoVideoCell2 extends FrameLayout {
String videoText; String videoText;
boolean drawVideoIcon = true; boolean drawVideoIcon = true;
private int privacyType;
private Bitmap privacyBitmap;
private Paint privacyPaint;
boolean drawViews; boolean drawViews;
AnimatedFloat viewsAlpha = new AnimatedFloat(this, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); AnimatedFloat viewsAlpha = new AnimatedFloat(this, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT);
AnimatedTextView.AnimatedTextDrawable viewsText = new AnimatedTextView.AnimatedTextDrawable(false, true, true); AnimatedTextView.AnimatedTextDrawable viewsText = new AnimatedTextView.AnimatedTextDrawable(false, true, true);
@ -93,6 +101,7 @@ public class SharedPhotoVideoCell2 extends FrameLayout {
private boolean gradientDrawableLoading; private boolean gradientDrawableLoading;
public boolean isStory; public boolean isStory;
public boolean isStoryPinned;
static long lastUpdateDownloadSettingsTime; static long lastUpdateDownloadSettingsTime;
static boolean lastAutoDownload; static boolean lastAutoDownload;
@ -169,7 +178,7 @@ public class SharedPhotoVideoCell2 extends FrameLayout {
if (currentMessageObject == null && messageObject == null) { if (currentMessageObject == null && messageObject == null) {
return; return;
} }
if (currentMessageObject != null && messageObject != null && currentMessageObject.getId() == messageObject.getId() && oldParentColumsCount == parentColumnsCount) { if (currentMessageObject != null && messageObject != null && currentMessageObject.getId() == messageObject.getId() && oldParentColumsCount == parentColumnsCount && (privacyType == 100) == isStoryPinned) {
return; return;
} }
currentMessageObject = messageObject; currentMessageObject = messageObject;
@ -186,6 +195,8 @@ public class SharedPhotoVideoCell2 extends FrameLayout {
showVideoLayout = false; showVideoLayout = false;
gradientDrawableLoading = false; gradientDrawableLoading = false;
gradientDrawable = null; gradientDrawable = null;
privacyType = -1;
privacyBitmap = null;
return; return;
} else { } else {
if (attached) { if (attached) {
@ -303,6 +314,35 @@ public class SharedPhotoVideoCell2 extends FrameLayout {
imageReceiver.addDecorator(new StoryWidgetsImageDecorator(messageObject.storyItem)); 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(); invalidate();
} }
@ -446,6 +486,7 @@ public class SharedPhotoVideoCell2 extends FrameLayout {
bounds.set(imageReceiver.getImageX(), imageReceiver.getImageY(), imageReceiver.getImageX2(), imageReceiver.getImageY2()); bounds.set(imageReceiver.getImageX(), imageReceiver.getImageY(), imageReceiver.getImageX2(), imageReceiver.getImageY2());
drawDuration(canvas, bounds, 1f); drawDuration(canvas, bounds, 1f);
drawViews(canvas, bounds, 1f); drawViews(canvas, bounds, 1f);
drawPrivacy(canvas, bounds, 1f);
if (checkBoxBase != null && (style == STYLE_CACHE || checkBoxBase.getProgress() != 0)) { if (checkBoxBase != null && (style == STYLE_CACHE || checkBoxBase.getProgress() != 0)) {
canvas.save(); canvas.save();
@ -474,12 +515,16 @@ public class SharedPhotoVideoCell2 extends FrameLayout {
return; return;
} }
final float fwidth = bounds.width() + dp(20) * checkBoxProgress;
final float scale = bounds.width() / fwidth;
if (alpha < 1) { if (alpha < 1) {
alpha = (float) Math.pow(alpha, 8); alpha = (float) Math.pow(alpha, 8);
} }
canvas.save(); canvas.save();
canvas.translate(bounds.left, bounds.top); canvas.translate(bounds.left, bounds.top);
canvas.scale(scale, scale, 0, bounds.height());
canvas.clipRect(0, 0, bounds.width(), bounds.height()); canvas.clipRect(0, 0, bounds.width(), bounds.height());
if (currentParentColumnsCount != 9 && videoInfoLayot == null && videoText != null) { if (currentParentColumnsCount != 9 && videoInfoLayot == null && videoText != null) {
int textWidth = (int) Math.ceil(sharedResources.textPaint.measureText(videoText)); int textWidth = (int) Math.ceil(sharedResources.textPaint.measureText(videoText));
@ -487,16 +532,9 @@ public class SharedPhotoVideoCell2 extends FrameLayout {
} else if ((currentParentColumnsCount >= 9 || videoText == null) && videoInfoLayot != null) { } else if ((currentParentColumnsCount >= 9 || videoText == null) && videoInfoLayot != null) {
videoInfoLayot = null; videoInfoLayot = null;
} }
int width; final boolean up = viewsOnLeft(fwidth);
if (videoInfoLayot == null) { int width = dp(8) + (videoInfoLayot != null ? videoInfoLayot.getWidth() : 0) + (drawVideoIcon ? dp(10) : 0);
width = dp(8); canvas.translate(dp(5), dp(1) + bounds.height() - dp(17) - dp(4) - (up ? dp(17 + 5) : 0));
} else {
width = dp(4) + videoInfoLayot.getWidth() + dp(4);
}
if (drawVideoIcon) {
width += dp(10);
}
canvas.translate(dp(5), dp(1) + bounds.height() - dp(17) - dp(4));
AndroidUtilities.rectTmp.set(0, 0, width, dp(17)); AndroidUtilities.rectTmp.set(0, 0, width, dp(17));
int oldAlpha = Theme.chat_timeBackgroundPaint.getAlpha(); int oldAlpha = Theme.chat_timeBackgroundPaint.getAlpha();
Theme.chat_timeBackgroundPaint.setAlpha((int) (oldAlpha * alpha)); Theme.chat_timeBackgroundPaint.setAlpha((int) (oldAlpha * alpha));
@ -529,11 +567,46 @@ public class SharedPhotoVideoCell2 extends FrameLayout {
} }
} }
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) { public void drawViews(Canvas canvas, RectF bounds, float alpha) {
if (!isStory || imageReceiver != null && !imageReceiver.getVisible() || currentParentColumnsCount >= 5) { if (!isStory || imageReceiver != null && !imageReceiver.getVisible() || currentParentColumnsCount >= 5) {
return; 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); float a = viewsAlpha.set(drawViews);
alpha *= a; alpha *= a;
@ -547,11 +620,12 @@ public class SharedPhotoVideoCell2 extends FrameLayout {
canvas.save(); canvas.save();
canvas.translate(bounds.left, bounds.top); canvas.translate(bounds.left, bounds.top);
canvas.scale(scale, scale, left ? 0 : bounds.width(), bounds.height());
canvas.clipRect(0, 0, bounds.width(), bounds.height()); canvas.clipRect(0, 0, bounds.width(), bounds.height());
float width = dp(18 + 8) + viewsText.getCurrentWidth(); float width = dp(18 + 8) + viewsText.getCurrentWidth();
canvas.translate(bounds.width() - dp(5) - width, dp(1) + bounds.height() - dp(17) - dp(4)); 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)); AndroidUtilities.rectTmp.set(0, 0, width, dp(17));
int oldAlpha = Theme.chat_timeBackgroundPaint.getAlpha(); int oldAlpha = Theme.chat_timeBackgroundPaint.getAlpha();
Theme.chat_timeBackgroundPaint.setAlpha((int) (oldAlpha * alpha)); Theme.chat_timeBackgroundPaint.setAlpha((int) (oldAlpha * alpha));
@ -787,6 +861,7 @@ public class SharedPhotoVideoCell2 extends FrameLayout {
Drawable viewDrawable; Drawable viewDrawable;
Paint highlightPaint = new Paint(); Paint highlightPaint = new Paint();
SparseArray<String> imageFilters = new SparseArray<>(); SparseArray<String> imageFilters = new SparseArray<>();
private final HashMap<Integer, Bitmap> privacyBitmaps = new HashMap<>();
public SharedResources(Context context, Theme.ResourcesProvider resourcesProvider) { public SharedResources(Context context, Theme.ResourcesProvider resourcesProvider) {
textPaint.setTextSize(dp(12)); textPaint.setTextSize(dp(12));
@ -807,6 +882,39 @@ public class SharedPhotoVideoCell2 extends FrameLayout {
} }
return 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 @Override

View file

@ -114,7 +114,7 @@ public class SharingLiveLocationCell extends FrameLayout {
distanceTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3)); distanceTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3));
distanceTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); distanceTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
addView(distanceTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? padding : 73, 37, LocaleController.isRTL ? 73 : padding, 0)); addView(distanceTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? padding : 73, 33, LocaleController.isRTL ? 73 : padding, 0));
} else { } else {
addView(avatarImageView, LayoutHelper.createFrame(42, 42, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 15, 6, LocaleController.isRTL ? 15 : 0, 0)); addView(avatarImageView, LayoutHelper.createFrame(42, 42, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 15, 6, LocaleController.isRTL ? 15 : 0, 0));
addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? padding : 74, 17, LocaleController.isRTL ? 74 : padding, 0)); addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? padding : 74, 17, LocaleController.isRTL ? 74 : padding, 0));
@ -385,6 +385,9 @@ public class SharingLiveLocationCell extends FrameLayout {
} }
} }
private Drawable foreverDrawable;
private int foreverDrawableColor;
@Override @Override
protected void onDraw(Canvas canvas) { protected void onDraw(Canvas canvas) {
if (currentInfo == null && liveLocation == null) { if (currentInfo == null && liveLocation == null) {
@ -399,11 +402,12 @@ public class SharingLiveLocationCell extends FrameLayout {
stopTime = liveLocation.object.date + liveLocation.object.media.period; stopTime = liveLocation.object.date + liveLocation.object.media.period;
period = liveLocation.object.media.period; period = liveLocation.object.media.period;
} }
boolean forever = period == 0x7FFFFFFF;
int currentTime = ConnectionsManager.getInstance(currentAccount).getCurrentTime(); int currentTime = ConnectionsManager.getInstance(currentAccount).getCurrentTime();
if (stopTime < currentTime) { if (stopTime < currentTime && !forever) {
return; return;
} }
float progress = Math.abs(stopTime - currentTime) / (float) period; float progress = forever ? 1 : Math.abs(stopTime - currentTime) / (float) period;
if (LocaleController.isRTL) { if (LocaleController.isRTL) {
rect.set(dp(13), dp(distanceTextView != null ? 18 : 12), dp(43), dp(distanceTextView != null ? 48 : 42)); rect.set(dp(13), dp(distanceTextView != null ? 18 : 12), dp(43), dp(distanceTextView != null ? 48 : 42));
} else { } else {
@ -419,14 +423,33 @@ public class SharingLiveLocationCell extends FrameLayout {
Theme.chat_radialProgress2Paint.setColor(color); Theme.chat_radialProgress2Paint.setColor(color);
Theme.chat_livePaint.setColor(color); Theme.chat_livePaint.setColor(color);
int a = Theme.chat_radialProgress2Paint.getAlpha();
Theme.chat_radialProgress2Paint.setAlpha((int) (.20f * a));
canvas.drawArc(rect, -90, 360, false, Theme.chat_radialProgress2Paint);
Theme.chat_radialProgress2Paint.setAlpha((int) (a));
canvas.drawArc(rect, -90, -360 * progress, false, Theme.chat_radialProgress2Paint); canvas.drawArc(rect, -90, -360 * progress, false, Theme.chat_radialProgress2Paint);
Theme.chat_radialProgress2Paint.setAlpha(a);
if (forever) {
if (foreverDrawable == null) {
foreverDrawable = getContext().getResources().getDrawable(R.drawable.filled_location_forever).mutate();
}
if (Theme.chat_livePaint.getColor() != foreverDrawableColor) {
foreverDrawable.setColorFilter(new PorterDuffColorFilter(foreverDrawableColor = Theme.chat_livePaint.getColor(), PorterDuff.Mode.SRC_IN));
}
foreverDrawable.setBounds(
(int) rect.centerX() - foreverDrawable.getIntrinsicWidth() / 2,
(int) rect.centerY() - foreverDrawable.getIntrinsicHeight() / 2,
(int) rect.centerX() + foreverDrawable.getIntrinsicWidth() / 2,
(int) rect.centerY() + foreverDrawable.getIntrinsicHeight() / 2
);
foreverDrawable.draw(canvas);
} else {
String text = LocaleController.formatLocationLeftTime(stopTime - currentTime); String text = LocaleController.formatLocationLeftTime(stopTime - currentTime);
float size = Theme.chat_livePaint.measureText(text); float size = Theme.chat_livePaint.measureText(text);
canvas.drawText(text, rect.centerX() - size / 2, dp(distanceTextView != null ? 37 : 31), Theme.chat_livePaint); canvas.drawText(text, rect.centerX() - size / 2, dp(distanceTextView != null ? 37 : 31), Theme.chat_livePaint);
} }
}
private int getThemedColor(int key) { private int getThemedColor(int key) {
return Theme.getColor(key, resourcesProvider); return Theme.getColor(key, resourcesProvider);

View file

@ -15,6 +15,7 @@ import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect; import android.graphics.Rect;
import android.os.Build; import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity; import android.view.Gravity;
import android.view.HapticFeedbackConstants; import android.view.HapticFeedbackConstants;
import android.view.MotionEvent; import android.view.MotionEvent;
@ -22,6 +23,7 @@ import android.widget.FrameLayout;
import org.checkerframework.checker.units.qual.A; import org.checkerframework.checker.units.qual.A;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.ChannelMonetizationLayout; import org.telegram.ui.ChannelMonetizationLayout;
@ -92,7 +94,7 @@ public class SlideIntChooseView extends FrameLayout {
if (options == null || whenChanged == null) { if (options == null || whenChanged == null) {
return; return;
} }
final int newValue = (int) (options.min + stepsCount * progress); final int newValue = (int) Math.round(options.min + stepsCount * progress);
if (value != newValue) { if (value != newValue) {
value = newValue; value = newValue;
AndroidUtilities.vibrateCursor(seekBarView); AndroidUtilities.vibrateCursor(seekBarView);
@ -132,7 +134,13 @@ public class SlideIntChooseView extends FrameLayout {
public void updateTexts(int value, boolean animated) { public void updateTexts(int value, boolean animated) {
minText.cancelAnimation(); minText.cancelAnimation();
minText.setText(processText(options.minStringResId, options.min), animated); maxText.cancelAnimation();
if (!TextUtils.isEmpty(options.resId)) {
valueText.cancelAnimation();
valueText.setText(LocaleController.formatPluralString(options.resId, value), animated);
minText.setText("" + options.min, animated);
maxText.setText("" + options.max, animated);
} else {
int valueResId; int valueResId;
if (value <= options.min) { if (value <= options.min) {
valueResId = options.valueMinStringResId; valueResId = options.valueMinStringResId;
@ -143,8 +151,9 @@ public class SlideIntChooseView extends FrameLayout {
} }
valueText.cancelAnimation(); valueText.cancelAnimation();
valueText.setText(processText(valueResId, value), animated); valueText.setText(processText(valueResId, value), animated);
maxText.cancelAnimation(); minText.setText(processText(options.minStringResId, options.min), animated);
maxText.setText(processText(options.maxStringResId, options.max), animated); maxText.setText(processText(options.maxStringResId, options.max), animated);
}
maxText.setTextColor(Theme.getColor(value >= options.max ? Theme.key_windowBackgroundWhiteValueText : Theme.key_windowBackgroundWhiteGrayText, resourcesProvider), animated); maxText.setTextColor(Theme.getColor(value >= options.max ? Theme.key_windowBackgroundWhiteValueText : Theme.key_windowBackgroundWhiteGrayText, resourcesProvider), animated);
setMaxTextEmojiSaturation(value >= options.max ? 1f : 0f, animated); setMaxTextEmojiSaturation(value >= options.max ? 1f : 0f, animated);
} }
@ -223,6 +232,8 @@ public class SlideIntChooseView extends FrameLayout {
public int min; public int min;
public int max; public int max;
public String resId;
public int minStringResId; public int minStringResId;
public int valueMinStringResId, valueStringResId, valueMaxStringResId; public int valueMinStringResId, valueStringResId, valueMaxStringResId;
public int maxStringResId; public int maxStringResId;
@ -244,5 +255,17 @@ public class SlideIntChooseView extends FrameLayout {
o.maxStringResId = maxStringResId; o.maxStringResId = maxStringResId;
return o; return o;
} }
public static Options make(
int style,
String resId, int min, int max
) {
Options o = new Options();
o.style = style;
o.min = min;
o.resId = resId;
o.max = max;
return o;
}
} }
} }

View file

@ -35,6 +35,7 @@ import org.telegram.ui.ActionBar.ThemeDescription;
import org.telegram.ui.Components.ColorSpanUnderline; import org.telegram.ui.Components.ColorSpanUnderline;
import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.RecyclerListView;
import org.telegram.ui.Components.ScaleStateListAnimator;
import java.util.List; import java.util.List;
@ -90,21 +91,22 @@ public class StickerSetNameCell extends FrameLayout {
lp = LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, emoji ? 5 : 15, 5, emoji ? 15 : 25, 0); lp = LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, emoji ? 5 : 15, 5, emoji ? 15 : 25, 0);
} }
addView(layout, lp); addView(layout, lp);
layout.addView(textView); layout.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, 1, Gravity.CENTER_VERTICAL));
editView = new TextView(context); editView = new TextView(context);
editView.setTextColor(getThemedColor(Theme.key_chat_emojiPanelStickerSetName)); editView.setTextColor(getThemedColor(Theme.key_chat_emojiPanelStickerSetName));
editView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 11); editView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 11);
editView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); editView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM));
editView.setEllipsize(TextUtils.TruncateAt.END); editView.setEllipsize(TextUtils.TruncateAt.END);
editView.setPadding(dp(6.33f), 0, dp(6.33f), 0); editView.setPadding(dp(6), 0, dp(6.33f), 0);
editView.setBackground(Theme.createSimpleSelectorRoundRectDrawable(dp(9), editView.setBackground(Theme.createSimpleSelectorRoundRectDrawable(dp(9),
Theme.multAlpha(getThemedColor(Theme.key_chat_emojiPanelStickerSetName), .10f), Theme.multAlpha(getThemedColor(Theme.key_chat_emojiPanelStickerSetName), .10f),
Theme.multAlpha(getThemedColor(Theme.key_chat_emojiPanelStickerSetName), .24f) Theme.multAlpha(getThemedColor(Theme.key_chat_emojiPanelStickerSetName), .24f)
)); ));
editView.setGravity(Gravity.CENTER); editView.setGravity(Gravity.CENTER);
editView.setSingleLine(true); editView.setSingleLine(true);
layout.addView(editView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, 5.33f, .66f, 0, 0)); ScaleStateListAnimator.apply(editView);
layout.addView(editView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, 0, Gravity.CENTER_VERTICAL, 5, 1, 0, 0));
editView.setVisibility(View.GONE); editView.setVisibility(View.GONE);
urlTextView = new TextView(context); urlTextView = new TextView(context);
@ -200,6 +202,10 @@ public class StickerSetNameCell extends FrameLayout {
editView.setOnClickListener(whenClickedEdit); editView.setOnClickListener(whenClickedEdit);
} }
public void setHeaderOnClick(View.OnClickListener listener) {
textView.setOnClickListener(listener);
}
private void updateTextSearchSpan() { private void updateTextSearchSpan() {
if (stickerSetName != null && stickerSetNameSearchLength > 0) { if (stickerSetName != null && stickerSetNameSearchLength > 0) {
SpannableStringBuilder builder = new SpannableStringBuilder(stickerSetName); SpannableStringBuilder builder = new SpannableStringBuilder(stickerSetName);

View file

@ -13,7 +13,9 @@ import static org.telegram.messenger.AndroidUtilities.dp;
import android.content.Context; import android.content.Context;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Color; import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint; import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff; import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
@ -25,7 +27,12 @@ import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.ImageView; import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ImageLocation;
import org.telegram.messenger.ImageReceiver;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.SimpleTextView; import org.telegram.ui.ActionBar.SimpleTextView;
@ -49,7 +56,7 @@ public class TextCell extends FrameLayout {
public final RLottieImageView imageView; public final RLottieImageView imageView;
private Switch checkBox; private Switch checkBox;
private ImageView valueImageView; private ImageView valueImageView;
private int leftPadding; public int leftPadding;
private boolean needDivider; private boolean needDivider;
public int offsetFromImage = 71; public int offsetFromImage = 71;
public int heightDp = 50; public int heightDp = 50;
@ -644,6 +651,25 @@ public class TextCell extends FrameLayout {
setValueSticker(document); setValueSticker(document);
} }
public void setTextAndSticker(CharSequence text, String localPath, boolean divider) {
imageLeft = 21;
offsetFromImage = getOffsetFromImage(false);
textView.setText(text);
textView.setRightDrawable(null);
valueTextView.setText(valueText = null, false);
valueImageView.setVisibility(GONE);
valueTextView.setVisibility(GONE);
valueSpoilersTextView.setVisibility(GONE);
imageView.setVisibility(GONE);
imageView.setPadding(0, dp(7), 0, 0);
needDivider = divider;
setWillNotDraw(!needDivider);
if (checkBox != null) {
checkBox.setVisibility(GONE);
}
setValueSticker(localPath);
}
public void setValueSticker(TLRPC.Document document) { public void setValueSticker(TLRPC.Document document) {
if (emojiDrawable == null) { if (emojiDrawable == null) {
emojiDrawable = new AnimatedEmojiDrawable.SwapAnimatedEmojiDrawable(this, dp(30)); emojiDrawable = new AnimatedEmojiDrawable.SwapAnimatedEmojiDrawable(this, dp(30));
@ -655,6 +681,64 @@ public class TextCell extends FrameLayout {
invalidate(); invalidate();
} }
public void setValueSticker(String path) {
if (emojiDrawable == null) {
emojiDrawable = new AnimatedEmojiDrawable.SwapAnimatedEmojiDrawable(this, dp(30));
if (attached) {
emojiDrawable.attach();
}
}
ImageReceiver imageReceiver = new ImageReceiver(this);
if (isAttachedToWindow()) {
imageReceiver.onAttachedToWindow();
}
addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(@NonNull View v) {
imageReceiver.onAttachedToWindow();
}
@Override
public void onViewDetachedFromWindow(@NonNull View v) {
imageReceiver.onDetachedFromWindow();
}
});
imageReceiver.setImage(path, "30_30", null, null, 0);
emojiDrawable.set(new Drawable() {
@Override
public void draw(@NonNull Canvas canvas) {
imageReceiver.setImageCoords(getBounds());
imageReceiver.draw(canvas);
}
@Override
public void setAlpha(int alpha) {
imageReceiver.setAlpha(alpha / (float) 0xFF);
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
imageReceiver.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
@Override
public int getIntrinsicWidth() {
return dp(30);
}
@Override
public int getIntrinsicHeight() {
return dp(30);
}
}, true);
invalidate();
}
protected int getOffsetFromImage(boolean colourful) { protected int getOffsetFromImage(boolean colourful) {
return colourful ? 65 : 71; return colourful ? 65 : 71;
} }

View file

@ -33,6 +33,7 @@ import org.telegram.ui.Components.Switch;
public class TextCheckCell2 extends FrameLayout { public class TextCheckCell2 extends FrameLayout {
public int id;
private TextView textView; private TextView textView;
private TextView valueTextView; private TextView valueTextView;
private Switch checkBox; private Switch checkBox;

View file

@ -33,7 +33,6 @@ public class TextColorCell extends FrameLayout {
private TextView textView; private TextView textView;
private boolean needDivider; private boolean needDivider;
private int currentColor; private int currentColor;
private float alpha = 1.0f;
private static Paint colorPaint; private static Paint colorPaint;
@ -62,19 +61,6 @@ public class TextColorCell extends FrameLayout {
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 21, 0, 21, 0)); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 21, 0, 21, 0));
} }
@Keep
@Override
public void setAlpha(float value) {
alpha = value;
invalidate();
}
@Keep
@Override
public float getAlpha() {
return alpha;
}
@Override @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(50) + (needDivider ? 1 : 0), MeasureSpec.EXACTLY)); super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(50) + (needDivider ? 1 : 0), MeasureSpec.EXACTLY));
@ -106,7 +92,6 @@ public class TextColorCell extends FrameLayout {
} }
if (currentColor != 0) { if (currentColor != 0) {
colorPaint.setColor(currentColor); colorPaint.setColor(currentColor);
colorPaint.setAlpha((int) (255 * alpha));
canvas.drawCircle(LocaleController.isRTL ? AndroidUtilities.dp(33) : getMeasuredWidth() - AndroidUtilities.dp(33), getMeasuredHeight() / 2, AndroidUtilities.dp(10), colorPaint); canvas.drawCircle(LocaleController.isRTL ? AndroidUtilities.dp(33) : getMeasuredWidth() - AndroidUtilities.dp(33), getMeasuredHeight() / 2, AndroidUtilities.dp(10), colorPaint);
} }
} }

View file

@ -738,7 +738,7 @@ public class UserCell extends FrameLayout implements NotificationCenter.Notifica
} }
} }
public void setCloseIcon(Runnable onClick) { public void setCloseIcon(View.OnClickListener onClick) {
if (onClick == null) { if (onClick == null) {
if (closeView != null) { if (closeView != null) {
removeView(closeView); removeView(closeView);
@ -754,7 +754,7 @@ public class UserCell extends FrameLayout implements NotificationCenter.Notifica
closeView.setBackground(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector, resourcesProvider), Theme.RIPPLE_MASK_CIRCLE_AUTO)); closeView.setBackground(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector, resourcesProvider), Theme.RIPPLE_MASK_CIRCLE_AUTO));
addView(closeView, LayoutHelper.createFrame(30, 30, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 14 : 0, 0, LocaleController.isRTL ? 0 : 14, 0)); addView(closeView, LayoutHelper.createFrame(30, 30, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 14 : 0, 0, LocaleController.isRTL ? 0 : 14, 0));
} }
closeView.setOnClickListener(v -> onClick.run()); closeView.setOnClickListener(onClick);
} }
} }
} }

View file

@ -17,8 +17,10 @@ import android.graphics.Bitmap;
import android.graphics.BitmapShader; import android.graphics.BitmapShader;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Color; import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint; import android.graphics.Paint;
import android.graphics.Path; import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff; import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode; import android.graphics.PorterDuffXfermode;
import android.graphics.Shader; import android.graphics.Shader;
@ -39,6 +41,7 @@ import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.GridLayoutManager;
@ -50,16 +53,21 @@ import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.ChatObject; import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ChatThemeController; import org.telegram.messenger.ChatThemeController;
import org.telegram.messenger.DialogObject; import org.telegram.messenger.DialogObject;
import org.telegram.messenger.DocumentObject;
import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.messenger.ImageLocation;
import org.telegram.messenger.ImageReceiver;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.SvgHelper;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.ResultCallback; import org.telegram.tgnet.ResultCallback;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.tgnet.tl.TL_stories; import org.telegram.tgnet.tl.TL_stories;
import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBar;
@ -378,6 +386,13 @@ public class ChannelColorActivity extends BaseFragment implements NotificationCe
contentView.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.FILL, 0, 0, 0, 68)); contentView.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.FILL, 0, 0, 0, 68));
listView.setOnItemClickListener((view, position) -> { listView.setOnItemClickListener((view, position) -> {
if (view instanceof EmojiCell) { if (view instanceof EmojiCell) {
if (position == packStickerRow) {
if (chatFull == null) return;
GroupStickersActivity fragment = new GroupStickersActivity(-dialogId);
fragment.setInfo(chatFull);
presentFragment(fragment);
return;
}
long selectedEmojiId = 0; long selectedEmojiId = 0;
if (position == replyEmojiRow) { if (position == replyEmojiRow) {
selectedEmojiId = selectedReplyEmoji; selectedEmojiId = selectedReplyEmoji;
@ -878,6 +893,9 @@ public class ChannelColorActivity extends BaseFragment implements NotificationCe
protected int packEmojiRow; protected int packEmojiRow;
protected int packEmojiHintRow; protected int packEmojiHintRow;
protected int packStickerRow;
protected int packStickerHintRow;
protected void updateRows() { protected void updateRows() {
rowsCount = 0; rowsCount = 0;
messagesPreviewRow = rowsCount++; messagesPreviewRow = rowsCount++;
@ -926,6 +944,14 @@ public class ChannelColorActivity extends BaseFragment implements NotificationCe
return 0; return 0;
} }
protected int getStickerPackStrRes() {
return 0;
}
protected int getStickerPackInfoStrRes() {
return 0;
}
protected int getEmojiStatusInfoStrRes() { protected int getEmojiStatusInfoStrRes() {
return R.string.ChannelEmojiStatusInfo; return R.string.ChannelEmojiStatusInfo;
} }
@ -1097,6 +1123,15 @@ public class ChannelColorActivity extends BaseFragment implements NotificationCe
} else { } else {
emojiCell.setEmoji(0, false); emojiCell.setEmoji(0, false);
} }
} else if (position == packStickerRow) {
emojiCell.setText(LocaleController.getString(getStickerPackStrRes()));
emojiCell.setLockLevel(0);
TLRPC.ChatFull chatFull = getMessagesController().getChatFull(-dialogId);
if (chatFull != null && chatFull.stickerset != null) {
emojiCell.setEmoji(getEmojiSetThumb(chatFull.stickerset), false);
} else {
emojiCell.setEmoji(0, false);
}
} }
break; break;
case VIEW_TYPE_SHADOW: case VIEW_TYPE_SHADOW:
@ -1112,6 +1147,8 @@ public class ChannelColorActivity extends BaseFragment implements NotificationCe
infoCell.setText(LocaleController.getString(getEmojiStatusInfoStrRes())); infoCell.setText(LocaleController.getString(getEmojiStatusInfoStrRes()));
} else if (position == packEmojiHintRow) { } else if (position == packEmojiHintRow) {
infoCell.setText(LocaleController.getString(getEmojiPackInfoStrRes())); infoCell.setText(LocaleController.getString(getEmojiPackInfoStrRes()));
} else if (position == packStickerHintRow) {
infoCell.setText(LocaleController.getString(getStickerPackInfoStrRes()));
} else if (position == removeProfileColorShadowRow) { } else if (position == removeProfileColorShadowRow) {
infoCell.setText(""); infoCell.setText("");
infoCell.setFixedSize(12); infoCell.setFixedSize(12);
@ -1165,7 +1202,7 @@ public class ChannelColorActivity extends BaseFragment implements NotificationCe
return VIEW_TYPE_COLOR_REPLY_GRID; return VIEW_TYPE_COLOR_REPLY_GRID;
} else if (position == profileColorGridRow) { } else if (position == profileColorGridRow) {
return VIEW_TYPE_COLOR_PROFILE_GRID; return VIEW_TYPE_COLOR_PROFILE_GRID;
} else if (position == replyEmojiRow || position == profileEmojiRow || position == statusEmojiRow || position == packEmojiRow) { } else if (position == replyEmojiRow || position == profileEmojiRow || position == statusEmojiRow || position == packEmojiRow || position == packStickerRow) {
return VIEW_TYPE_BUTTON_EMOJI; return VIEW_TYPE_BUTTON_EMOJI;
} else if (position == wallpaperRow || position == removeProfileColorRow) { } else if (position == wallpaperRow || position == removeProfileColorRow) {
return VIEW_TYPE_BUTTON; return VIEW_TYPE_BUTTON;
@ -1230,6 +1267,7 @@ public class ChannelColorActivity extends BaseFragment implements NotificationCe
View emojiPicker = findChildAt(profileEmojiRow); View emojiPicker = findChildAt(profileEmojiRow);
View emojiStatusPicker = findChildAt(statusEmojiRow); View emojiStatusPicker = findChildAt(statusEmojiRow);
View packEmojiPicker = findChildAt(packEmojiRow); View packEmojiPicker = findChildAt(packEmojiRow);
View packStatusPicker = findChildAt(packStickerRow);
if (profilePreview instanceof ProfilePreview) { if (profilePreview instanceof ProfilePreview) {
((ProfilePreview) profilePreview).setColor(selectedProfileColor, animated); ((ProfilePreview) profilePreview).setColor(selectedProfileColor, animated);
@ -1259,6 +1297,14 @@ public class ChannelColorActivity extends BaseFragment implements NotificationCe
((EmojiCell) packEmojiPicker).setEmoji(0, false); ((EmojiCell) packEmojiPicker).setEmoji(0, false);
} }
} }
if (packStatusPicker instanceof EmojiCell) {
TLRPC.ChatFull chatFull = getMessagesController().getChatFull(-dialogId);
if (chatFull != null && chatFull.stickerset != null) {
((EmojiCell) packStatusPicker).setEmoji(getEmojiSetThumb(chatFull.stickerset), false);
} else {
((EmojiCell) packStatusPicker).setEmoji(0, false);
}
}
updateRows(); updateRows();
} }
@ -1277,6 +1323,20 @@ public class ChannelColorActivity extends BaseFragment implements NotificationCe
return thumbDocumentId; return thumbDocumentId;
} }
private TLRPC.Document getEmojiSetThumb(TLRPC.StickerSet emojiSet) {
if (emojiSet == null) {
return null;
}
long thumbDocumentId = emojiSet.thumb_document_id;
if (thumbDocumentId == 0) {
TLRPC.TL_messages_stickerSet stickerSet = getMediaDataController().getGroupStickerSetById(emojiSet);
if (!stickerSet.documents.isEmpty()) {
return stickerSet.documents.get(0);
}
}
return null;
}
public View findChildAt(int position) { public View findChildAt(int position) {
for (int i = 0; i < listView.getChildCount(); ++i) { for (int i = 0; i < listView.getChildCount(); ++i) {
View child = listView.getChildAt(i); View child = listView.getChildAt(i);
@ -1439,6 +1499,18 @@ public class ChannelColorActivity extends BaseFragment implements NotificationCe
} }
} }
public void setEmoji(TLRPC.Document document, boolean animated) {
if (document == null) {
imageDrawable.set((Drawable) null, animated);
if (offText == null) {
offText = new Text(LocaleController.getString(R.string.ChannelReplyIconOff), 16);
}
} else {
imageDrawable.set(document, animated);
offText = null;
}
}
public void updateColors() { public void updateColors() {
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider)); textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider));
} }

View file

@ -92,6 +92,8 @@ import java.util.Locale;
public class ChannelMonetizationLayout extends FrameLayout { public class ChannelMonetizationLayout extends FrameLayout {
public static ChannelMonetizationLayout instance;
private final BaseFragment fragment; private final BaseFragment fragment;
private final Theme.ResourcesProvider resourcesProvider; private final Theme.ResourcesProvider resourcesProvider;
private final int currentAccount; private final int currentAccount;
@ -144,7 +146,7 @@ public class ChannelMonetizationLayout extends FrameLayout {
showLearnSheet(); showLearnSheet();
}, resourcesProvider), true); }, resourcesProvider), true);
balanceInfo = AndroidUtilities.replaceArrows(AndroidUtilities.replaceSingleTag(getString(MessagesController.getInstance(currentAccount).channelRevenueWithdrawalEnabled ? R.string.MonetizationBalanceInfo : R.string.MonetizationBalanceInfoNotAvailable), -1, REPLACING_TAG_TYPE_LINK_NBSP, () -> { balanceInfo = AndroidUtilities.replaceArrows(AndroidUtilities.replaceSingleTag(getString(MessagesController.getInstance(currentAccount).channelRevenueWithdrawalEnabled ? R.string.MonetizationBalanceInfo : R.string.MonetizationBalanceInfoNotAvailable), -1, REPLACING_TAG_TYPE_LINK_NBSP, () -> {
showLearnSheet(); Browser.openUrl(getContext(), getString(R.string.MonetizationBalanceInfoLink));
}), true); }), true);
setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray, resourcesProvider)); setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray, resourcesProvider));
@ -383,6 +385,7 @@ public class ChannelMonetizationLayout extends FrameLayout {
balanceSubtitle.setText("~" + BillingController.getInstance().formatCurrency(amount, "USD")); balanceSubtitle.setText("~" + BillingController.getInstance().formatCurrency(amount, "USD"));
} }
private double usd_rate;
private void initLevel() { private void initLevel() {
TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId);
if (chat != null) { if (chat != null) {
@ -427,23 +430,8 @@ public class ChannelMonetizationLayout extends FrameLayout {
impressionsChart.useHourFormat = true; impressionsChart.useHourFormat = true;
} }
availableValue.crypto_amount = stats.available_balance; usd_rate = stats.usd_rate;
availableValue.amount = (long) (availableValue.crypto_amount / 1_000_000_000.0 * stats.usd_rate * 100.0); setupBalances(stats.balances);
setBalance(availableValue.crypto_amount, availableValue.amount);
availableValue.currency = "USD";
lastWithdrawalValue.crypto_amount = stats.current_balance;
lastWithdrawalValue.amount = (long) (lastWithdrawalValue.crypto_amount / 1_000_000_000.0 * stats.usd_rate * 100.0);
lastWithdrawalValue.currency = "USD";
lifetimeValue.crypto_amount = stats.overall_revenue;
lifetimeValue.amount = (long) (lifetimeValue.crypto_amount / 1_000_000_000.0 * stats.usd_rate * 100.0);
lifetimeValue.currency = "USD";
proceedsAvailable = true;
balanceButton.setVisibility(stats.available_balance > 0 || BuildVars.DEBUG_PRIVATE_VERSION ? View.VISIBLE : View.GONE);
if (listView != null && listView.adapter != null) {
listView.adapter.update(true);
}
progress.animate().alpha(0).setDuration(380).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).withEndAction(() -> { progress.animate().alpha(0).setDuration(380).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).withEndAction(() -> {
progress.setVisibility(View.GONE); progress.setVisibility(View.GONE);
@ -453,13 +441,41 @@ public class ChannelMonetizationLayout extends FrameLayout {
} }
}), null, null, 0, stats_dc, ConnectionsManager.ConnectionTypeGeneric, true); }), null, null, 0, stats_dc, ConnectionsManager.ConnectionTypeGeneric, true);
} }
public void setupBalances(TLRPC.TL_broadcastRevenueBalances balances) {
if (usd_rate == 0) {
return;
}
availableValue.crypto_amount = balances.available_balance;
availableValue.amount = (long) (availableValue.crypto_amount / 1_000_000_000.0 * usd_rate * 100.0);
setBalance(availableValue.crypto_amount, availableValue.amount);
availableValue.currency = "USD";
lastWithdrawalValue.crypto_amount = balances.current_balance;
lastWithdrawalValue.amount = (long) (lastWithdrawalValue.crypto_amount / 1_000_000_000.0 * usd_rate * 100.0);
lastWithdrawalValue.currency = "USD";
lifetimeValue.crypto_amount = balances.overall_revenue;
lifetimeValue.amount = (long) (lifetimeValue.crypto_amount / 1_000_000_000.0 * usd_rate * 100.0);
lifetimeValue.currency = "USD";
proceedsAvailable = true;
balanceButton.setVisibility(balances.available_balance > 0 || BuildVars.DEBUG_PRIVATE_VERSION ? View.VISIBLE : View.GONE);
if (listView != null && listView.adapter != null) {
listView.adapter.update(true);
}
}
@Override @Override
protected void onAttachedToWindow() { protected void onAttachedToWindow() {
instance = this;
super.onAttachedToWindow(); super.onAttachedToWindow();
checkLearnSheet(); checkLearnSheet();
} }
@Override
protected void onDetachedFromWindow() {
instance = null;
super.onDetachedFromWindow();
}
private void checkLearnSheet() { private void checkLearnSheet() {
if (isAttachedToWindow() && proceedsAvailable && MessagesController.getGlobalMainSettings().getBoolean("monetizationadshint", true)) { if (isAttachedToWindow() && proceedsAvailable && MessagesController.getGlobalMainSettings().getBoolean("monetizationadshint", true)) {
showLearnSheet(); showLearnSheet();
@ -553,14 +569,22 @@ public class ChannelMonetizationLayout extends FrameLayout {
} }
} }
public void reloadTransactions() {
if (loadingTransactions) return;
transactions.clear();
transactionsTotalCount = 0;
loadingTransactions = false;
loadTransactions();
}
private boolean loadingTransactions = false; private boolean loadingTransactions = false;
private void loadTransactions() { private void loadTransactions() {
if (loadingTransactions) return; if (loadingTransactions) return;
if (transactions.size() >= transactionsTotalCount && transactionsTotalCount != 0) return; if (transactions.size() >= transactionsTotalCount && transactionsTotalCount != 0) return;
// TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId);
// if (chat == null || !chat.creator) { if (chat == null || !chat.creator) {
// return; return;
// } }
loadingTransactions = true; loadingTransactions = true;
TL_stats.TL_getBroadcastRevenueTransactions req = new TL_stats.TL_getBroadcastRevenueTransactions(); TL_stats.TL_getBroadcastRevenueTransactions req = new TL_stats.TL_getBroadcastRevenueTransactions();
@ -620,7 +644,7 @@ public class ChannelMonetizationLayout extends FrameLayout {
if (ChannelMonetizationLayout.tonString == null) { if (ChannelMonetizationLayout.tonString == null) {
ChannelMonetizationLayout.tonString = new HashMap<>(); ChannelMonetizationLayout.tonString = new HashMap<>();
} }
final int key = textPaint.getFontMetricsInt().bottom * (large ? 1 : -1) * (int) (100 * scale); final int key = textPaint.getFontMetricsInt().bottom * (large ? 1 : -1) * (int) (100 * scale) - (int) (100 * translateY);
SpannableString tonString = ChannelMonetizationLayout.tonString.get(key); SpannableString tonString = ChannelMonetizationLayout.tonString.get(key);
if (tonString == null) { if (tonString == null) {
tonString = new SpannableString("T"); tonString = new SpannableString("T");
@ -807,13 +831,13 @@ public class ChannelMonetizationLayout extends FrameLayout {
SpannableStringBuilder value = new SpannableStringBuilder(); SpannableStringBuilder value = new SpannableStringBuilder();
value.append(type < 0 ? "-" : "+"); value.append(type < 0 ? "-" : "+");
value.append(formatter.format((Math.abs(amount) / 1_000_000_000.0)));
value.append("TON "); value.append("TON ");
value.append(formatter.format((Math.abs(amount) / 1_000_000_000.0)));
int index = TextUtils.indexOf(value, "."); int index = TextUtils.indexOf(value, ".");
if (index >= 0) { if (index >= 0) {
value.setSpan(new RelativeSizeSpan(1.15f), 0, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); value.setSpan(new RelativeSizeSpan(1.15f), 0, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} }
valueText.setText(value); valueText.setText(replaceTON(value, valueText.getPaint(), 1.1f, dp(.33f), false));
valueText.setTextColor(Theme.getColor(type < 0 ? Theme.key_text_RedBold : Theme.key_avatar_nameInMessageGreen, resourcesProvider)); valueText.setTextColor(Theme.getColor(type < 0 ? Theme.key_text_RedBold : Theme.key_avatar_nameInMessageGreen, resourcesProvider));
setWillNotDraw(!(needDivider = divider)); setWillNotDraw(!(needDivider = divider));

View file

@ -158,6 +158,7 @@ import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.NotificationsController; import org.telegram.messenger.NotificationsController;
import org.telegram.messenger.PushListenerController;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.SecretChatHelper; import org.telegram.messenger.SecretChatHelper;
import org.telegram.messenger.SendMessagesHelper; import org.telegram.messenger.SendMessagesHelper;
@ -261,6 +262,7 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@ -905,6 +907,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private boolean openImport; private boolean openImport;
public float chatListViewPaddingTop; public float chatListViewPaddingTop;
public float paddingTopHeight;
public int chatListViewPaddingVisibleOffset; public int chatListViewPaddingVisibleOffset;
private int contentPaddingTop; private int contentPaddingTop;
@ -1023,8 +1026,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
NotificationCenter.pinnedInfoDidLoad, NotificationCenter.pinnedInfoDidLoad,
NotificationCenter.didSetNewWallpapper, NotificationCenter.didSetNewWallpapper,
NotificationCenter.savedMessagesDialogsUpdate, NotificationCenter.savedMessagesDialogsUpdate,
NotificationCenter.didApplyNewTheme, NotificationCenter.didApplyNewTheme
NotificationCenter.messageReceivedByServer // NotificationCenter.messageReceivedByServer
}; };
private final DialogInterface.OnCancelListener postponedScrollCancelListener = dialog -> { private final DialogInterface.OnCancelListener postponedScrollCancelListener = dialog -> {
@ -4501,7 +4504,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
c.translate(0, getMeasuredHeight() - blurredViewBottomOffset - transitionOffset); c.translate(0, getMeasuredHeight() - blurredViewBottomOffset - transitionOffset);
if (pullingDownDrawable == null) { if (pullingDownDrawable == null) {
pullingDownDrawable = new ChatPullingDownDrawable(currentAccount, fragmentView, dialog_id, dialogFolderId, dialogFilterId, themeDelegate); pullingDownDrawable = new ChatPullingDownDrawable(currentAccount, fragmentView, dialog_id, dialogFolderId, dialogFilterId, getTopicId(), themeDelegate);
if (nextChannels != null && !nextChannels.isEmpty()) {
pullingDownDrawable.updateDialog(nextChannels.get(0));
} else if (isTopic) {
pullingDownDrawable.updateTopic();
} else {
pullingDownDrawable.updateDialog();
}
pullingDownDrawable.onAttach(); pullingDownDrawable.onAttach();
} }
pullingDownDrawable.setWidth(getMeasuredWidth()); pullingDownDrawable.setWidth(getMeasuredWidth());
@ -5532,6 +5542,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
chatListView.setAnimateEmptyView(true, RecyclerListView.EMPTY_VIEW_ANIMATION_TYPE_ALPHA_SCALE); chatListView.setAnimateEmptyView(true, RecyclerListView.EMPTY_VIEW_ANIMATION_TYPE_ALPHA_SCALE);
chatListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); chatListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
chatListViewPaddingTop = 0; chatListViewPaddingTop = 0;
paddingTopHeight = 0;
invalidateChatListViewTopPadding(); invalidateChatListViewTopPadding();
if (MessagesController.getGlobalMainSettings().getBoolean("view_animations", true)) { if (MessagesController.getGlobalMainSettings().getBoolean("view_animations", true)) {
chatListItemAnimator = new ChatListItemAnimator(this, chatListView, themeDelegate) { chatListItemAnimator = new ChatListItemAnimator(this, chatListView, themeDelegate) {
@ -5762,10 +5773,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (!foundTopView) { if (!foundTopView) {
scrolled = super.scrollVerticallyBy(dy, recycler, state); scrolled = super.scrollVerticallyBy(dy, recycler, state);
} }
if (dy > 0 && scrolled == 0 && ChatObject.isChannel(currentChat) && chatMode != MODE_SAVED && !currentChat.megagroup && chatListView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING && !chatListView.isFastScrollAnimationRunning() && !chatListView.isMultiselect() && reportType < 0) { if (dy > 0 && scrolled == 0 && (ChatObject.isChannel(currentChat) && !currentChat.megagroup || isTopic) && chatMode != MODE_SAVED && chatListView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING && !chatListView.isFastScrollAnimationRunning() && !chatListView.isMultiselect() && reportType < 0) {
if (pullingDownOffset == 0 && pullingDownDrawable != null) { if (pullingDownOffset == 0 && pullingDownDrawable != null) {
if (nextChannels != null && !nextChannels.isEmpty()) {
pullingDownDrawable.updateDialog(nextChannels.get(0));
} else if (isTopic) {
pullingDownDrawable.updateTopic();
} else {
pullingDownDrawable.updateDialog(); pullingDownDrawable.updateDialog();
} }
}
if (pullingDownBackAnimator != null) { if (pullingDownBackAnimator != null) {
pullingDownBackAnimator.removeAllListeners(); pullingDownBackAnimator.removeAllListeners();
pullingDownBackAnimator.cancel(); pullingDownBackAnimator.cancel();
@ -9040,7 +9057,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
tagSelector.setVisibility(View.VISIBLE); tagSelector.setVisibility(View.VISIBLE);
tagSelector.setHint(LocaleController.getString(tagSelector.getSelectedReactions().isEmpty() ? R.string.SavedTagReactionsSelectedAddHint : R.string.SavedTagReactionsSelectedEditHint)); tagSelector.setHint(LocaleController.getString(tagSelector.getSelectedReactions().isEmpty() ? R.string.SavedTagReactionsSelectedAddHint : R.string.SavedTagReactionsSelectedEditHint));
contentView.addView(tagSelector, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 92.5f, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 0, 0, 0)); contentView.addView(tagSelector, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 92.5f, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 0, 0, 0));
tagSelector.setMessage(null, null); tagSelector.setMessage(null, null, true);
tagSelector.setTranslationY(-dp(12)); tagSelector.setTranslationY(-dp(12));
tagSelector.setScaleY(.4f); tagSelector.setScaleY(.4f);
tagSelector.setScaleX(.4f); tagSelector.setScaleX(.4f);
@ -9686,14 +9703,22 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (pullingDownDrawable == null) { if (pullingDownDrawable == null) {
return; return;
} }
// if (getParentLayout().fragmentsStack.size() > 1) { if (isTopic) {
// BaseFragment previousFragment = getParentLayout().fragmentsStack.get(getParentLayout().fragmentsStack.size() - 2); if (pullingDownDrawable.getTopic() != null) {
// if (previousFragment instanceof ChatActivity) { addToPulledTopicsMyself();
// getParentLayout().fragmentsStack.remove(getParentLayout().fragmentsStack.size() - 2); addToPulledDialogs(currentChat, pullingDownDrawable.nextTopic, dialog_id, dialogFolderId, dialogFilterId);
// } Bundle bundle = new Bundle();
// } bundle.putInt("dialog_folder_id", pullingDownDrawable.dialogFolderId);
bundle.putInt("dialog_filter_id", pullingDownDrawable.dialogFilterId);
bundle.putBoolean("pulled", true);
ChatActivity chatActivity = ForumUtilities.getChatActivityForTopic(ChatActivity.this, -dialog_id, pullingDownDrawable.getTopic(), 0, bundle);
chatActivity.setPullingDownTransition(true);
replacingChatActivity = true;
presentFragment(chatActivity, true);
}
} else {
addToPulledDialogsMyself(); addToPulledDialogsMyself();
addToPulledDialogs(pullingDownDrawable.nextChat, pullingDownDrawable.nextDialogId, pullingDownDrawable.dialogFolderId, pullingDownDrawable.dialogFilterId); addToPulledDialogs(pullingDownDrawable.nextChat, null, pullingDownDrawable.nextDialogId, pullingDownDrawable.dialogFolderId, pullingDownDrawable.dialogFilterId);
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putLong("chat_id", pullingDownDrawable.getChatId()); bundle.putLong("chat_id", pullingDownDrawable.getChatId());
bundle.putInt("dialog_folder_id", pullingDownDrawable.dialogFolderId); bundle.putInt("dialog_folder_id", pullingDownDrawable.dialogFolderId);
@ -9702,24 +9727,41 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
SharedPreferences sharedPreferences = MessagesController.getNotificationsSettings(currentAccount); SharedPreferences sharedPreferences = MessagesController.getNotificationsSettings(currentAccount);
sharedPreferences.edit().remove("diditem" + pullingDownDrawable.nextDialogId).apply(); sharedPreferences.edit().remove("diditem" + pullingDownDrawable.nextDialogId).apply();
ChatActivity chatActivity = new ChatActivity(bundle); ChatActivity chatActivity = new ChatActivity(bundle);
if (nextChannels != null && nextChannels.size() > 1) {
chatActivity.setNextChannels(new ArrayList<>(nextChannels.subList(1, nextChannels.size())));
}
chatActivity.setPullingDownTransition(true); chatActivity.setPullingDownTransition(true);
replacingChatActivity = true; replacingChatActivity = true;
presentFragment(chatActivity, true); presentFragment(chatActivity, true);
} }
}
private ArrayList<TLRPC.Chat> nextChannels;
public void setNextChannels(ArrayList<TLRPC.Chat> channels) {
nextChannels = channels;
}
private void addToPulledDialogsMyself() { private void addToPulledDialogsMyself() {
if (getParentLayout() == null) { if (getParentLayout() == null) {
return; return;
} }
int stackIndex = getParentLayout().getFragmentStack().indexOf(this); int stackIndex = getParentLayout().getFragmentStack().indexOf(this);
BackButtonMenu.addToPulledDialogs(this, stackIndex, currentChat, currentUser, dialog_id, dialogFilterId, dialogFolderId); BackButtonMenu.addToPulledDialogs(this, stackIndex, currentChat, currentUser, null, dialog_id, dialogFilterId, dialogFolderId);
} }
private void addToPulledDialogs(TLRPC.Chat chat, long dialogId, int folderId, int filterId) { private void addToPulledDialogs(TLRPC.Chat chat, TLRPC.TL_forumTopic topic, long dialogId, int folderId, int filterId) {
if (getParentLayout() == null) { if (getParentLayout() == null) {
return; return;
} }
int stackIndex = getParentLayout().getFragmentStack().indexOf(this); int stackIndex = getParentLayout().getFragmentStack().indexOf(this);
BackButtonMenu.addToPulledDialogs(this, stackIndex, chat, null, dialogId, folderId, filterId); BackButtonMenu.addToPulledDialogs(this, stackIndex, chat, null, topic, dialogId, folderId, filterId);
}
private void addToPulledTopicsMyself() {
if (getParentLayout() == null) {
return;
}
int stackIndex = getParentLayout().getFragmentStack().indexOf(this);
BackButtonMenu.addToPulledDialogs(this, stackIndex, currentChat, currentUser, forumTopic, dialog_id, dialogFilterId, dialogFolderId);
} }
private void setPullingDownTransition(boolean fromPullingDownTransition) { private void setPullingDownTransition(boolean fromPullingDownTransition) {
@ -10478,7 +10520,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
pendingViewH = Math.max(0, pendingRequestsView.getHeight() + pendingRequestsDelegate.getViewEnterOffset() - AndroidUtilities.dp(4)); pendingViewH = Math.max(0, pendingRequestsView.getHeight() + pendingRequestsDelegate.getViewEnterOffset() - AndroidUtilities.dp(4));
} }
float oldPadding = chatListViewPaddingTop; float oldPadding = chatListViewPaddingTop;
chatListViewPaddingTop = AndroidUtilities.dp(4) + contentPaddingTop + topPanelViewH + pinnedViewH + pendingViewH; chatListViewPaddingTop = AndroidUtilities.dp(4) + contentPaddingTop + (paddingTopHeight = topPanelViewH + pinnedViewH + pendingViewH);
chatListViewPaddingTop += blurredViewTopOffset; chatListViewPaddingTop += blurredViewTopOffset;
chatListViewPaddingVisibleOffset = 0; chatListViewPaddingVisibleOffset = 0;
chatListViewPaddingTop += contentPanTranslation + bottomPanelTranslationY; chatListViewPaddingTop += contentPanTranslation + bottomPanelTranslationY;
@ -12031,7 +12073,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
chatAttachAlert.setMaxSelectedPhotos(1, false); chatAttachAlert.setMaxSelectedPhotos(1, false);
chatAttachAlert.setOpenWithFrontFaceCamera(true); chatAttachAlert.setOpenWithFrontFaceCamera(true);
chatAttachAlert.enableStickerMode(); chatAttachAlert.enableStickerMode(null);
chatAttachAlert.init(); chatAttachAlert.init();
chatAttachAlert.parentThemeDelegate = themeDelegate; chatAttachAlert.parentThemeDelegate = themeDelegate;
if (visibleDialog != null) { if (visibleDialog != null) {
@ -15515,12 +15557,18 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
MessageObject.SendAnimationData data = cell.getMessageObject().sendAnimationData; MessageObject.SendAnimationData data = cell.getMessageObject().sendAnimationData;
if (data != null) { if (data != null) {
canvas.save(); canvas.save();
final int actionBarBottom = actionBar.getVisibility() == VISIBLE ? (int) actionBar.getTranslationY() + actionBar.getMeasuredHeight() + (actionBarSearchTags != null ? actionBarSearchTags.getCurrentHeight() : 0) + (inPreviewMode && Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0) : 0;
canvas.clipRect(0, actionBarBottom + paddingTopHeight, getWidth(), getHeight());
ImageReceiver imageReceiver = cell.getPhotoImage(); ImageReceiver imageReceiver = cell.getPhotoImage();
canvas.translate(data.currentX, data.currentY); cell.getLocationInWindow(AndroidUtilities.pointTmp2);
int finalY = AndroidUtilities.pointTmp2[1];
finalY -= cell.getTranslationY() * (1.0f - data.progress);
finalY += chatActivityEnterView.topViewVisible() * AndroidUtilities.dp(48);
canvas.translate(data.currentX, AndroidUtilities.lerp(data.y, finalY + imageReceiver.getCenterY(), data.progress));
canvas.scale(data.currentScale, data.currentScale); canvas.scale(data.currentScale, data.currentScale);
canvas.translate(-imageReceiver.getCenterX(), -imageReceiver.getCenterY()); canvas.translate(-imageReceiver.getCenterX(), -imageReceiver.getCenterY());
cell.setTimeAlpha(data.timeAlpha); cell.setTimeAlpha(data.timeAlpha);
animateSendingViews.get(a).draw(canvas); cell.draw(canvas);
canvas.restore(); canvas.restore();
} }
} }
@ -18989,11 +19037,32 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
TLRPC.TL_inputStickerSetID inputStickerSet = new TLRPC.TL_inputStickerSetID(); TLRPC.TL_inputStickerSetID inputStickerSet = new TLRPC.TL_inputStickerSetID();
inputStickerSet.access_hash = set.access_hash; inputStickerSet.access_hash = set.access_hash;
inputStickerSet.id = set.id; inputStickerSet.id = set.id;
final boolean replacing = args.length > 4 ? (boolean) args[4] : false;
if (visibleDialog instanceof StickersAlert) {
StickersAlert existingAlert = (StickersAlert) visibleDialog;
if (existingAlert.stickerSet != null && existingAlert.stickerSet.set != null && existingAlert.stickerSet.set.id == set.id) {
existingAlert.updateStickerSet(((TLRPC.TL_messages_stickerSet) args[1]));
if (args.length > 2 && args[2] instanceof TLRPC.Document) {
TLRPC.Document stickerDocument = (TLRPC.Document) args[2];
if (args.length > 3 && args[3] instanceof String) {
stickerDocument.localThumbPath = (String) args[3];
}
BulletinFactory.of(existingAlert.container, resourceProvider).createEmojiBulletin(stickerDocument, LocaleController.formatString(replacing ? R.string.StickersStickerEditedInSetToast : R.string.StickersStickerAddedToSetToast, set.title)).setDuration(Bulletin.DURATION_LONG).show(true);
}
return;
}
}
StickersAlert alert = new StickersAlert(getParentActivity(), ChatActivity.this, inputStickerSet, null, chatActivityEnterView, themeDelegate); StickersAlert alert = new StickersAlert(getParentActivity(), ChatActivity.this, inputStickerSet, null, chatActivityEnterView, themeDelegate);
alert.setOnShowListener(dialog -> { alert.setOnShowListener(dialog -> {
if (args.length > 2 && args[2] instanceof TLRPC.Document) { if (args.length > 2 && args[2] instanceof TLRPC.Document) {
TLRPC.Document stickerDocument = (TLRPC.Document) args[2]; TLRPC.Document stickerDocument = (TLRPC.Document) args[2];
BulletinFactory.of((FrameLayout) alert.getContainerView(), resourceProvider).createEmojiBulletin(stickerDocument, LocaleController.formatString(R.string.StickersStickerAddedToSetToast, set.title)).setDuration(Bulletin.DURATION_LONG).show(); if (args.length > 3 && args[3] instanceof String) {
stickerDocument.localThumbPath = (String) args[3];
}
BulletinFactory.of(alert.container, resourceProvider).createEmojiBulletin(stickerDocument, LocaleController.formatString(replacing ? R.string.StickersStickerEditedInSetToast : R.string.StickersStickerAddedToSetToast, set.title)).setDuration(Bulletin.DURATION_LONG).show(true);
} }
}); });
showDialog(alert); showDialog(alert);
@ -19495,7 +19564,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
getMediaDataController().loadReplyMessagesForMessages(messArr, dialog_id, chatMode, 0, null, classGuid); getMediaDataController().loadReplyMessagesForMessages(messArr, dialog_id, chatMode, 0, null, classGuid);
} }
if (chatAdapter != null) { if (chatAdapter != null) {
chatAdapter.updateRowWithMessageObject(obj, false, false); ChatMessageCell cell = null;
for (int i = 0; i < chatListView.getChildCount(); ++i) {
View child = chatListView.getChildAt(i);
if (child instanceof ChatMessageCell && ((ChatMessageCell) child).getMessageObject() == obj) {
cell = (ChatMessageCell) child;
break;
}
}
chatAdapter.updateRowWithMessageObject(obj, animateSendingViews.contains(cell), false);
} }
if (chatLayoutManager != null) { if (chatLayoutManager != null) {
if (mediaUpdated && chatLayoutManager.findFirstVisibleItemPosition() == 0) { if (mediaUpdated && chatLayoutManager.findFirstVisibleItemPosition() == 0) {
@ -21563,8 +21640,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private int sponsoredMessagesPostsBetween; private int sponsoredMessagesPostsBetween;
private boolean sponsoredMessagesAdded; private boolean sponsoredMessagesAdded;
private Pattern sponsoredUrlPattern;
private void addSponsoredMessages(boolean animated) { private void addSponsoredMessages(boolean animated) {
if (sponsoredMessagesAdded || chatMode != 0 || !ChatObject.isChannel(currentChat) || !forwardEndReached[0] || getUserConfig().isPremium()) { if (sponsoredMessagesAdded || chatMode != 0 || !ChatObject.isChannel(currentChat) || !forwardEndReached[0] || getUserConfig().isPremium() && getMessagesController().isSponsoredDisabled()) {
return; return;
} }
MessagesController.SponsoredMessagesInfo res = getMessagesController().getSponsoredMessages(dialog_id); MessagesController.SponsoredMessagesInfo res = getMessagesController().getSponsoredMessages(dialog_id);
@ -21574,12 +21652,36 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
for (int i = 0; i < res.messages.size(); i++) { for (int i = 0; i < res.messages.size(); i++) {
MessageObject messageObject = res.messages.get(i); MessageObject messageObject = res.messages.get(i);
messageObject.resetLayout(); messageObject.resetLayout();
long dialogId = MessageObject.getPeerId(messageObject.messageOwner.from_id); if (messageObject.sponsoredUrl != null) {
int messageId = 0; try {
if (messageObject.sponsoredChannelPost != 0) { if (sponsoredUrlPattern == null) {
messageId = messageObject.sponsoredChannelPost; sponsoredUrlPattern = Pattern.compile("https://t\\.me/(\\w+)(?:/(\\d+))?");
}
Matcher matcher = sponsoredUrlPattern.matcher(messageObject.sponsoredUrl);
if (matcher.matches()) {
String username = matcher.group(1);
int postId = 0;
try {
postId = matcher.groupCount() >= 2 ? Integer.parseInt(matcher.group(2)) : 0;
} catch (Exception e2) {
FileLog.e(e2);
}
TLObject obj = getMessagesController().getUserOrChat(username);
long did;
if (obj instanceof TLRPC.User) {
did = ((TLRPC.User) obj).id;
} else if (obj instanceof TLRPC.Chat) {
did = -((TLRPC.Chat) obj).id;
} else {
continue;
}
if (postId < 0) continue;
getMessagesController().ensureMessagesLoaded(did, postId, null);
}
} catch (Exception e) {
FileLog.e(e);
}
} }
getMessagesController().ensureMessagesLoaded(dialogId, messageId, null);
} }
sponsoredMessagesAdded = true; sponsoredMessagesAdded = true;
sponsoredMessagesPostsBetween = res.posts_between != null ? res.posts_between : 0; sponsoredMessagesPostsBetween = res.posts_between != null ? res.posts_between : 0;
@ -22791,7 +22893,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (editingMessageObject == obj) { if (editingMessageObject == obj) {
hideFieldPanel(true); hideFieldPanel(true);
} }
int index = chatAdapter.isFiltered && filteredMessagesDict != null ? chatAdapter.filteredMessages.indexOf(filteredMessagesDict.get(mid)) : messages.indexOf(obj); int index = chatAdapter != null && chatAdapter.isFiltered && filteredMessagesDict != null ? chatAdapter.filteredMessages.indexOf(filteredMessagesDict.get(mid)) : messages.indexOf(obj);
if (index != -1) { if (index != -1) {
if (obj.scheduled) { if (obj.scheduled) {
scheduledMessagesCount--; scheduledMessagesCount--;
@ -22801,7 +22903,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
updatedSelected = true; updatedSelected = true;
addToSelectedMessages(obj, false, updatedSelectedLast = (a == size - 1)); addToSelectedMessages(obj, false, updatedSelectedLast = (a == size - 1));
} }
MessageObject removed = chatAdapter.getMessages().remove(index); MessageObject removed = chatAdapter != null && chatAdapter.isFiltered && filteredMessagesDict != null ? chatAdapter.filteredMessages.remove(index) : messages.remove(index);
if (chatAdapter != null) { if (chatAdapter != null) {
if (chatAdapter.isFiltered) { if (chatAdapter.isFiltered) {
int mindex = messages.indexOf(obj); int mindex = messages.indexOf(obj);
@ -22862,7 +22964,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (filteredMessagesByDays != null) { if (filteredMessagesByDays != null) {
dayArr = filteredMessagesByDays.get(obj.dateKeyInt); dayArr = filteredMessagesByDays.get(obj.dateKeyInt);
if (dayArr != null) { if (dayArr != null) {
MessageObject mobj = chatAdapter.isFiltered ? filteredMessagesDict.get(obj.getId()) : obj; MessageObject mobj = chatAdapter != null && chatAdapter.isFiltered ? filteredMessagesDict.get(obj.getId()) : obj;
dayArr.remove(mobj); dayArr.remove(mobj);
if (dayArr.isEmpty()) { if (dayArr.isEmpty()) {
filteredMessagesByDays.remove(obj.dateKeyInt); filteredMessagesByDays.remove(obj.dateKeyInt);
@ -22914,7 +23016,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
MessageObject messageObject = groupedMessages.messages.get(groupedMessages.messages.size() - 1); MessageObject messageObject = groupedMessages.messages.get(groupedMessages.messages.size() - 1);
int index = chatAdapter.getMessages().indexOf(messageObject); int index = chatAdapter.getMessages().indexOf(messageObject);
if (index >= 0) { if (index >= 0) {
if (chatAdapter != null) { if (chatAdapter != null && !chatAdapter.isFrozen) {
chatAdapter.notifyItemRangeChanged(index + chatAdapter.messagesStartRow, newGroupsSizes.get(groupedMessages.groupId)); chatAdapter.notifyItemRangeChanged(index + chatAdapter.messagesStartRow, newGroupsSizes.get(groupedMessages.groupId));
} }
} }
@ -22963,7 +23065,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
avatarContainer.setTitle(LocaleController.formatPluralString("PinnedMessagesCount", getPinnedMessagesCount())); avatarContainer.setTitle(LocaleController.formatPluralString("PinnedMessagesCount", getPinnedMessagesCount()));
} }
} }
if (chatAdapter != null) { if (chatAdapter != null && !chatAdapter.isFrozen) {
int prevHintRow = chatAdapter.hintRow; int prevHintRow = chatAdapter.hintRow;
int prevLoadingUpRow = chatAdapter.loadingUpRow; int prevLoadingUpRow = chatAdapter.loadingUpRow;
int prevLoadingDownRow = chatAdapter.loadingDownRow; int prevLoadingDownRow = chatAdapter.loadingDownRow;
@ -23300,6 +23402,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
CharSequence text; CharSequence text;
if (!results.solution_entities.isEmpty()) { if (!results.solution_entities.isEmpty()) {
text = new SpannableStringBuilder(results.solution); text = new SpannableStringBuilder(results.solution);
text = Emoji.replaceEmoji(text, Theme.chat_msgBotButtonPaint.getFontMetricsInt(), AndroidUtilities.dp(13), false);
text = MessageObject.replaceAnimatedEmoji(text, results.solution_entities, Theme.chat_msgBotButtonPaint.getFontMetricsInt());
MessageObject.addEntitiesToText(text, results.solution_entities, false, true, true, false); MessageObject.addEntitiesToText(text, results.solution_entities, false, true, true, false);
} else { } else {
text = results.solution; text = results.solution;
@ -24884,7 +24988,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
pinnedText = String.format("%s - %s", pinnedMessageObject.getMusicAuthor(), pinnedMessageObject.getMusicTitle()); pinnedText = String.format("%s - %s", pinnedMessageObject.getMusicAuthor(), pinnedMessageObject.getMusicTitle());
} else if (pinnedMessageObject.type == MessageObject.TYPE_POLL) { } else if (pinnedMessageObject.type == MessageObject.TYPE_POLL) {
TLRPC.TL_messageMediaPoll poll = (TLRPC.TL_messageMediaPoll) pinnedMessageObject.messageOwner.media; TLRPC.TL_messageMediaPoll poll = (TLRPC.TL_messageMediaPoll) pinnedMessageObject.messageOwner.media;
String mess = poll.poll.question; String mess = poll.poll.question.text;
if (mess.length() > 150) { if (mess.length() > 150) {
mess = mess.substring(0, 150); mess = mess.substring(0, 150);
} }
@ -25332,7 +25436,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
getMessagesController().getTranslateController().isDialogTranslatable(getDialogId()) && !getMessagesController().getTranslateController().isTranslateDialogHidden(getDialogId()) : getMessagesController().getTranslateController().isDialogTranslatable(getDialogId()) && !getMessagesController().getTranslateController().isTranslateDialogHidden(getDialogId()) :
!getMessagesController().premiumFeaturesBlocked() && preferences.getInt("dialog_show_translate_count" + did, 5) <= 0 !getMessagesController().premiumFeaturesBlocked() && preferences.getInt("dialog_show_translate_count" + did, 5) <= 0
); );
boolean showBizBot = getUserConfig().isPremium() && preferences.getLong("dialog_botid" + did, 0) != 0; boolean showBizBot = currentEncryptedChat == null && getUserConfig().isPremium() && preferences.getLong("dialog_botid" + did, 0) != 0;
if (showRestartTopic) { if (showRestartTopic) {
shownRestartTopic = true; shownRestartTopic = true;
} }
@ -26279,6 +26383,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
CharSequence message = ChatActivityEnterView.applyMessageEntities(entities, resolvedChatLink.message, chatActivityEnterView.getEditField().getPaint().getFontMetricsInt()); CharSequence message = ChatActivityEnterView.applyMessageEntities(entities, resolvedChatLink.message, chatActivityEnterView.getEditField().getPaint().getFontMetricsInt());
if (message != null && message.length() > 0 && message.charAt(0) == '@') {
message = TextUtils.concat(" ", message);
}
chatActivityEnterView.setFieldText(message, true, true); chatActivityEnterView.setFieldText(message, true, true);
@ -26635,19 +26742,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
} }
private void createDeleteMessagesAlert(final MessageObject finalSelectedObject, final MessageObject.GroupedMessages selectedGroup) { private void createDeleteMessagesAlert(final MessageObject finalSelectedObject, final MessageObject.GroupedMessages finalSelectedGroup) {
createDeleteMessagesAlert(finalSelectedObject, selectedGroup, 1); createDeleteMessagesAlert(finalSelectedObject, finalSelectedGroup, false);
} }
private void createDeleteMessagesAlert(final MessageObject finalSelectedObject, final MessageObject.GroupedMessages finalSelectedGroup, int loadParticipant) { private void createDeleteMessagesAlert(final MessageObject finalSelectedObject, final MessageObject.GroupedMessages finalSelectedGroup, boolean hideDimAfter) {
createDeleteMessagesAlert(finalSelectedObject, finalSelectedGroup, loadParticipant, false);
}
private void createDeleteMessagesAlert(final MessageObject finalSelectedObject, final MessageObject.GroupedMessages finalSelectedGroup, int loadParticipant, boolean hideDimAfter) {
if (finalSelectedObject == null && (selectedMessagesIds[0].size() + selectedMessagesIds[1].size()) == 0) { if (finalSelectedObject == null && (selectedMessagesIds[0].size() + selectedMessagesIds[1].size()) == 0) {
return; return;
} }
AlertsCreator.createDeleteMessagesAlert(this, currentUser, currentChat, currentEncryptedChat, chatInfo, mergeDialogId, finalSelectedObject, selectedMessagesIds, finalSelectedGroup, (int) getTopicId(), chatMode, loadParticipant, () -> { AlertsCreator.createDeleteMessagesAlert(this, currentUser, currentChat, currentEncryptedChat, chatInfo, mergeDialogId, finalSelectedObject, selectedMessagesIds, finalSelectedGroup, (int) getTopicId(), chatMode, null, () -> {
hideActionMode(); hideActionMode();
updatePinnedMessageView(true); updatePinnedMessageView(true);
}, hideDimAfter ? () -> dimBehindView(false) : null, themeDelegate); }, hideDimAfter ? () -> dimBehindView(false) : null, themeDelegate);
@ -26964,9 +27067,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
try { try {
TLRPC.Poll poll = ((TLRPC.TL_messageMediaPoll) selectedObject.messageOwner.media).poll; TLRPC.Poll poll = ((TLRPC.TL_messageMediaPoll) selectedObject.messageOwner.media).poll;
StringBuilder pollText = new StringBuilder(); StringBuilder pollText = new StringBuilder();
pollText = new StringBuilder(poll.question).append("\n"); pollText = new StringBuilder(poll.question.text).append("\n");
for (TLRPC.TL_pollAnswer answer : poll.answers) for (TLRPC.PollAnswer answer : poll.answers)
pollText.append("\n\uD83D\uDD18 ").append(answer.text); pollText.append("\n\uD83D\uDD18 ").append(answer.text == null ? "" : answer.text.text);
messageTextToTranslate = pollText.toString(); messageTextToTranslate = pollText.toString();
} catch (Exception e) { } catch (Exception e) {
} }
@ -27251,7 +27354,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
icons.add(R.drawable.msg_sticker); icons.add(R.drawable.msg_sticker);
TLRPC.Document document = selectedObject.getDocument(); TLRPC.Document document = selectedObject.getDocument();
if (!getMediaDataController().isStickerInFavorites(document)) { if (!getMediaDataController().isStickerInFavorites(document)) {
if (getMediaDataController().canAddStickerToFavorites() && MessageObject.isStickerHasSet(document)) { if (getMediaDataController().canAddStickerToFavorites()) {
items.add(LocaleController.getString("AddToFavorites", R.string.AddToFavorites)); items.add(LocaleController.getString("AddToFavorites", R.string.AddToFavorites));
options.add(OPTION_ADD_STICKER_TO_FAVORITES); options.add(OPTION_ADD_STICKER_TO_FAVORITES);
icons.add(R.drawable.msg_fave); icons.add(R.drawable.msg_fave);
@ -27286,7 +27389,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} else if (type == 9) { } else if (type == 9) {
TLRPC.Document document = selectedObject.getDocument(); TLRPC.Document document = selectedObject.getDocument();
if (!getMediaDataController().isStickerInFavorites(document)) { if (!getMediaDataController().isStickerInFavorites(document)) {
if (MessageObject.isStickerHasSet(document)) { if (getMediaDataController().canAddStickerToFavorites()) {
items.add(LocaleController.getString("AddToFavorites", R.string.AddToFavorites)); items.add(LocaleController.getString("AddToFavorites", R.string.AddToFavorites));
options.add(OPTION_ADD_STICKER_TO_FAVORITES); options.add(OPTION_ADD_STICKER_TO_FAVORITES);
icons.add(R.drawable.msg_fave); icons.add(R.drawable.msg_fave);
@ -27469,7 +27572,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
boolean showMessageSeen = !isReactionsViewAvailable && !isInScheduleMode() && currentChat != null && message.isOutOwner() && message.isSent() && !message.isEditing() && !message.isSending() && !message.isSendError() && !message.isContentUnread() && !message.isUnread() && (ConnectionsManager.getInstance(currentAccount).getCurrentTime() - message.messageOwner.date < getMessagesController().chatReadMarkExpirePeriod) && (ChatObject.isMegagroup(currentChat) || !ChatObject.isChannel(currentChat)) && chatInfo != null && chatInfo.participants_count <= getMessagesController().chatReadMarkSizeThreshold && !(message.messageOwner.action instanceof TLRPC.TL_messageActionChatJoinedByRequest) && (v instanceof ChatMessageCell); boolean showMessageSeen = !isReactionsViewAvailable && !isInScheduleMode() && currentChat != null && message.isOutOwner() && message.isSent() && !message.isEditing() && !message.isSending() && !message.isSendError() && !message.isContentUnread() && !message.isUnread() && (ConnectionsManager.getInstance(currentAccount).getCurrentTime() - message.messageOwner.date < getMessagesController().chatReadMarkExpirePeriod) && (ChatObject.isMegagroup(currentChat) || !ChatObject.isChannel(currentChat)) && chatInfo != null && chatInfo.participants_count <= getMessagesController().chatReadMarkSizeThreshold && !(message.messageOwner.action instanceof TLRPC.TL_messageActionChatJoinedByRequest) && (v instanceof ChatMessageCell);
boolean showPrivateMessageSeen = !isReactionsViewAvailable && currentChat == null && currentEncryptedChat == null && (currentUser != null && !UserObject.isUserSelf(currentUser) && !UserObject.isReplyUser(currentUser) && !UserObject.isAnonymous(currentUser) && !currentUser.bot && !UserObject.isService(currentUser.id)) && (userInfo == null || !userInfo.read_dates_private) && !isInScheduleMode() && message.isOutOwner() && message.isSent() && !message.isEditing() && !message.isSending() && !message.isSendError() && !message.isContentUnread() && !message.isUnread() && (ConnectionsManager.getInstance(currentAccount).getCurrentTime() - message.messageOwner.date < getMessagesController().pmReadDateExpirePeriod) && !(message.messageOwner.action instanceof TLRPC.TL_messageActionChatJoinedByRequest) && (v instanceof ChatMessageCell); boolean showPrivateMessageSeen = !isReactionsViewAvailable && currentChat == null && currentEncryptedChat == null && (currentUser != null && !UserObject.isUserSelf(currentUser) && !UserObject.isReplyUser(currentUser) && !UserObject.isAnonymous(currentUser) && !currentUser.bot && !UserObject.isService(currentUser.id)) && (userInfo == null || !userInfo.read_dates_private) && !isInScheduleMode() && message.isOutOwner() && message.isSent() && !message.isEditing() && !message.isSending() && !message.isSendError() && !message.isContentUnread() && !message.isUnread() && (ConnectionsManager.getInstance(currentAccount).getCurrentTime() - message.messageOwner.date < getMessagesController().pmReadDateExpirePeriod) && !(message.messageOwner.action instanceof TLRPC.TL_messageActionChatJoinedByRequest) && (v instanceof ChatMessageCell);
boolean showSponsorInfo = selectedObject != null && selectedObject.isSponsored() && (selectedObject.sponsoredInfo != null || selectedObject.sponsoredAdditionalInfo != null || selectedObject.sponsoredWebPage != null || selectedObject.sponsoredBotApp != null); boolean showSponsorInfo = selectedObject != null && selectedObject.isSponsored() && (selectedObject.sponsoredInfo != null || selectedObject.sponsoredAdditionalInfo != null || selectedObject.sponsoredUrl != null && !selectedObject.sponsoredUrl.startsWith("https://" + getMessagesController().linkPrefix));
if (chatMode == MODE_SAVED) { if (chatMode == MODE_SAVED) {
showMessageSeen = false; showMessageSeen = false;
} }
@ -27953,7 +28056,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
if (selectedObject != null && selectedObject.isSponsored()) { if (selectedObject != null && selectedObject.isSponsored()) {
if (selectedObject.sponsoredInfo != null || selectedObject.sponsoredAdditionalInfo != null || selectedObject.sponsoredWebPage != null) { if (selectedObject.sponsoredInfo != null || selectedObject.sponsoredAdditionalInfo != null || selectedObject.sponsoredUrl != null && !selectedObject.sponsoredUrl.startsWith("https://" + getMessagesController().linkPrefix)) {
LinearLayout linearLayout = new LinearLayout(getParentActivity()); LinearLayout linearLayout = new LinearLayout(getParentActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setOrientation(LinearLayout.VERTICAL);
@ -27968,13 +28071,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
ArrayList<View> sections = new ArrayList<>(); ArrayList<View> sections = new ArrayList<>();
if (selectedObject.sponsoredWebPage != null) { if (selectedObject.sponsoredUrl != null && !selectedObject.sponsoredUrl.startsWith(getMessagesController().linkPrefix)) {
TextView textView = new TextView(getParentActivity()); TextView textView = new TextView(getParentActivity());
textView.setTextColor(getThemedColor(Theme.key_chat_messageLinkIn)); textView.setTextColor(getThemedColor(Theme.key_chat_messageLinkIn));
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setPadding(AndroidUtilities.dp(18), AndroidUtilities.dp(10), AndroidUtilities.dp(18), AndroidUtilities.dp(10)); textView.setPadding(AndroidUtilities.dp(18), AndroidUtilities.dp(10), AndroidUtilities.dp(18), AndroidUtilities.dp(10));
textView.setMaxWidth(AndroidUtilities.dp(300)); textView.setMaxWidth(AndroidUtilities.dp(300));
Uri uri = Uri.parse(selectedObject.sponsoredWebPage.url); Uri uri = Uri.parse(selectedObject.sponsoredUrl);
textView.setText(Browser.replaceHostname(uri, IDN.toUnicode(uri.getHost(), IDN.ALLOW_UNASSIGNED))); textView.setText(Browser.replaceHostname(uri, IDN.toUnicode(uri.getHost(), IDN.ALLOW_UNASSIGNED)));
textView.setBackground(Theme.createRadSelectorDrawable(getThemedColor(Theme.key_dialogButtonSelector), 0, selectedObject.sponsoredAdditionalInfo == null ? 6 : 0)); textView.setBackground(Theme.createRadSelectorDrawable(getThemedColor(Theme.key_dialogButtonSelector), 0, selectedObject.sponsoredAdditionalInfo == null ? 6 : 0));
textView.setOnClickListener(e -> { textView.setOnClickListener(e -> {
@ -27982,13 +28085,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
return; return;
} }
logSponsoredClicked(selectedObject); logSponsoredClicked(selectedObject);
Browser.openUrl(getContext(), selectedObject.sponsoredWebPage.url, true, false); Browser.openUrl(getContext(), selectedObject.sponsoredUrl, true, false);
}); });
textView.setOnLongClickListener(e -> { textView.setOnLongClickListener(e -> {
if (selectedObject == null) { if (selectedObject == null) {
return false; return false;
} }
if (AndroidUtilities.addToClipboard(selectedObject.sponsoredWebPage.url)) { if (AndroidUtilities.addToClipboard(selectedObject.sponsoredUrl)) {
BulletinFactory.of(Bulletin.BulletinWindow.make(getParentActivity()), themeDelegate).createCopyLinkBulletin().show(); BulletinFactory.of(Bulletin.BulletinWindow.make(getParentActivity()), themeDelegate).createCopyLinkBulletin().show();
} }
return true; return true;
@ -28325,7 +28428,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (group != null) { if (group != null) {
messageWithReactions = group.findPrimaryMessageObject(); messageWithReactions = group.findPrimaryMessageObject();
} }
reactionsLayout.setMessage(messageWithReactions, chatInfo); reactionsLayout.setMessage(messageWithReactions, chatInfo, true);
reactionsLayout.setTransitionProgress(0); reactionsLayout.setTransitionProgress(0);
if (popupLayout.getSwipeBack() != null) { if (popupLayout.getSwipeBack() != null) {
@ -28349,7 +28452,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
} }
boolean showNoForwards = noforwards && message.messageOwner.action == null && message.isSent() && !message.isEditing() && chatMode != MODE_SCHEDULED && chatMode != MODE_SAVED; boolean showNoForwards = (getMessagesController().isChatNoForwards(currentChat) || message.messageOwner.noforwards && currentUser != null && currentUser.bot) && message.messageOwner.action == null && message.isSent() && !message.isEditing() && chatMode != MODE_SCHEDULED && chatMode != MODE_SAVED;
scrimPopupContainerLayout.addView(popupLayout, LayoutHelper.createLinearRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT, isReactionsAvailable ? 16 : 0, 0, isReactionsAvailable ? 36 : 0, 0)); scrimPopupContainerLayout.addView(popupLayout, LayoutHelper.createLinearRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT, isReactionsAvailable ? 16 : 0, 0, isReactionsAvailable ? 36 : 0, 0));
scrimPopupContainerLayout.setPopupWindowLayout(popupLayout); scrimPopupContainerLayout.setPopupWindowLayout(popupLayout);
if (showNoForwards) { if (showNoForwards) {
@ -29254,7 +29357,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
return; return;
} }
preserveDim = true; preserveDim = true;
createDeleteMessagesAlert(selectedObject, selectedObjectGroup, 1,true); createDeleteMessagesAlert(selectedObject, selectedObjectGroup, true);
break; break;
} }
case OPTION_FORWARD: { case OPTION_FORWARD: {
@ -29891,8 +29994,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
break; break;
} }
case OPTION_HIDE_SPONSORED_MESSAGE: { case OPTION_HIDE_SPONSORED_MESSAGE: {
MessageObject message = selectedObject; hideAds();
showDialog(new PremiumFeatureBottomSheet(ChatActivity.this, PremiumPreviewFragment.PREMIUM_FEATURE_ADS, true));
break; break;
} }
case OPTION_ABOUT_REVENUE_SHARING_ADS: { case OPTION_ABOUT_REVENUE_SHARING_ADS: {
@ -29971,6 +30073,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
BulletinFactory.of(ChatActivity.this) BulletinFactory.of(ChatActivity.this)
.createAdReportedBulletin(LocaleController.getString(R.string.AdHidden)) .createAdReportedBulletin(LocaleController.getString(R.string.AdHidden))
.show(); .show();
getMessagesController().disableAds(false);
removeFromSponsored(message); removeFromSponsored(message);
removeMessageWithThanos(message); removeMessageWithThanos(message);
}, 200); }, 200);
@ -29996,7 +30099,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
break; break;
} }
case OPTION_REMOVE_ADS: { case OPTION_REMOVE_ADS: {
showDialog(new PremiumFeatureBottomSheet(ChatActivity.this, PremiumPreviewFragment.PREMIUM_FEATURE_ADS, true)); hideAds();
break; break;
} }
case OPTION_SPEED_PROMO: { case OPTION_SPEED_PROMO: {
@ -30015,6 +30118,19 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
closeMenu(!preserveDim); closeMenu(!preserveDim);
} }
private void hideAds() {
if (getUserConfig().isPremium()) {
BulletinFactory.of(ChatActivity.this)
.createAdReportedBulletin(LocaleController.getString(R.string.AdHidden))
.show();
getMessagesController().disableAds(true);
removeFromSponsored(selectedObject);
removeMessageWithThanos(selectedObject);
} else {
showDialog(new PremiumFeatureBottomSheet(ChatActivity.this, PremiumPreviewFragment.PREMIUM_FEATURE_ADS, true));
}
}
@Override @Override
public boolean didSelectDialogs(DialogsActivity fragment, ArrayList<MessagesStorage.TopicKey> dids, CharSequence message, boolean param, TopicsFragment topicsFragment) { public boolean didSelectDialogs(DialogsActivity fragment, ArrayList<MessagesStorage.TopicKey> dids, CharSequence message, boolean param, TopicsFragment topicsFragment) {
if ((messagePreviewParams == null && (!fragment.isQuote || replyingMessageObject == null) || fragment.isQuote && replyingMessageObject == null) && forwardingMessage == null && selectedMessagesIds[0].size() == 0 && selectedMessagesIds[1].size() == 0) { if ((messagePreviewParams == null && (!fragment.isQuote || replyingMessageObject == null) || fragment.isQuote && replyingMessageObject == null) && forwardingMessage == null && selectedMessagesIds[0].size() == 0 && selectedMessagesIds[1].size() == 0) {
@ -32642,31 +32758,28 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
return object.currentX; return object.currentX;
} }
}; };
Property<MessageObject.SendAnimationData, Float> param3 = new AnimationProperties.FloatProperty<MessageObject.SendAnimationData>("p3") { AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(
ObjectAnimator.ofFloat(sendAnimationData, param1, scale, 1.0f),
ObjectAnimator.ofFloat(sendAnimationData, new AnimationProperties.FloatProperty<MessageObject.SendAnimationData>("progress") {
@Override @Override
public void setValue(MessageObject.SendAnimationData object, float value) { public void setValue(MessageObject.SendAnimationData object, float value) {
object.currentY = value; object.progress = value;
if (fragmentView != null) { if (fragmentView != null) {
fragmentView.invalidate(); fragmentView.invalidate();
} }
} }
@Override @Override
public Float get(MessageObject.SendAnimationData object) { public Float get(MessageObject.SendAnimationData object) {
return object.currentY; return object.progress;
} }
}; }, 0, 1)
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(
ObjectAnimator.ofFloat(sendAnimationData, param1, scale, 1.0f),
ObjectAnimator.ofFloat(sendAnimationData, param3, sendAnimationData.y, position[1] + imageReceiver.getCenterY())
); );
animatorSet.setInterpolator(ChatListItemAnimator.DEFAULT_INTERPOLATOR);
ObjectAnimator o = ObjectAnimator.ofFloat(sendAnimationData, param2, sendAnimationData.x, position[0] + imageReceiver.getCenterX()); ObjectAnimator o = ObjectAnimator.ofFloat(sendAnimationData, param2, sendAnimationData.x, position[0] + imageReceiver.getCenterX());
o.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT);
allAnimators.playTogether(o, animatorSet); allAnimators.playTogether(o, animatorSet);
allAnimators.setDuration(ChatListItemAnimator.DEFAULT_DURATION); allAnimators.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT);
allAnimators.setDuration(460);
allAnimators.addListener(new AnimatorListenerAdapter() { allAnimators.addListener(new AnimatorListenerAdapter() {
@Override @Override
@ -32998,6 +33111,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
@Override @Override
public void notifyItemChanged(int position) { public void notifyItemChanged(int position) {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("notify item changed " + position);
}
if (!fragmentBeginToShow) { if (!fragmentBeginToShow) {
chatListView.setItemAnimator(null); chatListView.setItemAnimator(null);
} else if (chatListView.getItemAnimator() != chatListItemAnimator) { } else if (chatListView.getItemAnimator() != chatListItemAnimator) {
@ -33659,8 +33775,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
@Override @Override
public void didPressSponsoredClose() { public void didPressSponsoredClose(ChatMessageCell cell) {
showDialog(new PremiumFeatureBottomSheet(ChatActivity.this, PremiumPreviewFragment.PREMIUM_FEATURE_ADS, true)); selectedObject = cell.getMessageObject();
hideAds();
} }
@Override @Override
@ -33845,7 +33962,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
private void openProfile(TLRPC.User user, boolean expandPhoto) { private void openProfile(TLRPC.User user, boolean expandPhoto) {
if (user != null && user.id != getUserConfig().getClientUserId()) { if (user != null) {
if (user.photo == null || user.photo instanceof TLRPC.TL_userProfilePhotoEmpty) { if (user.photo == null || user.photo instanceof TLRPC.TL_userProfilePhotoEmpty) {
expandPhoto = false; expandPhoto = false;
} }
@ -33887,7 +34004,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (avatarContainer != null && postId == 0) { if (avatarContainer != null && postId == 0) {
avatarContainer.openProfile(false); avatarContainer.openProfile(false);
} else { } else {
scrollToMessageId(postId, cell.getMessageObject().getId(), true, 0, true, 0); scrollToMessageId(postId, cell.getMessageObject().getId(), true, 0, false, 0);
} }
} else if (currentChat == null || chat.id != currentChat.id || isThreadChat()) { } else if (currentChat == null || chat.id != currentChat.id || isThreadChat()) {
Bundle args = new Bundle(); Bundle args = new Bundle();
@ -34247,7 +34364,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
@Override @Override
public void didPressVoteButtons(ChatMessageCell cell, ArrayList<TLRPC.TL_pollAnswer> buttons, int showCount, int x, int y) { public void didPressVoteButtons(ChatMessageCell cell, ArrayList<TLRPC.PollAnswer> buttons, int showCount, int x, int y) {
if (showCount >= 0 || buttons.isEmpty()) { if (showCount >= 0 || buttons.isEmpty()) {
if (getParentActivity() == null) { if (getParentActivity() == null) {
return; return;
@ -34920,111 +35037,98 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
args.putBoolean("addContact", true); args.putBoolean("addContact", true);
presentFragment(new ContactAddActivity(args)); presentFragment(new ContactAddActivity(args));
} }
} else if (type == ChatMessageCell.INSTANT_BUTTON_TYPE_STICKER_SET || type == ChatMessageCell.INSTANT_BUTTON_TYPE_EMOJI_SET) {
final boolean emoji = type == ChatMessageCell.INSTANT_BUTTON_TYPE_EMOJI_SET;
TLRPC.WebPage webPage = null;
if (webPage == null && messageObject.messageOwner != null && messageObject.messageOwner.media != null) {
webPage = messageObject.messageOwner.media.webpage;
}
if (webPage == null || webPage.url == null) return;
Pattern pattern = Pattern.compile("^https?\\:\\/\\/t\\.me\\/add(?:emoji|stickers)\\/(.+)$");
Matcher m = pattern.matcher(webPage.url);
if (progressDialogCurrent != null) {
progressDialogCurrent.cancel(true);
}
progressDialogCurrent = cell == null || cell.getMessageObject() == null ? null : new Browser.Progress() {
@Override
public void init() {
progressDialogAtMessageId = cell.getMessageObject().getId();
progressDialogAtMessageType = PROGRESS_INSTANT;
progressDialogLinkSpan = null;
cell.invalidate();
}
@Override
public void end(boolean replaced) {
if (!replaced) {
AndroidUtilities.runOnUIThread(ChatActivity.this::resetProgressDialogLoading, 250);
}
}
};
if (m.matches() && m.groupCount() > 1 && m.group(1) != null) {
String setname = m.group(1);
TLRPC.TL_messages_stickerSet set = MediaDataController.getInstance(currentAccount).getStickerSetByName(setname);
if (set == null) {
progressDialogCurrent.init();
TLRPC.TL_messages_getStickerSet req = new TLRPC.TL_messages_getStickerSet();
TLRPC.TL_inputStickerSetShortName input = new TLRPC.TL_inputStickerSetShortName();
input.short_name = setname;
req.stickerset = input;
int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (res, err) -> AndroidUtilities.runOnUIThread(() -> {
progressDialogCurrent.end();
if (res instanceof TLRPC.TL_messages_stickerSet) {
MediaDataController.getInstance(currentAccount).putStickerSet((TLRPC.TL_messages_stickerSet) res, false);
TLRPC.TL_inputStickerSetID inputStickerSet = new TLRPC.TL_inputStickerSetID();
inputStickerSet.access_hash = ((TLRPC.TL_messages_stickerSet) res).set.access_hash;
inputStickerSet.id = ((TLRPC.TL_messages_stickerSet) res).set.id;
if (emoji) {
ArrayList<TLRPC.InputStickerSet> inputSets = new ArrayList<>(1);
inputSets.add(inputStickerSet);
EmojiPacksAlert alert = new EmojiPacksAlert(ChatActivity.this, getParentActivity(), themeDelegate, inputSets);
alert.setCalcMandatoryInsets(isKeyboardVisible());
showDialog(alert);
} else {
StickersAlert alert = new StickersAlert(getParentActivity(), ChatActivity.this, inputStickerSet, null, chatActivityEnterView, themeDelegate);
alert.setCalcMandatoryInsets(isKeyboardVisible());
showDialog(alert);
}
} else {
BulletinFactory.of(ChatActivity.this).createSimpleBulletin(R.raw.error, getString(emoji ? R.string.AddEmojiNotFound : R.string.AddStickersNotFound)).show(true);
}
}));
progressDialogCurrent.onCancel(() -> ConnectionsManager.getInstance(currentAccount).cancelRequest(reqId, true));
return;
}
}
Browser.openUrl(getParentActivity(), Uri.parse(webPage.url), true, true, false, progressDialogCurrent);
} else { } else {
if (messageObject.isSponsored()) { if (messageObject.isSponsored()) {
logSponsoredClicked(messageObject); logSponsoredClicked(messageObject);
Bundle args = new Bundle(); Bundle args = new Bundle();
if (messageObject.sponsoredBotApp != null) { if (messageObject.sponsoredUrl != null) {
TLRPC.TL_messages_getBotApp getBotApp = new TLRPC.TL_messages_getBotApp(); if (progressDialogCurrent != null) {
TLRPC.TL_inputBotAppShortName app = new TLRPC.TL_inputBotAppShortName(); progressDialogCurrent.cancel(true);
if (messageObject.messageOwner == null || messageObject.messageOwner.from_id == null) {
return;
} }
TLRPC.User bot = MessagesController.getInstance(currentAccount).getUser(messageObject.messageOwner.from_id.user_id); progressDialogCurrent = cell == null || cell.getMessageObject() == null ? null : new Browser.Progress() {
if (bot == null) { @Override
return; public void init() {
progressDialogAtMessageId = cell.getMessageObject().getId();
progressDialogAtMessageType = PROGRESS_INSTANT;
progressDialogLinkSpan = null;
cell.invalidate();
}
@Override
public void end(boolean replaced) {
if (!replaced) {
AndroidUtilities.runOnUIThread(ChatActivity.this::resetProgressDialogLoading, 250);
} }
app.bot_id = MessagesController.getInstance(currentAccount).getInputUser(bot);
app.short_name = messageObject.sponsoredBotApp.short_name;
getBotApp.app = app;
ConnectionsManager.getInstance(currentAccount).sendRequest(getBotApp, (response1, error1) -> {
// if (progress != null) {
// progress.end();
// }
if (error1 != null) {
BulletinFactory.of(ChatActivity.this).createErrorBulletin(LocaleController.getString(R.string.UnknownError)).show(true);
} else {
TLRPC.TL_messages_botApp botApp = (TLRPC.TL_messages_botApp) response1;
AndroidUtilities.runOnUIThread(() -> {
// dismissLoading.run();
AtomicBoolean allowWrite = new AtomicBoolean();
Runnable loadBotSheet = () -> {
BotWebViewSheet sheet = new BotWebViewSheet(getContext(), getResourceProvider());
sheet.setParentActivity(getParentActivity());
sheet.requestWebView(currentAccount, bot.id, bot.id, null, null, BotWebViewSheet.TYPE_WEB_VIEW_BOT_APP, 0, false, ChatActivity.this, botApp.app, allowWrite.get(), messageObject.botStartParam, bot);
showDialog(sheet);
if (botApp.inactive) {
sheet.showJustAddedBulletin();
} }
}; };
Browser.openUrl(getContext(), Uri.parse(messageObject.sponsoredUrl), true, false, false, progressDialogCurrent);
if (botApp.request_write_access) {
AlertsCreator.createBotLaunchAlert(ChatActivity.this, allowWrite, bot, loadBotSheet);
} else {
loadBotSheet.run();
}
});
}
});
} else if (messageObject.sponsoredWebPage != null) {
Browser.openUrl(getContext(), messageObject.sponsoredWebPage.url, true, false);
} else if (messageObject.sponsoredChatInvite != null) {
final TLRPC.TL_messages_checkChatInvite req = new TLRPC.TL_messages_checkChatInvite();
req.hash = messageObject.sponsoredChatInviteHash;
ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (error == null) {
TLRPC.ChatInvite invite = (TLRPC.ChatInvite) response;
if (invite.chat != null && (!ChatObject.isLeftFromChat(invite.chat) || !invite.chat.kicked && (ChatObject.isPublic(invite.chat) || invite instanceof TLRPC.TL_chatInvitePeek || invite.chat.has_geo))) {
MessagesController.getInstance(currentAccount).putChat(invite.chat, false);
ArrayList<TLRPC.Chat> chats = new ArrayList<>();
chats.add(invite.chat);
MessagesStorage.getInstance(currentAccount).putUsersAndChats(null, chats, false, true);
args.putLong("chat_id", invite.chat.id);
if (MessagesController.getInstance(currentAccount).checkCanOpenChat(args, ChatActivity.this)) {
ChatActivity fragment = new ChatActivity(args);
if (invite instanceof TLRPC.TL_chatInvitePeek) {
fragment.setChatInvite(invite);
}
presentFragment(fragment);
}
} else {
showDialog(new JoinGroupAlert(getContext(), messageObject.sponsoredChatInvite, messageObject.sponsoredChatInviteHash, ChatActivity.this, themeDelegate, JoinGroupAlert.ORIGINATION_SPONSORED_CHAT));
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
if (error.text.startsWith("FLOOD_WAIT")) {
builder.setMessage(LocaleController.getString("FloodWait", R.string.FloodWait));
} else if (error.text.startsWith("INVITE_HASH_EXPIRED")) {
builder.setTitle(LocaleController.getString("ExpiredLink", R.string.ExpiredLink));
builder.setMessage(LocaleController.getString("InviteExpired", R.string.InviteExpired));
} else {
builder.setMessage(LocaleController.getString("JoinToGroupErrorNotExist", R.string.JoinToGroupErrorNotExist));
}
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
showDialog(builder.create());
}
}), ConnectionsManager.RequestFlagFailOnServerErrors);
} else {
long peerId = MessageObject.getPeerId(messageObject.messageOwner.from_id);
if (peerId == getDialogId() && messageObject.sponsoredChannelPost != 0) {
scrollToMessageId(messageObject.sponsoredChannelPost, 0, true, 0, false, 0);
} else {
if (peerId < 0) {
args.putLong("chat_id", -peerId);
} else {
args.putLong("user_id", peerId);
}
if (messageObject.sponsoredChannelPost != 0) {
args.putInt("message_id", messageObject.sponsoredChannelPost);
}
if (messageObject.botStartParam != null) {
args.putString("inline_query", messageObject.botStartParam);
}
if (getMessagesController().checkCanOpenChat(args, ChatActivity.this)) {
presentFragment(new ChatActivity(args));
}
}
} }
} else { } else {
TLRPC.WebPage webPage = messageObject.getStoryMentionWebpage(); TLRPC.WebPage webPage = messageObject.getStoryMentionWebpage();

View file

@ -8,6 +8,8 @@
package org.telegram.ui; package org.telegram.ui;
import static org.telegram.messenger.LocaleController.getString;
import android.animation.Animator; import android.animation.Animator;
import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet; import android.animation.AnimatorSet;
@ -244,7 +246,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
req.id = new TLRPC.TL_inputPhotoEmpty(); req.id = new TLRPC.TL_inputPhotoEmpty();
getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
avatarImage.setImageDrawable(avatarDrawable); avatarImage.setImageDrawable(avatarDrawable);
setAvatarCell.setTextAndIcon(LocaleController.getString("ChatSetPhotoOrVideo", R.string.ChatSetPhotoOrVideo), R.drawable.msg_addphoto, true); setAvatarCell.setTextAndIcon(getString("ChatSetPhotoOrVideo", R.string.ChatSetPhotoOrVideo), R.drawable.msg_addphoto, true);
if (currentUser != null) { if (currentUser != null) {
currentUser.photo = null; currentUser.photo = null;
@ -600,7 +602,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
linearLayout1.setOrientation(LinearLayout.VERTICAL); linearLayout1.setOrientation(LinearLayout.VERTICAL);
actionBar.setTitle(LocaleController.getString("ChannelEdit", R.string.ChannelEdit)); actionBar.setTitle(getString("ChannelEdit", R.string.ChannelEdit));
avatarContainer = new LinearLayout(context); avatarContainer = new LinearLayout(context);
avatarContainer.setOrientation(LinearLayout.VERTICAL); avatarContainer.setOrientation(LinearLayout.VERTICAL);
@ -691,11 +693,11 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
nameTextView = new EditTextEmoji(context, sizeNotifierFrameLayout, this, EditTextEmoji.STYLE_FRAGMENT, false); nameTextView = new EditTextEmoji(context, sizeNotifierFrameLayout, this, EditTextEmoji.STYLE_FRAGMENT, false);
if (userId != 0) { if (userId != 0) {
nameTextView.setHint(LocaleController.getString(R.string.BotName)); nameTextView.setHint(getString(R.string.BotName));
} else if (isChannel) { } else if (isChannel) {
nameTextView.setHint(LocaleController.getString("EnterChannelName", R.string.EnterChannelName)); nameTextView.setHint(getString("EnterChannelName", R.string.EnterChannelName));
} else { } else {
nameTextView.setHint(LocaleController.getString("GroupName", R.string.GroupName)); nameTextView.setHint(getString("GroupName", R.string.GroupName));
} }
nameTextView.setEnabled(currentChat != null || ChatObject.canChangeChatInfo(currentChat)); nameTextView.setEnabled(currentChat != null || ChatObject.canChangeChatInfo(currentChat));
nameTextView.setFocusable(nameTextView.isEnabled()); nameTextView.setFocusable(nameTextView.isEnabled());
@ -749,7 +751,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
req.id = new TLRPC.TL_inputPhotoEmpty(); req.id = new TLRPC.TL_inputPhotoEmpty();
getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
avatarImage.setImageDrawable(avatarDrawable); avatarImage.setImageDrawable(avatarDrawable);
setAvatarCell.setTextAndIcon(LocaleController.getString("ChatSetPhotoOrVideo", R.string.ChatSetPhotoOrVideo), R.drawable.msg_addphoto, true); setAvatarCell.setTextAndIcon(getString("ChatSetPhotoOrVideo", R.string.ChatSetPhotoOrVideo), R.drawable.msg_addphoto, true);
if (currentUser != null) { if (currentUser != null) {
currentUser.photo = null; currentUser.photo = null;
@ -798,7 +800,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
inputFilters = new InputFilter[1]; inputFilters = new InputFilter[1];
inputFilters[0] = new InputFilter.LengthFilter(255); inputFilters[0] = new InputFilter.LengthFilter(255);
descriptionTextView.setFilters(inputFilters); descriptionTextView.setFilters(inputFilters);
descriptionTextView.setHint(LocaleController.getString("DescriptionOptionalPlaceholder", R.string.DescriptionOptionalPlaceholder)); descriptionTextView.setHint(getString("DescriptionOptionalPlaceholder", R.string.DescriptionOptionalPlaceholder));
descriptionTextView.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); descriptionTextView.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
descriptionTextView.setCursorSize(AndroidUtilities.dp(20)); descriptionTextView.setCursorSize(AndroidUtilities.dp(20));
descriptionTextView.setCursorWidth(1.5f); descriptionTextView.setCursorWidth(1.5f);
@ -914,7 +916,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
HeaderCell headerCell = new HeaderCell(context, Theme.key_dialogTextBlue2, 23, 15, false); HeaderCell headerCell = new HeaderCell(context, Theme.key_dialogTextBlue2, 23, 15, false);
headerCell.setHeight(47); headerCell.setHeight(47);
headerCell.setText(LocaleController.getString("ChatHistory", R.string.ChatHistory)); headerCell.setText(getString("ChatHistory", R.string.ChatHistory));
linearLayout.addView(headerCell); linearLayout.addView(headerCell);
LinearLayout linearLayoutInviteContainer = new LinearLayout(context); LinearLayout linearLayoutInviteContainer = new LinearLayout(context);
@ -928,12 +930,12 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
buttons[a].setTag(a); buttons[a].setTag(a);
buttons[a].setBackgroundDrawable(Theme.getSelectorDrawable(false)); buttons[a].setBackgroundDrawable(Theme.getSelectorDrawable(false));
if (a == 0) { if (a == 0) {
buttons[a].setTextAndValue(LocaleController.getString("ChatHistoryVisible", R.string.ChatHistoryVisible), LocaleController.getString("ChatHistoryVisibleInfo", R.string.ChatHistoryVisibleInfo), true, !historyHidden); buttons[a].setTextAndValue(getString("ChatHistoryVisible", R.string.ChatHistoryVisible), getString("ChatHistoryVisibleInfo", R.string.ChatHistoryVisibleInfo), true, !historyHidden);
} else { } else {
if (ChatObject.isChannel(currentChat)) { if (ChatObject.isChannel(currentChat)) {
buttons[a].setTextAndValue(LocaleController.getString("ChatHistoryHidden", R.string.ChatHistoryHidden), LocaleController.getString("ChatHistoryHiddenInfo", R.string.ChatHistoryHiddenInfo), false, historyHidden); buttons[a].setTextAndValue(getString("ChatHistoryHidden", R.string.ChatHistoryHidden), getString("ChatHistoryHiddenInfo", R.string.ChatHistoryHiddenInfo), false, historyHidden);
} else { } else {
buttons[a].setTextAndValue(LocaleController.getString("ChatHistoryHidden", R.string.ChatHistoryHidden), LocaleController.getString("ChatHistoryHiddenInfo2", R.string.ChatHistoryHiddenInfo2), false, historyHidden); buttons[a].setTextAndValue(getString("ChatHistoryHidden", R.string.ChatHistoryHidden), getString("ChatHistoryHiddenInfo2", R.string.ChatHistoryHiddenInfo2), false, historyHidden);
} }
} }
linearLayoutInviteContainer.addView(buttons[a], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); linearLayoutInviteContainer.addView(buttons[a], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
@ -968,7 +970,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
if (isChannel) { if (isChannel) {
signCell = new TextCell(context, 23, false, true, null); signCell = new TextCell(context, 23, false, true, null);
signCell.setBackgroundDrawable(Theme.getSelectorDrawable(true)); signCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
signCell.setTextAndCheckAndIcon(LocaleController.getString("ChannelSignMessages", R.string.ChannelSignMessages), signMessages, R.drawable.msg_signed, false); signCell.setTextAndCheckAndIcon(getString("ChannelSignMessages", R.string.ChannelSignMessages), signMessages, R.drawable.msg_signed, false);
typeEditContainer.addView(signCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); typeEditContainer.addView(signCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
signCell.setOnClickListener(v -> { signCell.setOnClickListener(v -> {
signMessages = !signMessages; signMessages = !signMessages;
@ -977,14 +979,14 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
} else if (currentChat.creator) { } else if (currentChat.creator) {
forumsCell = new TextCell(context, 23, false, true, null); forumsCell = new TextCell(context, 23, false, true, null);
forumsCell.setBackgroundDrawable(Theme.getSelectorDrawable(true)); forumsCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
forumsCell.setTextAndCheckAndIcon(LocaleController.getString("ChannelTopics", R.string.ChannelTopics), forum, R.drawable.msg_topics, false); forumsCell.setTextAndCheckAndIcon(getString("ChannelTopics", R.string.ChannelTopics), forum, R.drawable.msg_topics, false);
forumsCell.getCheckBox().setIcon(canForum ? 0 : R.drawable.permission_locked); forumsCell.getCheckBox().setIcon(canForum ? 0 : R.drawable.permission_locked);
typeEditContainer.addView(forumsCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); typeEditContainer.addView(forumsCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
forumsCell.setOnClickListener(v -> { forumsCell.setOnClickListener(v -> {
if (!canForum) { if (!canForum) {
CharSequence text; CharSequence text;
if (!(info == null || info.linked_chat_id == 0)) { if (!(info == null || info.linked_chat_id == 0)) {
text = AndroidUtilities.replaceTags(LocaleController.getString("ChannelTopicsDiscussionForbidden", R.string.ChannelTopicsDiscussionForbidden)); text = AndroidUtilities.replaceTags(getString("ChannelTopicsDiscussionForbidden", R.string.ChannelTopicsDiscussionForbidden));
} else { } else {
text = AndroidUtilities.replaceTags(LocaleController.formatPluralString("ChannelTopicsForbidden", getMessagesController().forumUpgradeParticipantsMin)); text = AndroidUtilities.replaceTags(LocaleController.formatPluralString("ChannelTopicsForbidden", getMessagesController().forumUpgradeParticipantsMin));
} }
@ -1005,7 +1007,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
ActionBarMenu menu = actionBar.createMenu(); ActionBarMenu menu = actionBar.createMenu();
if (currentUser != null || ChatObject.canChangeChatInfo(currentChat) || signCell != null || historyCell != null) { if (currentUser != null || ChatObject.canChangeChatInfo(currentChat) || signCell != null || historyCell != null) {
doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_ab_done, AndroidUtilities.dp(56)); doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_ab_done, AndroidUtilities.dp(56));
doneButton.setContentDescription(LocaleController.getString("Done", R.string.Done)); doneButton.setContentDescription(getString("Done", R.string.Done));
} }
if (locationCell != null || signCell != null || historyCell != null || typeCell != null || linkedCell != null || forumsCell != null) { if (locationCell != null || signCell != null || historyCell != null || typeCell != null || linkedCell != null || forumsCell != null) {
@ -1017,9 +1019,9 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
settingsSectionCell.setBackground(combinedDrawable); settingsSectionCell.setBackground(combinedDrawable);
linearLayout1.addView(settingsSectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); linearLayout1.addView(settingsSectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
if (forumsCell != null) { if (forumsCell != null) {
settingsSectionCell.setText(LocaleController.getString("ForumToggleDescription", R.string.ForumToggleDescription)); settingsSectionCell.setText(getString("ForumToggleDescription", R.string.ForumToggleDescription));
} else { } else {
settingsSectionCell.setText(LocaleController.getString("ChannelSignMessagesInfo", R.string.ChannelSignMessagesInfo)); settingsSectionCell.setText(getString("ChannelSignMessagesInfo", R.string.ChannelSignMessagesInfo));
} }
} }
@ -1103,7 +1105,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
if (ChatObject.isBoostSupported(currentChat)) { if (ChatObject.isBoostSupported(currentChat)) {
statsAndBoosts = new TextCell(context); statsAndBoosts = new TextCell(context);
statsAndBoosts.setTextAndIcon(LocaleController.getString("StatisticsAndBoosts", R.string.StatisticsAndBoosts), R.drawable.msg_stats, true); statsAndBoosts.setTextAndIcon(getString(R.string.StatisticsAndBoosts), R.drawable.msg_stats, true);
statsAndBoosts.setBackground(Theme.getSelectorDrawable(false)); statsAndBoosts.setBackground(Theme.getSelectorDrawable(false));
statsAndBoosts.setOnClickListener(v -> { statsAndBoosts.setOnClickListener(v -> {
presentFragment(StatisticActivity.create(currentChat, false)); presentFragment(StatisticActivity.create(currentChat, false));
@ -1129,25 +1131,6 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
if (isChannel || currentChat.gigagroup) { if (isChannel || currentChat.gigagroup) {
infoContainer.addView(blockCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); infoContainer.addView(blockCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
} }
if (!isChannel && info != null && info.can_set_stickers) {
stickersContainer = new FrameLayout(context);
stickersContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
linearLayout1.addView(stickersContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
stickersCell = new TextCell(context);
stickersCell.setBackground(Theme.getSelectorDrawable(false));
stickersCell.setOnClickListener(v -> presentFragment(new ChannelAdminLogActivity(currentChat)));
stickersCell.setPrioritizeTitleOverValue(true);
stickersContainer.addView(stickersCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
stickersCell.setOnClickListener(v -> {
GroupStickersActivity groupStickersActivity = new GroupStickersActivity(currentChat.id);
groupStickersActivity.setInfo(info);
presentFragment(groupStickersActivity);
});
if (statsAndBoosts != null) {
infoContainer.addView(statsAndBoosts, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
}
} else {
if (statsAndBoosts != null) { if (statsAndBoosts != null) {
infoContainer.addView(statsAndBoosts, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); infoContainer.addView(statsAndBoosts, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
} }
@ -1155,7 +1138,6 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
infoContainer.addView(logCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); infoContainer.addView(logCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
} }
} }
}
if (currentUser != null) { if (currentUser != null) {
publicLinkCell = new TextCell(context); publicLinkCell = new TextCell(context);
@ -1172,19 +1154,19 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
editIntroCell = new TextCell(context); editIntroCell = new TextCell(context);
editIntroCell.setBackground(Theme.getSelectorDrawable(false)); editIntroCell.setBackground(Theme.getSelectorDrawable(false));
editIntroCell.setTextAndIcon(LocaleController.getString(R.string.BotEditIntro), R.drawable.msg_log, true); editIntroCell.setTextAndIcon(getString(R.string.BotEditIntro), R.drawable.msg_log, true);
infoContainer.addView(editIntroCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); infoContainer.addView(editIntroCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
editIntroCell.setOnClickListener(v -> Browser.openUrl(v.getContext(), "https://t.me/BotFather?start=" + getActiveUsername(currentUser) + "-intro")); editIntroCell.setOnClickListener(v -> Browser.openUrl(v.getContext(), "https://t.me/BotFather?start=" + getActiveUsername(currentUser) + "-intro"));
editCommandsCell = new TextCell(context); editCommandsCell = new TextCell(context);
editCommandsCell.setBackground(Theme.getSelectorDrawable(false)); editCommandsCell.setBackground(Theme.getSelectorDrawable(false));
editCommandsCell.setTextAndIcon(LocaleController.getString(R.string.BotEditCommands), R.drawable.msg_media, true); editCommandsCell.setTextAndIcon(getString(R.string.BotEditCommands), R.drawable.msg_media, true);
infoContainer.addView(editCommandsCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); infoContainer.addView(editCommandsCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
editCommandsCell.setOnClickListener(v -> Browser.openUrl(v.getContext(), "https://t.me/BotFather?start=" + getActiveUsername(currentUser) + "-commands")); editCommandsCell.setOnClickListener(v -> Browser.openUrl(v.getContext(), "https://t.me/BotFather?start=" + getActiveUsername(currentUser) + "-commands"));
changeBotSettingsCell = new TextCell(context); changeBotSettingsCell = new TextCell(context);
changeBotSettingsCell.setBackground(Theme.getSelectorDrawable(false)); changeBotSettingsCell.setBackground(Theme.getSelectorDrawable(false));
changeBotSettingsCell.setTextAndIcon(LocaleController.getString(R.string.BotChangeSettings), R.drawable.msg_bot, true); changeBotSettingsCell.setTextAndIcon(getString(R.string.BotChangeSettings), R.drawable.msg_bot, true);
infoContainer.addView(changeBotSettingsCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); infoContainer.addView(changeBotSettingsCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
changeBotSettingsCell.setOnClickListener(v -> Browser.openUrl(v.getContext(), "https://t.me/BotFather?start=" + getActiveUsername(currentUser))); changeBotSettingsCell.setOnClickListener(v -> Browser.openUrl(v.getContext(), "https://t.me/BotFather?start=" + getActiveUsername(currentUser)));
} }
@ -1199,15 +1181,9 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
infoSectionCell = new ShadowSectionCell(context); infoSectionCell = new ShadowSectionCell(context);
linearLayout1.addView(infoSectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); linearLayout1.addView(infoSectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
} }
if (!isChannel && info != null && info.can_set_stickers) {
stickersInfoCell = new TextInfoPrivacyCell(context);
stickersInfoCell.setText(LocaleController.getString(R.string.GroupStickersInfo));
linearLayout1.addView(stickersInfoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
}
} else { } else {
botInfoCell = new TextInfoPrivacyCell(context); botInfoCell = new TextInfoPrivacyCell(context);
String str = LocaleController.getString(R.string.BotManageInfo); String str = getString(R.string.BotManageInfo);
SpannableString span = SpannableString.valueOf(str); SpannableString span = SpannableString.valueOf(str);
int index = str.indexOf("@BotFather"); int index = str.indexOf("@BotFather");
if (index != -1) { if (index != -1) {
@ -1238,11 +1214,11 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
deleteCell.setTextColor(Theme.getColor(Theme.key_text_RedRegular)); deleteCell.setTextColor(Theme.getColor(Theme.key_text_RedRegular));
deleteCell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); deleteCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
if (currentUser != null) { if (currentUser != null) {
deleteCell.setText(LocaleController.getString(R.string.DeleteBot), false); deleteCell.setText(getString(R.string.DeleteBot), false);
} else if (isChannel) { } else if (isChannel) {
deleteCell.setText(LocaleController.getString("ChannelDelete", R.string.ChannelDelete), false); deleteCell.setText(getString("ChannelDelete", R.string.ChannelDelete), false);
} else { } else {
deleteCell.setText(LocaleController.getString("DeleteAndExitButton", R.string.DeleteAndExitButton), false); deleteCell.setText(getString("DeleteAndExitButton", R.string.DeleteAndExitButton), false);
} }
deleteContainer.addView(deleteCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); deleteContainer.addView(deleteCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
deleteCell.setOnClickListener(v -> AlertsCreator.createClearOrDeleteDialogAlert(ChatEditActivity.this, false, true, false, currentChat, null, false, true, false, (param) -> { deleteCell.setOnClickListener(v -> AlertsCreator.createClearOrDeleteDialogAlert(ChatEditActivity.this, false, true, false, currentChat, null, false, true, false, (param) -> {
@ -1296,9 +1272,9 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
} }
} }
publicLinkCell.setTextAndValueAndIcon(LocaleController.getString(R.string.BotPublicLinks), LocaleController.formatString(R.string.BotPublicLinksCount, usernamesActive, currentUser.usernames.size()), R.drawable.msg_link2, true); publicLinkCell.setTextAndValueAndIcon(getString(R.string.BotPublicLinks), LocaleController.formatString(R.string.BotPublicLinksCount, usernamesActive, currentUser.usernames.size()), R.drawable.msg_link2, true);
} else { } else {
publicLinkCell.setTextAndValueAndIcon(LocaleController.getString(R.string.BotPublicLink), "t.me/" + currentUser.username, R.drawable.msg_link2, true); publicLinkCell.setTextAndValueAndIcon(getString(R.string.BotPublicLink), "t.me/" + currentUser.username, R.drawable.msg_link2, true);
} }
} }
@ -1342,9 +1318,9 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
} }
if (setAvatarCell != null) { if (setAvatarCell != null) {
if (hasPhoto || imageUpdater.isUploadingImage()) { if (hasPhoto || imageUpdater.isUploadingImage()) {
setAvatarCell.setTextAndIcon(LocaleController.getString("ChatSetNewPhoto", R.string.ChatSetNewPhoto), R.drawable.msg_addphoto, true); setAvatarCell.setTextAndIcon(getString("ChatSetNewPhoto", R.string.ChatSetNewPhoto), R.drawable.msg_addphoto, true);
} else { } else {
setAvatarCell.setTextAndIcon(LocaleController.getString("ChatSetPhotoOrVideo", R.string.ChatSetPhotoOrVideo), R.drawable.msg_addphoto, true); setAvatarCell.setTextAndIcon(getString("ChatSetPhotoOrVideo", R.string.ChatSetPhotoOrVideo), R.drawable.msg_addphoto, true);
} }
if (cameraDrawable == null) { if (cameraDrawable == null) {
cameraDrawable = new RLottieDrawable(R.raw.camera_outline, "" + R.raw.camera_outline, AndroidUtilities.dp(50), AndroidUtilities.dp(50), false, null); cameraDrawable = new RLottieDrawable(R.raw.camera_outline, "" + R.raw.camera_outline, AndroidUtilities.dp(50), AndroidUtilities.dp(50), false, null);
@ -1477,7 +1453,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
showAvatarProgress(false, true); showAvatarProgress(false, true);
} else { } else {
avatarImage.setImage(ImageLocation.getForLocal(avatar), "50_50", avatarDrawable, currentUser != null ? currentUser : currentChat); avatarImage.setImage(ImageLocation.getForLocal(avatar), "50_50", avatarDrawable, currentUser != null ? currentUser : currentChat);
setAvatarCell.setTextAndIcon(LocaleController.getString("ChatSetNewPhoto", R.string.ChatSetNewPhoto), R.drawable.msg_addphoto, true); setAvatarCell.setTextAndIcon(getString("ChatSetNewPhoto", R.string.ChatSetNewPhoto), R.drawable.msg_addphoto, true);
if (cameraDrawable == null) { if (cameraDrawable == null) {
cameraDrawable = new RLottieDrawable(R.raw.camera_outline, "" + R.raw.camera_outline, AndroidUtilities.dp(50), AndroidUtilities.dp(50), false, null); cameraDrawable = new RLottieDrawable(R.raw.camera_outline, "" + R.raw.camera_outline, AndroidUtilities.dp(50), AndroidUtilities.dp(50), false, null);
} }
@ -1503,10 +1479,10 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
if (nameTextView != null && !currentUser.first_name.equals(nameTextView.getText().toString()) || if (nameTextView != null && !currentUser.first_name.equals(nameTextView.getText().toString()) ||
descriptionTextView != null && !about.equals(descriptionTextView.getText().toString())) { descriptionTextView != null && !about.equals(descriptionTextView.getText().toString())) {
showDialog(new AlertDialog.Builder(getParentActivity()) showDialog(new AlertDialog.Builder(getParentActivity())
.setTitle(LocaleController.getString("UserRestrictionsApplyChanges", R.string.UserRestrictionsApplyChanges)) .setTitle(getString("UserRestrictionsApplyChanges", R.string.UserRestrictionsApplyChanges))
.setMessage(LocaleController.getString(R.string.BotSettingsChangedAlert)) .setMessage(getString(R.string.BotSettingsChangedAlert))
.setPositiveButton(LocaleController.getString("ApplyTheme", R.string.ApplyTheme), (dialogInterface, i) -> processDone()) .setPositiveButton(getString("ApplyTheme", R.string.ApplyTheme), (dialogInterface, i) -> processDone())
.setNegativeButton(LocaleController.getString("PassportDiscard", R.string.PassportDiscard), (dialog, which) -> finishFragment()) .setNegativeButton(getString("PassportDiscard", R.string.PassportDiscard), (dialog, which) -> finishFragment())
.create()); .create());
return false; return false;
} }
@ -1519,14 +1495,14 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
descriptionTextView != null && !about.equals(descriptionTextView.getText().toString()) || descriptionTextView != null && !about.equals(descriptionTextView.getText().toString()) ||
signMessages != currentChat.signatures || forum != currentChat.forum) { signMessages != currentChat.signatures || forum != currentChat.forum) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("UserRestrictionsApplyChanges", R.string.UserRestrictionsApplyChanges)); builder.setTitle(getString("UserRestrictionsApplyChanges", R.string.UserRestrictionsApplyChanges));
if (isChannel) { if (isChannel) {
builder.setMessage(LocaleController.getString("ChannelSettingsChangedAlert", R.string.ChannelSettingsChangedAlert)); builder.setMessage(getString("ChannelSettingsChangedAlert", R.string.ChannelSettingsChangedAlert));
} else { } else {
builder.setMessage(LocaleController.getString("GroupSettingsChangedAlert", R.string.GroupSettingsChangedAlert)); builder.setMessage(getString("GroupSettingsChangedAlert", R.string.GroupSettingsChangedAlert));
} }
builder.setPositiveButton(LocaleController.getString("ApplyTheme", R.string.ApplyTheme), (dialogInterface, i) -> processDone()); builder.setPositiveButton(getString("ApplyTheme", R.string.ApplyTheme), (dialogInterface, i) -> processDone());
builder.setNegativeButton(LocaleController.getString("PassportDiscard", R.string.PassportDiscard), (dialog, which) -> finishFragment()); builder.setNegativeButton(getString("PassportDiscard", R.string.PassportDiscard), (dialog, which) -> finishFragment());
showDialog(builder.create()); showDialog(builder.create());
return false; return false;
} }
@ -1778,7 +1754,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
} }
if (logCell != null) { if (logCell != null) {
logCell.setVisibility(!currentChat.megagroup || currentChat.gigagroup || info != null && info.participants_count > 200 ? View.VISIBLE : View.GONE); logCell.setVisibility(ChatObject.isChannel(currentChat) ? View.VISIBLE : View.GONE);
} }
if (linkedCell != null) { if (linkedCell != null) {
@ -1787,7 +1763,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
} else { } else {
linkedCell.setVisibility(View.VISIBLE); linkedCell.setVisibility(View.VISIBLE);
if (info.linked_chat_id == 0) { if (info.linked_chat_id == 0) {
linkedCell.setTextAndValueAndIcon(LocaleController.getString("Discussion", R.string.Discussion), LocaleController.getString("DiscussionInfoShort", R.string.DiscussionInfoShort), R.drawable.msg_discuss, true); linkedCell.setTextAndValueAndIcon(getString("Discussion", R.string.Discussion), getString("DiscussionInfoShort", R.string.DiscussionInfoShort), R.drawable.msg_discuss, true);
} else { } else {
TLRPC.Chat chat = getMessagesController().getChat(info.linked_chat_id); TLRPC.Chat chat = getMessagesController().getChat(info.linked_chat_id);
if (chat == null) { if (chat == null) {
@ -1796,15 +1772,15 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
String username; String username;
if (isChannel) { if (isChannel) {
if (TextUtils.isEmpty(username = ChatObject.getPublicUsername(chat))) { if (TextUtils.isEmpty(username = ChatObject.getPublicUsername(chat))) {
linkedCell.setTextAndValueAndIcon(LocaleController.getString("Discussion", R.string.Discussion), chat.title, R.drawable.msg_discuss,true); linkedCell.setTextAndValueAndIcon(getString("Discussion", R.string.Discussion), chat.title, R.drawable.msg_discuss,true);
} else { } else {
linkedCell.setTextAndValueAndIcon(LocaleController.getString("Discussion", R.string.Discussion), "@" + username, R.drawable.msg_discuss,true); linkedCell.setTextAndValueAndIcon(getString("Discussion", R.string.Discussion), "@" + username, R.drawable.msg_discuss,true);
} }
} else { } else {
if (TextUtils.isEmpty(username = ChatObject.getPublicUsername(chat))) { if (TextUtils.isEmpty(username = ChatObject.getPublicUsername(chat))) {
linkedCell.setTextAndValueAndIcon(LocaleController.getString("LinkedChannel", R.string.LinkedChannel), chat.title, R.drawable.msg_channel, forumsCell != null && forumsCell.getVisibility() == View.VISIBLE); linkedCell.setTextAndValueAndIcon(getString("LinkedChannel", R.string.LinkedChannel), chat.title, R.drawable.msg_channel, forumsCell != null && forumsCell.getVisibility() == View.VISIBLE);
} else { } else {
linkedCell.setTextAndValueAndIcon(LocaleController.getString("LinkedChannel", R.string.LinkedChannel), "@" + username, R.drawable.msg_channel, forumsCell != null && forumsCell.getVisibility() == View.VISIBLE); linkedCell.setTextAndValueAndIcon(getString("LinkedChannel", R.string.LinkedChannel), "@" + username, R.drawable.msg_channel, forumsCell != null && forumsCell.getVisibility() == View.VISIBLE);
} }
} }
} }
@ -1817,9 +1793,9 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
locationCell.setVisibility(View.VISIBLE); locationCell.setVisibility(View.VISIBLE);
if (info.location instanceof TLRPC.TL_channelLocation) { if (info.location instanceof TLRPC.TL_channelLocation) {
TLRPC.TL_channelLocation location = (TLRPC.TL_channelLocation) info.location; TLRPC.TL_channelLocation location = (TLRPC.TL_channelLocation) info.location;
locationCell.setTextAndValue(LocaleController.getString("AttachLocation", R.string.AttachLocation), location.address, animated, true); locationCell.setTextAndValue(getString("AttachLocation", R.string.AttachLocation), location.address, animated, true);
} else { } else {
locationCell.setTextAndValue(LocaleController.getString("AttachLocation", R.string.AttachLocation), "Unknown address", animated, true); locationCell.setTextAndValue(getString("AttachLocation", R.string.AttachLocation), "Unknown address", animated, true);
} }
} else { } else {
locationCell.setVisibility(View.GONE); locationCell.setVisibility(View.GONE);
@ -1830,30 +1806,30 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
if (info != null && info.location instanceof TLRPC.TL_channelLocation) { if (info != null && info.location instanceof TLRPC.TL_channelLocation) {
String link; String link;
if (isPrivate) { if (isPrivate) {
link = LocaleController.getString("TypeLocationGroupEdit", R.string.TypeLocationGroupEdit); link = getString("TypeLocationGroupEdit", R.string.TypeLocationGroupEdit);
} else { } else {
link = String.format("https://" + getMessagesController().linkPrefix + "/%s", ChatObject.getPublicUsername(currentChat)); link = String.format("https://" + getMessagesController().linkPrefix + "/%s", ChatObject.getPublicUsername(currentChat));
} }
typeCell.setTextAndValueAndIcon(LocaleController.getString("TypeLocationGroup", R.string.TypeLocationGroup), link, R.drawable.msg_channel, historyCell != null && historyCell.getVisibility() == View.VISIBLE || linkedCell != null && linkedCell.getVisibility() == View.VISIBLE || forumsCell != null && forumsCell.getVisibility() == View.VISIBLE); typeCell.setTextAndValueAndIcon(getString("TypeLocationGroup", R.string.TypeLocationGroup), link, R.drawable.msg_channel, historyCell != null && historyCell.getVisibility() == View.VISIBLE || linkedCell != null && linkedCell.getVisibility() == View.VISIBLE || forumsCell != null && forumsCell.getVisibility() == View.VISIBLE);
} else { } else {
String type; String type;
boolean isRestricted = currentChat.noforwards; boolean isRestricted = currentChat.noforwards;
if (isChannel) { if (isChannel) {
type = isPrivate ? isRestricted ? LocaleController.getString("TypePrivateRestrictedForwards", R.string.TypePrivateRestrictedForwards) : LocaleController.getString("TypePrivate", R.string.TypePrivate) : LocaleController.getString("TypePublic", R.string.TypePublic); type = isPrivate ? isRestricted ? getString("TypePrivateRestrictedForwards", R.string.TypePrivateRestrictedForwards) : getString("TypePrivate", R.string.TypePrivate) : getString("TypePublic", R.string.TypePublic);
} else { } else {
type = isPrivate ? isRestricted ? LocaleController.getString("TypePrivateGroupRestrictedForwards", R.string.TypePrivateGroupRestrictedForwards) : LocaleController.getString("TypePrivateGroup", R.string.TypePrivateGroup) : LocaleController.getString("TypePublicGroup", R.string.TypePublicGroup); type = isPrivate ? isRestricted ? getString("TypePrivateGroupRestrictedForwards", R.string.TypePrivateGroupRestrictedForwards) : getString("TypePrivateGroup", R.string.TypePrivateGroup) : getString("TypePublicGroup", R.string.TypePublicGroup);
} }
if (isChannel) { if (isChannel) {
typeCell.setTextAndValueAndIcon(LocaleController.getString("ChannelType", R.string.ChannelType), type, R.drawable.msg_channel, historyCell != null && historyCell.getVisibility() == View.VISIBLE || linkedCell != null && linkedCell.getVisibility() == View.VISIBLE || forumsCell != null && forumsCell.getVisibility() == View.VISIBLE); typeCell.setTextAndValueAndIcon(getString("ChannelType", R.string.ChannelType), type, R.drawable.msg_channel, historyCell != null && historyCell.getVisibility() == View.VISIBLE || linkedCell != null && linkedCell.getVisibility() == View.VISIBLE || forumsCell != null && forumsCell.getVisibility() == View.VISIBLE);
} else { } else {
typeCell.setTextAndValueAndIcon(LocaleController.getString("GroupType", R.string.GroupType), type, R.drawable.msg_groups, historyCell != null && historyCell.getVisibility() == View.VISIBLE || linkedCell != null && linkedCell.getVisibility() == View.VISIBLE || forumsCell != null && forumsCell.getVisibility() == View.VISIBLE); typeCell.setTextAndValueAndIcon(getString("GroupType", R.string.GroupType), type, R.drawable.msg_groups, historyCell != null && historyCell.getVisibility() == View.VISIBLE || linkedCell != null && linkedCell.getVisibility() == View.VISIBLE || forumsCell != null && forumsCell.getVisibility() == View.VISIBLE);
} }
} }
} }
if (historyCell != null) { if (historyCell != null) {
String type = historyHidden && !forum ? LocaleController.getString("ChatHistoryHidden", R.string.ChatHistoryHidden) : LocaleController.getString("ChatHistoryVisible", R.string.ChatHistoryVisible); String type = historyHidden && !forum ? getString("ChatHistoryHidden", R.string.ChatHistoryHidden) : getString("ChatHistoryVisible", R.string.ChatHistoryVisible);
historyCell.setTextAndValueAndIcon(LocaleController.getString("ChatHistoryShort", R.string.ChatHistoryShort), type, animated, R.drawable.msg_discuss, forumsCell != null); historyCell.setTextAndValueAndIcon(getString("ChatHistoryShort", R.string.ChatHistoryShort), type, animated, R.drawable.msg_discuss, forumsCell != null);
historyCell.setEnabled(!forum); historyCell.setEnabled(!forum);
updateHistoryShow(!forum && isPrivate && (info == null || info.linked_chat_id == 0) && !(info != null && info.location instanceof TLRPC.TL_channelLocation), animated); updateHistoryShow(!forum && isPrivate && (info == null || info.linked_chat_id == 0) && !(info != null && info.location instanceof TLRPC.TL_channelLocation), animated);
} }
@ -1868,16 +1844,16 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
memberRequestsCell.setVisibility(info.requests_pending > 0 ? View.VISIBLE : View.GONE); memberRequestsCell.setVisibility(info.requests_pending > 0 ? View.VISIBLE : View.GONE);
} }
if (isChannel) { if (isChannel) {
membersCell.setTextAndValueAndIcon(LocaleController.getString("ChannelSubscribers", R.string.ChannelSubscribers), String.format("%d", info.participants_count), R.drawable.msg_groups, true); membersCell.setTextAndValueAndIcon(getString("ChannelSubscribers", R.string.ChannelSubscribers), String.format("%d", info.participants_count), R.drawable.msg_groups, true);
blockCell.setTextAndValueAndIcon(LocaleController.getString("ChannelBlacklist", R.string.ChannelBlacklist), String.format("%d", Math.max(info.banned_count, info.kicked_count)), R.drawable.msg_user_remove, logCell != null && logCell.getVisibility() == View.VISIBLE); blockCell.setTextAndValueAndIcon(getString("ChannelBlacklist", R.string.ChannelBlacklist), String.format("%d", Math.max(info.banned_count, info.kicked_count)), R.drawable.msg_user_remove, logCell != null && logCell.getVisibility() == View.VISIBLE);
} else { } else {
if (ChatObject.isChannel(currentChat)) { if (ChatObject.isChannel(currentChat)) {
membersCell.setTextAndValueAndIcon(LocaleController.getString("ChannelMembers", R.string.ChannelMembers), String.format("%d", info.participants_count), R.drawable.msg_groups, true); membersCell.setTextAndValueAndIcon(getString("ChannelMembers", R.string.ChannelMembers), String.format("%d", info.participants_count), R.drawable.msg_groups, true);
} else { } else {
membersCell.setTextAndValueAndIcon(LocaleController.getString("ChannelMembers", R.string.ChannelMembers), String.format("%d", info.participants.participants.size()), R.drawable.msg_groups, memberRequestsCell.getVisibility() == View.VISIBLE); membersCell.setTextAndValueAndIcon(getString("ChannelMembers", R.string.ChannelMembers), String.format("%d", info.participants.participants.size()), R.drawable.msg_groups, memberRequestsCell.getVisibility() == View.VISIBLE);
} }
if (currentChat.gigagroup) { if (currentChat.gigagroup) {
blockCell.setTextAndValueAndIcon(LocaleController.getString("ChannelBlacklist", R.string.ChannelBlacklist), String.format("%d", Math.max(info.banned_count, info.kicked_count)), R.drawable.msg_user_remove, logCell != null && logCell.getVisibility() == View.VISIBLE); blockCell.setTextAndValueAndIcon(getString("ChannelBlacklist", R.string.ChannelBlacklist), String.format("%d", Math.max(info.banned_count, info.kicked_count)), R.drawable.msg_user_remove, logCell != null && logCell.getVisibility() == View.VISIBLE);
} else { } else {
int count = 0; int count = 0;
if (currentChat.default_banned_rights != null) { if (currentChat.default_banned_rights != null) {
@ -1900,26 +1876,26 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
} else { } else {
count = forum ? 14 : 13; count = forum ? 14 : 13;
} }
blockCell.setTextAndValueAndIcon(LocaleController.getString("ChannelPermissions", R.string.ChannelPermissions), String.format("%d/%d", count, forum ? 14 : 13), animated, R.drawable.msg_permissions, true); blockCell.setTextAndValueAndIcon(getString("ChannelPermissions", R.string.ChannelPermissions), String.format("%d/%d", count, forum ? 14 : 13), animated, R.drawable.msg_permissions, true);
} }
if (memberRequestsCell != null) { if (memberRequestsCell != null) {
memberRequestsCell.setTextAndValueAndIcon(LocaleController.getString("MemberRequests", R.string.MemberRequests), String.format("%d", info.requests_pending), R.drawable.msg_requests, logCell != null && logCell.getVisibility() == View.VISIBLE); memberRequestsCell.setTextAndValueAndIcon(getString("MemberRequests", R.string.MemberRequests), String.format("%d", info.requests_pending), R.drawable.msg_requests, logCell != null && logCell.getVisibility() == View.VISIBLE);
} }
} }
adminCell.setTextAndValueAndIcon(LocaleController.getString("ChannelAdministrators", R.string.ChannelAdministrators), String.format("%d", ChatObject.isChannel(currentChat) ? info.admins_count : getAdminCount()), R.drawable.msg_admins, true); adminCell.setTextAndValueAndIcon(getString("ChannelAdministrators", R.string.ChannelAdministrators), String.format("%d", ChatObject.isChannel(currentChat) ? info.admins_count : getAdminCount()), R.drawable.msg_admins, true);
} else { } else {
if (isChannel) { if (isChannel) {
membersCell.setTextAndIcon(LocaleController.getString("ChannelSubscribers", R.string.ChannelSubscribers), R.drawable.msg_groups, true); membersCell.setTextAndIcon(getString("ChannelSubscribers", R.string.ChannelSubscribers), R.drawable.msg_groups, true);
blockCell.setTextAndIcon(LocaleController.getString("ChannelBlacklist", R.string.ChannelBlacklist), R.drawable.msg_chats_remove, logCell != null && logCell.getVisibility() == View.VISIBLE); blockCell.setTextAndIcon(getString("ChannelBlacklist", R.string.ChannelBlacklist), R.drawable.msg_chats_remove, logCell != null && logCell.getVisibility() == View.VISIBLE);
} else { } else {
membersCell.setTextAndIcon(LocaleController.getString("ChannelMembers", R.string.ChannelMembers), R.drawable.msg_groups, logCell != null && logCell.getVisibility() == View.VISIBLE); membersCell.setTextAndIcon(getString("ChannelMembers", R.string.ChannelMembers), R.drawable.msg_groups, logCell != null && logCell.getVisibility() == View.VISIBLE);
if (currentChat.gigagroup) { if (currentChat.gigagroup) {
blockCell.setTextAndIcon(LocaleController.getString("ChannelBlacklist", R.string.ChannelBlacklist), R.drawable.msg_chats_remove, logCell != null && logCell.getVisibility() == View.VISIBLE); blockCell.setTextAndIcon(getString("ChannelBlacklist", R.string.ChannelBlacklist), R.drawable.msg_chats_remove, logCell != null && logCell.getVisibility() == View.VISIBLE);
} else { } else {
blockCell.setTextAndIcon(LocaleController.getString("ChannelPermissions", R.string.ChannelPermissions), R.drawable.msg_permissions, true); blockCell.setTextAndIcon(getString("ChannelPermissions", R.string.ChannelPermissions), R.drawable.msg_permissions, true);
} }
} }
adminCell.setTextAndIcon(LocaleController.getString("ChannelAdministrators", R.string.ChannelAdministrators), R.drawable.msg_admins, true); adminCell.setTextAndIcon(getString("ChannelAdministrators", R.string.ChannelAdministrators), R.drawable.msg_admins, true);
} }
reactionsCell.setVisibility(ChatObject.canChangeChatInfo(currentChat) ? View.VISIBLE : View.GONE); reactionsCell.setVisibility(ChatObject.canChangeChatInfo(currentChat) ? View.VISIBLE : View.GONE);
updateReactionsCell(animated); updateReactionsCell(animated);
@ -1927,21 +1903,21 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
inviteLinksCell.setVisibility(View.GONE); inviteLinksCell.setVisibility(View.GONE);
} else { } else {
if (info.invitesCount > 0) { if (info.invitesCount > 0) {
inviteLinksCell.setTextAndValueAndIcon(LocaleController.getString("InviteLinks", R.string.InviteLinks), Integer.toString(info.invitesCount), R.drawable.msg_link2, true); inviteLinksCell.setTextAndValueAndIcon(getString("InviteLinks", R.string.InviteLinks), Integer.toString(info.invitesCount), R.drawable.msg_link2, true);
} else { } else {
inviteLinksCell.setTextAndValueAndIcon(LocaleController.getString("InviteLinks", R.string.InviteLinks), "1", R.drawable.msg_link2, true); inviteLinksCell.setTextAndValueAndIcon(getString("InviteLinks", R.string.InviteLinks), "1", R.drawable.msg_link2, true);
} }
} }
} }
if (stickersCell != null && info != null) { if (stickersCell != null && info != null) {
stickersCell.setTextAndValueAndIcon(LocaleController.getString(R.string.GroupStickers), info.stickerset != null ? info.stickerset.title : LocaleController.getString(R.string.Add), R.drawable.msg_sticker, false); stickersCell.setTextAndValueAndIcon(getString(R.string.GroupStickers), info.stickerset != null ? info.stickerset.title : getString(R.string.Add), R.drawable.msg_sticker, false);
} }
} }
public void updateColorCell() { public void updateColorCell() {
if (colorCell != null) { if (colorCell != null) {
colorCell.set(currentChat, (historyCell != null && historyCell.getVisibility() == View.VISIBLE) || (signCell != null && signCell.getVisibility() == View.VISIBLE) || (forumsCell != null && forumsCell.getVisibility() == View.VISIBLE)); colorCell.set(currentChat, (historyCell != null && historyCell.getVisibility() == View.VISIBLE) || (signCell != null && signCell.getVisibility() == View.VISIBLE) || (forumsCell != null && forumsCell.getVisibility() == View.VISIBLE) || ChatObject.isMegagroup(currentChat) && ChatObject.hasAdminRights(currentChat));
} }
} }
@ -2022,7 +1998,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
boolean isChannelAndNotMegaGroup = ChatObject.isChannelAndNotMegaGroup(currentChat); boolean isChannelAndNotMegaGroup = ChatObject.isChannelAndNotMegaGroup(currentChat);
String finalString; String finalString;
if (availableReactions == null || availableReactions instanceof TLRPC.TL_chatReactionsNone) { if (availableReactions == null || availableReactions instanceof TLRPC.TL_chatReactionsNone) {
finalString = LocaleController.getString("ReactionsOff", R.string.ReactionsOff); finalString = getString("ReactionsOff", R.string.ReactionsOff);
} else if (availableReactions instanceof TLRPC.TL_chatReactionsSome) { } else if (availableReactions instanceof TLRPC.TL_chatReactionsSome) {
TLRPC.TL_chatReactionsSome someReactions = (TLRPC.TL_chatReactionsSome) availableReactions; TLRPC.TL_chatReactionsSome someReactions = (TLRPC.TL_chatReactionsSome) availableReactions;
int count = 0; int count = 0;
@ -2039,16 +2015,16 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image
} }
} }
if (isChannelAndNotMegaGroup) { if (isChannelAndNotMegaGroup) {
finalString = count == 0 ? LocaleController.getString("ReactionsOff", R.string.ReactionsOff) : String.valueOf(count); finalString = count == 0 ? getString("ReactionsOff", R.string.ReactionsOff) : String.valueOf(count);
} else { } else {
int reacts = Math.min(getMediaDataController().getEnabledReactionsList().size(), count); int reacts = Math.min(getMediaDataController().getEnabledReactionsList().size(), count);
finalString = reacts == 0 ? LocaleController.getString("ReactionsOff", R.string.ReactionsOff) : finalString = reacts == 0 ? getString("ReactionsOff", R.string.ReactionsOff) :
LocaleController.formatString("ReactionsCount", R.string.ReactionsCount, reacts, getMediaDataController().getEnabledReactionsList().size()); LocaleController.formatString("ReactionsCount", R.string.ReactionsCount, reacts, getMediaDataController().getEnabledReactionsList().size());
} }
} else { } else {
finalString = LocaleController.getString("ReactionsAll", R.string.ReactionsAll); finalString = getString("ReactionsAll", R.string.ReactionsAll);
} }
reactionsCell.setTextAndValueAndIcon(LocaleController.getString("Reactions", R.string.Reactions), finalString, animated, R.drawable.msg_reactions2, true); reactionsCell.setTextAndValueAndIcon(getString("Reactions", R.string.Reactions), finalString, animated, R.drawable.msg_reactions2, true);
} }
@Override @Override

View file

@ -4,15 +4,19 @@ import android.animation.Animator;
import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet; import android.animation.AnimatorSet;
import android.animation.ValueAnimator; import android.animation.ValueAnimator;
import android.graphics.Bitmap;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Paint; import android.graphics.Paint;
import android.graphics.Path; import android.graphics.Path;
import android.graphics.PorterDuff; import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.PorterDuffXfermode; import android.graphics.PorterDuffXfermode;
import android.graphics.RectF; import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.text.Layout; import android.text.Layout;
import android.text.StaticLayout; import android.text.StaticLayout;
import android.text.TextPaint; import android.text.TextPaint;
import android.text.TextUtils;
import android.view.Gravity; import android.view.Gravity;
import android.view.HapticFeedbackConstants; import android.view.HapticFeedbackConstants;
import android.view.View; import android.view.View;
@ -29,9 +33,14 @@ import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserConfig;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.AnimatedEmojiDrawable;
import org.telegram.ui.Components.AvatarDrawable; import org.telegram.ui.Components.AvatarDrawable;
import org.telegram.ui.Components.CombinedDrawable;
import org.telegram.ui.Components.CounterView; import org.telegram.ui.Components.CounterView;
import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.Forum.ForumUtilities;
import org.telegram.ui.Components.LetterDrawable;
import org.telegram.ui.Components.StaticLayoutEx;
import java.util.ArrayList; import java.util.ArrayList;
@ -56,8 +65,10 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC
int layout1Width; int layout1Width;
int layout2Width; int layout2Width;
ImageReceiver imageReceiver = new ImageReceiver(); private final ImageReceiver imageReceiver;
TLRPC.Chat nextChat; TLRPC.Chat nextChat;
TLRPC.TL_forumTopic nextTopic;
private long lastWidthTopicId = 0L;
AnimatorSet showReleaseAnimator; AnimatorSet showReleaseAnimator;
@ -74,26 +85,34 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC
private final View fragmentView; private final View fragmentView;
public long lastShowingReleaseTime; public long lastShowingReleaseTime;
boolean recommendedChannel;
boolean drawFolderBackground; boolean drawFolderBackground;
private final boolean isTopic;
Runnable onAnimationFinishRunnable; Runnable onAnimationFinishRunnable;
public long nextDialogId; public long nextDialogId;
View parentView; View parentView;
private boolean visibleCounterDrawable = true;
CounterView.CounterDrawable counterDrawable = new CounterView.CounterDrawable(null, true, null); CounterView.CounterDrawable counterDrawable = new CounterView.CounterDrawable(null, true, null);
int params[] = new int[3]; int params[] = new int[3];
private final int currentAccount; private final int currentAccount;
private final int folderId; private final int folderId;
private final int filterId; private final int filterId;
private final long topicId;
private final long currentDialog; private final long currentDialog;
private final Theme.ResourcesProvider resourcesProvider; private final Theme.ResourcesProvider resourcesProvider;
private AnimatedEmojiDrawable animatedEmojiDrawable;
public ChatPullingDownDrawable(int currentAccount, View fragmentView, long currentDialog, int folderId, int filterId, Theme.ResourcesProvider resourcesProvider) { public ChatPullingDownDrawable(int currentAccount, View fragmentView, long currentDialog, int folderId, int filterId, long topicId, Theme.ResourcesProvider resourcesProvider) {
this.fragmentView = fragmentView; this.fragmentView = fragmentView;
this.currentAccount = currentAccount; this.currentAccount = currentAccount;
this.currentDialog = currentDialog; this.currentDialog = currentDialog;
this.folderId = folderId; this.folderId = folderId;
this.filterId = filterId; this.filterId = filterId;
this.topicId = topicId;
this.isTopic = MessagesController.getInstance(currentAccount).isForum(currentDialog);
this.resourcesProvider = resourcesProvider; this.resourcesProvider = resourcesProvider;
this.imageReceiver = new ImageReceiver(fragmentView);
arrowPaint.setStrokeWidth(AndroidUtilities.dpf2(2.8f)); arrowPaint.setStrokeWidth(AndroidUtilities.dpf2(2.8f));
arrowPaint.setStrokeCap(Paint.Cap.ROUND); arrowPaint.setStrokeCap(Paint.Cap.ROUND);
@ -109,11 +128,37 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC
xRefPaint.setColor(0xff000000); xRefPaint.setColor(0xff000000);
xRefPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); xRefPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
public void updateDialog(TLRPC.Chat chat) {
if (chat == null) {
updateDialog(); updateDialog();
return;
}
nextDialogId = -chat.id;
drawFolderBackground = params[0] == 1;
dialogFolderId = params[1];
dialogFilterId = params[2];
emptyStub = false;
nextChat = chat;
AvatarDrawable avatarDrawable = new AvatarDrawable();
avatarDrawable.setInfo(currentAccount, nextChat);
imageReceiver.setImage(ImageLocation.getForChat(nextChat, ImageLocation.TYPE_SMALL), "50_50", avatarDrawable, null, UserConfig.getInstance(0).getCurrentUser(), 0);
MessagesController.getInstance(currentAccount).ensureMessagesLoaded(-chat.id, 0, null);
TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).getDialog(-chat.id);
final int count = dialog == null ? 0 : dialog.unread_count;
counterDrawable.setCount(count, false);
visibleCounterDrawable = count > 0;
recommendedChannel = true;
nextTopic = null;
} }
public void updateDialog() { public void updateDialog() {
recommendedChannel = false;
nextTopic = null;
TLRPC.Dialog dialog = getNextUnreadDialog(currentDialog, folderId, filterId, true, params); TLRPC.Dialog dialog = getNextUnreadDialog(currentDialog, folderId, filterId, true, params);
if (dialog != null) { if (dialog != null) {
nextDialogId = dialog.id; nextDialogId = dialog.id;
@ -123,13 +168,15 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC
emptyStub = false; emptyStub = false;
nextChat = MessagesController.getInstance(currentAccount).getChat(-dialog.id); nextChat = MessagesController.getInstance(currentAccount).getChat(-dialog.id);
if (nextChat == null) { if (nextChat == null) {
MessagesController.getInstance(currentAccount).getChat(dialog.id); nextChat = MessagesController.getInstance(currentAccount).getChat(dialog.id);
} }
AvatarDrawable avatarDrawable = new AvatarDrawable(); AvatarDrawable avatarDrawable = new AvatarDrawable();
avatarDrawable.setInfo(currentAccount, nextChat); avatarDrawable.setInfo(currentAccount, nextChat);
imageReceiver.setImage(ImageLocation.getForChat(nextChat, ImageLocation.TYPE_SMALL), "50_50", avatarDrawable, null, UserConfig.getInstance(0).getCurrentUser(), 0); imageReceiver.setImage(ImageLocation.getForChat(nextChat, ImageLocation.TYPE_SMALL), "50_50", avatarDrawable, null, UserConfig.getInstance(0).getCurrentUser(), 0);
MessagesController.getInstance(currentAccount).ensureMessagesLoaded(dialog.id, 0, null); MessagesController.getInstance(currentAccount).ensureMessagesLoaded(dialog.id, 0, null);
counterDrawable.setCount(dialog.unread_count, false); final int count = dialog.unread_count;
counterDrawable.setCount(count, false);
visibleCounterDrawable = count > 0;
} else { } else {
nextChat = null; nextChat = null;
drawFolderBackground = false; drawFolderBackground = false;
@ -137,28 +184,92 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC
} }
} }
public void updateTopic() {
recommendedChannel = false;
drawFolderBackground = false;
nextChat = null;
nextDialogId = 0;
imageReceiver.clearImage();
TLRPC.TL_forumTopic topic = getNextUnreadTopic(-currentDialog);
if (topic != null) {
emptyStub = false;
nextTopic = topic;
Drawable forumIcon;
if (topic.id == 1) {
if (parentView != null && animatedEmojiDrawable != null) {
animatedEmojiDrawable.removeView(parentView);
}
animatedEmojiDrawable = null;
forumIcon = ForumUtilities.createGeneralTopicDrawable(fragmentView.getContext(), 1f, getThemedColor(Theme.key_chat_inMenu), false);
imageReceiver.setImageBitmap(forumIcon);
} else if (topic.icon_emoji_id != 0) {
if (animatedEmojiDrawable == null || animatedEmojiDrawable.getDocumentId() != topic.icon_emoji_id) {
if (animatedEmojiDrawable != null && parentView != null) {
animatedEmojiDrawable.removeView(parentView);
}
animatedEmojiDrawable = new AnimatedEmojiDrawable(AnimatedEmojiDrawable.CACHE_TYPE_FORUM_TOPIC_LARGE, currentAccount, topic.icon_emoji_id);
animatedEmojiDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_serviceText), PorterDuff.Mode.SRC_IN));
}
if (animatedEmojiDrawable != null && parentView != null) {
animatedEmojiDrawable.addView(parentView);
}
imageReceiver.setImageBitmap((Bitmap) null);
} else {
if (parentView != null && animatedEmojiDrawable != null) {
animatedEmojiDrawable.removeView(parentView);
}
animatedEmojiDrawable = null;
forumIcon = ForumUtilities.createTopicDrawable(topic, false);
imageReceiver.setImageBitmap(forumIcon);
}
final int count = topic.unread_count;
counterDrawable.setCount(count, false);
visibleCounterDrawable = count > 0;
} else {
nextTopic = null;
emptyStub = true;
}
}
public void setWidth(int width) { public void setWidth(int width) {
if (width != lastWidth) { if (width != lastWidth || (isTopic && nextTopic != null && lastWidthTopicId != nextTopic.id)) {
circleRadius = AndroidUtilities.dp(56) / 2f; circleRadius = AndroidUtilities.dp(56) / 2f;
lastWidth = width; lastWidth = width;
String nameStr = nextChat != null ? nextChat.title : LocaleController.getString("SwipeToGoNextChannelEnd", R.string.SwipeToGoNextChannelEnd); CharSequence nameStr;
chatNameWidth = (int) textPaint.measureText(nameStr); if (nextChat != null) {
nameStr = nextChat.title;
} else if (nextTopic != null) {
nameStr = nextTopic.title;
} else if (isTopic) {
String forumName = MessagesController.getInstance(currentAccount).getChat(-currentDialog).title;
nameStr = LocaleController.formatString(R.string.SwipeToGoNextTopicEnd, forumName);
} else {
nameStr = LocaleController.getString(R.string.SwipeToGoNextChannelEnd);
}
chatNameWidth = (int) textPaint.measureText(nameStr, 0, nameStr.length());
chatNameWidth = Math.min(chatNameWidth, lastWidth - AndroidUtilities.dp(60)); chatNameWidth = Math.min(chatNameWidth, lastWidth - AndroidUtilities.dp(60));
chatNameLayout = new StaticLayout(nameStr, textPaint, chatNameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); chatNameLayout = StaticLayoutEx.createStaticLayout(nameStr, textPaint, chatNameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false, TextUtils.TruncateAt.END, chatNameWidth, 1);
String str1 = null; String str1 = null;
String str2 = null; String str2 = null;
if (drawFolderBackground && dialogFolderId != folderId && dialogFolderId != 0) { if (recommendedChannel) {
str1 = LocaleController.getString("SwipeToGoNextArchive", R.string.SwipeToGoNextArchive); str1 = LocaleController.getString(R.string.SwipeToGoNextRecommendedChannel);
str2 = LocaleController.getString("ReleaseToGoNextArchive", R.string.ReleaseToGoNextArchive); str2 = LocaleController.getString(R.string.ReleaseToGoNextRecommendedChannel);
} else if (isTopic) {
str1 = LocaleController.getString(R.string.SwipeToGoNextUnreadTopic);
str2 = LocaleController.getString(R.string.ReleaseToGoNextUnreadTopic);
} else if (drawFolderBackground && dialogFolderId != folderId && dialogFolderId != 0) {
str1 = LocaleController.getString(R.string.SwipeToGoNextArchive);
str2 = LocaleController.getString(R.string.ReleaseToGoNextArchive);
} else if (drawFolderBackground) { } else if (drawFolderBackground) {
str1 = LocaleController.getString("SwipeToGoNextFolder", R.string.SwipeToGoNextFolder); str1 = LocaleController.getString(R.string.SwipeToGoNextFolder);
str2 = LocaleController.getString("ReleaseToGoNextFolder", R.string.ReleaseToGoNextFolder); str2 = LocaleController.getString(R.string.ReleaseToGoNextFolder);
} else { } else {
str1 = LocaleController.getString("SwipeToGoNextChannel", R.string.SwipeToGoNextChannel); str1 = LocaleController.getString(R.string.SwipeToGoNextChannel);
str2 = LocaleController.getString("ReleaseToGoNextChannel", R.string.ReleaseToGoNextChannel); str2 = LocaleController.getString(R.string.ReleaseToGoNextChannel);
} }
layout1Width = (int) textPaint2.measureText(str1); layout1Width = (int) textPaint2.measureText(str1);
layout1Width = Math.min(layout1Width, lastWidth - AndroidUtilities.dp(60)); layout1Width = Math.min(layout1Width, lastWidth - AndroidUtilities.dp(60));
@ -176,12 +287,20 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC
imageReceiver.setRoundRadius((int) (AndroidUtilities.dp(40) / 2f)); imageReceiver.setRoundRadius((int) (AndroidUtilities.dp(40) / 2f));
counterDrawable.setSize(AndroidUtilities.dp(28), AndroidUtilities.dp(100)); counterDrawable.setSize(AndroidUtilities.dp(28), AndroidUtilities.dp(100));
if (isTopic) {
lastWidthTopicId = nextTopic == null ? 0 : nextTopic.id;
}
} }
} }
public void draw(Canvas canvas, View parent, float progress, float alpha) { public void draw(Canvas canvas, View parent, float progress, float alpha) {
if (this.parentView != parent) {
this.parentView = parent; this.parentView = parent;
if (animatedEmojiDrawable != null) {
animatedEmojiDrawable.addView(parent);
}
}
counterDrawable.setParent(parent); counterDrawable.setParent(parent);
int oldAlpha, oldAlpha1, oldAlpha2, oldAlpha3; int oldAlpha, oldAlpha1, oldAlpha2, oldAlpha3;
float offset = AndroidUtilities.dp(110) * progress; float offset = AndroidUtilities.dp(110) * progress;
@ -287,12 +406,21 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC
if (!emptyStub && size > 0) { if (!emptyStub && size > 0) {
float top = (-AndroidUtilities.dp(8) - AndroidUtilities.dp2(8) * progress - size) * (1f - swipeToReleaseProgress) + (-offset + AndroidUtilities.dp(4)) * swipeToReleaseProgress + bounceOffset; float top = (-AndroidUtilities.dp(8) - AndroidUtilities.dp2(8) * progress - size) * (1f - swipeToReleaseProgress) + (-offset + AndroidUtilities.dp(4)) * swipeToReleaseProgress + bounceOffset;
imageReceiver.setRoundRadius((int) (size / 2f)); ImageReceiver finalImageReceiver;
imageReceiver.setImageCoords(cx - size / 2f, top, size, size); if (animatedEmojiDrawable != null && animatedEmojiDrawable.getImageReceiver() != null) {
finalImageReceiver = animatedEmojiDrawable.getImageReceiver();
} else {
finalImageReceiver = imageReceiver;
}
finalImageReceiver.setRoundRadius((int) (size / 2f));
finalImageReceiver.setImageCoords(cx - size / 2f, top, size, size);
if (isTopic && finalImageReceiver.getDrawable() != null && finalImageReceiver.getDrawable() instanceof CombinedDrawable && ((CombinedDrawable) finalImageReceiver.getDrawable()).getIcon() instanceof LetterDrawable) {
((LetterDrawable) ((CombinedDrawable) finalImageReceiver.getDrawable()).getIcon()).scale = progress;
}
if (swipeToReleaseProgress > 0) { if (swipeToReleaseProgress > 0 && visibleCounterDrawable) {
canvas.saveLayerAlpha(imageReceiver.getImageX(), imageReceiver.getImageY(), imageReceiver.getImageX() + imageReceiver.getImageWidth(), imageReceiver.getImageY() + imageReceiver.getImageHeight(), 255, Canvas.ALL_SAVE_FLAG); canvas.saveLayerAlpha(finalImageReceiver.getImageX(), finalImageReceiver.getImageY(), finalImageReceiver.getImageX() + finalImageReceiver.getImageWidth(), finalImageReceiver.getImageY() + finalImageReceiver.getImageHeight(), 255, Canvas.ALL_SAVE_FLAG);
imageReceiver.draw(canvas); finalImageReceiver.draw(canvas);
canvas.scale(swipeToReleaseProgress, swipeToReleaseProgress, cx + AndroidUtilities.dp(12) + counterDrawable.getCenterX(), top - AndroidUtilities.dp(6) + AndroidUtilities.dp(14)); canvas.scale(swipeToReleaseProgress, swipeToReleaseProgress, cx + AndroidUtilities.dp(12) + counterDrawable.getCenterX(), top - AndroidUtilities.dp(6) + AndroidUtilities.dp(14));
canvas.translate(cx + AndroidUtilities.dp(12), top - AndroidUtilities.dp(6)); canvas.translate(cx + AndroidUtilities.dp(12), top - AndroidUtilities.dp(6));
counterDrawable.updateBackgroundRect(); counterDrawable.updateBackgroundRect();
@ -306,8 +434,7 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC
counterDrawable.draw(canvas); counterDrawable.draw(canvas);
canvas.restore(); canvas.restore();
} else { } else {
finalImageReceiver.draw(canvas);
imageReceiver.draw(canvas);
} }
} }
@ -476,12 +603,18 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC
public void onAttach() { public void onAttach() {
imageReceiver.onAttachedToWindow(); imageReceiver.onAttachedToWindow();
if (animatedEmojiDrawable != null && parentView != null) {
animatedEmojiDrawable.addView(parentView);
}
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.updateInterfaces); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.updateInterfaces);
} }
public void onDetach() { public void onDetach() {
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.updateInterfaces); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.updateInterfaces);
imageReceiver.onDetachedFromWindow(); imageReceiver.onDetachedFromWindow();
if (animatedEmojiDrawable != null && parentView != null) {
animatedEmojiDrawable.removeView(parentView);
}
lastProgress = 0; lastProgress = 0;
lastHapticTime = 0; lastHapticTime = 0;
} }
@ -491,7 +624,9 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC
if (nextDialogId != 0) { if (nextDialogId != 0) {
TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(nextDialogId); TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(nextDialogId);
if (dialog != null) { if (dialog != null) {
counterDrawable.setCount(dialog.unread_count, true); final int count = dialog.unread_count;
counterDrawable.setCount(count, true);
visibleCounterDrawable = count > 0;
if (parentView != null) { if (parentView != null) {
parentView.invalidate(); parentView.invalidate();
} }
@ -568,10 +703,28 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC
return null; return null;
} }
private TLRPC.TL_forumTopic getNextUnreadTopic(long currentDialogId) {
ArrayList<TLRPC.TL_forumTopic> topics = MessagesController.getInstance(currentAccount).getTopicsController().getTopics(currentDialogId);
TLRPC.TL_forumTopic nextUnreadTopic = null;
if (topics != null && topics.size() > 1) {
for (int i = 0; i < topics.size(); i++) {
TLRPC.TL_forumTopic topic = topics.get(i);
if (topic.id != topicId && !topic.hidden && topic.unread_count > 0 && (nextUnreadTopic == null || topic.topMessage.date > nextUnreadTopic.topMessage.date)) {
nextUnreadTopic = topic;
}
}
}
return nextUnreadTopic;
}
public long getChatId() { public long getChatId() {
return nextChat.id; return nextChat.id;
} }
public TLRPC.TL_forumTopic getTopic() {
return nextTopic;
}
public void drawBottomPanel(Canvas canvas, int top, int bottom, int width) { public void drawBottomPanel(Canvas canvas, int top, int bottom, int width) {
if (showBottomPanel && progressToBottomPanel != 1f) { if (showBottomPanel && progressToBottomPanel != 1f) {
progressToBottomPanel += 16f / 150f; progressToBottomPanel += 16f / 150f;

View file

@ -111,6 +111,7 @@ public class ChatRightsEditActivity extends BaseFragment {
private TLRPC.TL_chatAdminRights myAdminRights; private TLRPC.TL_chatAdminRights myAdminRights;
private TLRPC.TL_chatBannedRights bannedRights; private TLRPC.TL_chatBannedRights bannedRights;
private TLRPC.TL_chatBannedRights defaultBannedRights; private TLRPC.TL_chatBannedRights defaultBannedRights;
public boolean banning;
private String currentBannedRights = ""; private String currentBannedRights = "";
private String currentRank; private String currentRank;
private String initialRank; private String initialRank;
@ -595,6 +596,7 @@ public class ChatRightsEditActivity extends BaseFragment {
} }
finishFragment(); finishFragment();
} else if (currentType == TYPE_BANNED) { } else if (currentType == TYPE_BANNED) {
banning = true;
bannedRights = new TLRPC.TL_chatBannedRights(); bannedRights = new TLRPC.TL_chatBannedRights();
bannedRights.view_messages = true; bannedRights.view_messages = true;
bannedRights.send_media = true; bannedRights.send_media = true;
@ -2067,6 +2069,9 @@ public class ChatRightsEditActivity extends BaseFragment {
bannedRights.send_photos = !enabled; bannedRights.send_photos = !enabled;
bannedRights.send_videos = !enabled; bannedRights.send_videos = !enabled;
bannedRights.send_stickers = !enabled; bannedRights.send_stickers = !enabled;
bannedRights.send_gifs = !enabled;
bannedRights.send_games = !enabled;
bannedRights.send_inline = !enabled;
bannedRights.send_audios = !enabled; bannedRights.send_audios = !enabled;
bannedRights.send_docs = !enabled; bannedRights.send_docs = !enabled;
bannedRights.send_voices = !enabled; bannedRights.send_voices = !enabled;

View file

@ -449,7 +449,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente
} }
} else if (type == TYPE_ADMIN) { } else if (type == TYPE_ADMIN) {
if (ChatObject.isChannel(currentChat) && currentChat.megagroup && !currentChat.gigagroup && (info == null || info.participants_count <= 200 || !isChannel && info.can_set_stickers)) { if (ChatObject.isChannel(currentChat) && currentChat.megagroup && !currentChat.gigagroup && (info == null || info.participants_count <= 200 || !isChannel && info.can_set_stickers)) {
recentActionsRow = rowCount++; // recentActionsRow = rowCount++;
if (ChatObject.hasAdminRights(currentChat)) { if (ChatObject.hasAdminRights(currentChat)) {
antiSpamRow = rowCount++; antiSpamRow = rowCount++;
antiSpamInfoRow = rowCount++; antiSpamInfoRow = rowCount++;

View file

@ -0,0 +1,397 @@
package org.telegram.ui.Components;
import static org.telegram.messenger.AndroidUtilities.dp;
import static org.telegram.messenger.LocaleController.getString;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import androidx.collection.LongSparseArray;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.DialogObject;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.R;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.CheckBoxCell;
import org.telegram.ui.Components.Premium.boosts.cells.selector.SelectorBtnCell;
import org.telegram.ui.Stories.recorder.ButtonWithCounterView;
import java.util.ArrayList;
public class AdminLogFilterAlert2 extends BottomSheetWithRecyclerListView {
private UniversalAdapter adapter;
private TLRPC.TL_channelAdminLogEventsFilter currentFilter = new TLRPC.TL_channelAdminLogEventsFilter();
private ArrayList<TLRPC.ChannelParticipant> currentAdmins;
private LongSparseArray<TLRPC.User> selectedAdmins;
private boolean isMegagroup;
private final ButtonWithCounterView actionButton;
private final SelectorBtnCell buttonContainer;
public AdminLogFilterAlert2(BaseFragment fragment, TLRPC.TL_channelAdminLogEventsFilter filter, LongSparseArray<TLRPC.User> admins, boolean megagroup) {
super(fragment, false, false);
topPadding = 0.6f;
fixNavigationBar();
setSlidingActionBar();
setShowHandle(true);
if (filter != null) {
currentFilter.join = filter.join;
currentFilter.leave = filter.leave;
currentFilter.invite = filter.invite;
currentFilter.ban = filter.ban;
currentFilter.unban = filter.unban;
currentFilter.kick = filter.kick;
currentFilter.unkick = filter.unkick;
currentFilter.promote = filter.promote;
currentFilter.demote = filter.demote;
currentFilter.info = filter.info;
currentFilter.settings = filter.settings;
currentFilter.pinned = filter.pinned;
currentFilter.edit = filter.edit;
currentFilter.delete = filter.delete;
currentFilter.group_call = filter.group_call;
currentFilter.invites = filter.invites;
} else {
currentFilter.join = true;
currentFilter.leave = true;
currentFilter.invite = true;
currentFilter.ban = true;
currentFilter.unban = true;
currentFilter.kick = true;
currentFilter.unkick = true;
currentFilter.promote = true;
currentFilter.demote = true;
currentFilter.info = true;
currentFilter.settings = true;
currentFilter.pinned = true;
currentFilter.edit = true;
currentFilter.delete = true;
currentFilter.group_call = true;
currentFilter.invites = true;
}
if (admins != null) {
selectedAdmins = admins.clone();
}
isMegagroup = megagroup;
adapter.update(false);
DefaultItemAnimator itemAnimator = new DefaultItemAnimator();
itemAnimator.setSupportsChangeAnimations(false);
itemAnimator.setDelayAnimations(false);
itemAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT);
itemAnimator.setDurations(350);
recyclerListView.setItemAnimator(itemAnimator);
recyclerListView.setOnItemClickListener((view, position, x, y) -> {
onClick(adapter.getItem(position - 1), view, x);
});
buttonContainer = new SelectorBtnCell(getContext(), resourcesProvider, null);
buttonContainer.setClickable(true);
buttonContainer.setOrientation(LinearLayout.VERTICAL);
buttonContainer.setPadding(dp(10), dp(10), dp(10), dp(10));
buttonContainer.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground, resourcesProvider));
actionButton = new ButtonWithCounterView(getContext(), resourcesProvider);
actionButton.setText(getString(R.string.EventLogFilterApply), false);
actionButton.setOnClickListener(v -> {
if (currentFilter.join &&
currentFilter.leave &&
currentFilter.invite &&
currentFilter.ban &&
currentFilter.unban &&
currentFilter.kick &&
currentFilter.unkick &&
currentFilter.promote &&
currentFilter.demote &&
currentFilter.info &&
currentFilter.settings &&
currentFilter.pinned &&
currentFilter.edit &&
currentFilter.delete &&
currentFilter.group_call &&
currentFilter.invites) {
currentFilter = null;
}
if (selectedAdmins != null && currentAdmins != null && selectedAdmins.size() >= currentAdmins.size()) {
selectedAdmins = null;
}
delegate.didSelectRights(currentFilter, selectedAdmins);
dismiss();
});
buttonContainer.addView(actionButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.FILL_HORIZONTAL));
containerView.addView(buttonContainer, LayoutHelper.createFrameMarginPx(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.FILL_HORIZONTAL, backgroundPaddingLeft, 0, backgroundPaddingLeft, 0));
recyclerListView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, dp(68));
}
@Override
protected CharSequence getTitle() {
return getString(R.string.EventLog);
}
@Override
protected RecyclerListView.SelectionAdapter createAdapter(RecyclerListView listView) {
return adapter = new UniversalAdapter(listView, getContext(), currentAccount, 0, true, this::fillItems, resourcesProvider);
}
private final static int FILTER_SECTION_MEMBERS = 2;
private final static int FILTER_NEW_ADMINS = 3;
private final static int FILTER_RESTRICTIONS = 4;
private final static int FILTER_NEW_MEMBERS = 5;
private final static int FILTER_MEMBERS_LEFT = 6;
private final static int FILTER_SECTION_SETTINGS = 7;
private final static int FILTER_INFO = 8;
private final static int FILTER_INVITES = 9;
private final static int FILTER_CALLS = 10;
private final static int FILTER_SECTION_MESSAGES = 11;
private final static int FILTER_DELETE = 12;
private final static int FILTER_EDIT = 13;
private final static int FILTER_PIN = 14;
private final static int BUTTON_ALL_ADMINS = 15;
private boolean sectionMembersExpanded = false;
private boolean sectionSettingsExpanded = false;
private boolean sectionMessagesExpanded = false;
private String getGroupCount(int a) {
switch (a) {
case 0: return (
(currentFilter.promote || currentFilter.demote ? 1 : 0) +
(isMegagroup && (currentFilter.kick || currentFilter.ban || currentFilter.unkick || currentFilter.unban) ? 1 : 0) +
(currentFilter.invite || currentFilter.join ? 1 : 0) +
(currentFilter.leave ? 1 : 0) +
"/" + (isMegagroup ? 4 : 3)
);
case 1: return (
(currentFilter.info || currentFilter.settings ? 1 : 0) +
(currentFilter.invites ? 1 : 0) +
(currentFilter.group_call ? 1 : 0) +
"/3"
);
case 2:
default: return (
(currentFilter.delete ? 1 : 0) +
(currentFilter.edit ? 1 : 0) +
(currentFilter.pinned ? 1 : 0) +
"/3"
);
}
}
private View.OnClickListener getGroupClick(int a) {
return v -> {
saveScrollPosition();
switch (a) {
case 0:
sectionMembersExpanded = !sectionMembersExpanded;
break;
case 1:
sectionSettingsExpanded = !sectionSettingsExpanded;
break;
case 2:
sectionMessagesExpanded = !sectionMessagesExpanded;
break;
}
adapter.update(true);
applyScrolledPosition();
};
}
public void fillItems(ArrayList<UItem> items, UniversalAdapter adapter) {
if (currentFilter == null) return;
items.add(UItem.asHeader(getString(R.string.EventLogFilterByActions)));
items.add(UItem.asRoundGroupCheckbox(FILTER_SECTION_MEMBERS, getString(R.string.EventLogFilterSectionMembers), getGroupCount(0)).setChecked(
currentFilter.promote || currentFilter.demote ||
isMegagroup && (currentFilter.kick || currentFilter.ban || currentFilter.unkick || currentFilter.unban) ||
currentFilter.invite || currentFilter.join ||
currentFilter.leave
).setCollapsed(!sectionMembersExpanded).setClickCallback(getGroupClick(0)));
if (sectionMembersExpanded) {
items.add(UItem.asRoundCheckbox(FILTER_NEW_ADMINS, getString(R.string.EventLogFilterSectionAdmin)).pad().setChecked(currentFilter.promote || currentFilter.demote));
if (isMegagroup) {
items.add(UItem.asRoundCheckbox(FILTER_RESTRICTIONS, getString(R.string.EventLogFilterNewRestrictions)).pad().setChecked(currentFilter.kick || currentFilter.ban || currentFilter.unkick || currentFilter.unban));
}
items.add(UItem.asRoundCheckbox(FILTER_NEW_MEMBERS, getString(R.string.EventLogFilterNewMembers)).pad().setChecked(currentFilter.invite || currentFilter.join));
items.add(UItem.asRoundCheckbox(FILTER_MEMBERS_LEFT, getString(R.string.EventLogFilterLeavingMembers2)).pad().setChecked(currentFilter.leave));
}
items.add(UItem.asRoundGroupCheckbox(FILTER_SECTION_SETTINGS, getString(isMegagroup ? R.string.EventLogFilterSectionGroupSettings : R.string.EventLogFilterSectionChannelSettings), getGroupCount(1)).setChecked(
currentFilter.info || currentFilter.settings ||
currentFilter.invites ||
currentFilter.group_call
).setCollapsed(!sectionSettingsExpanded).setClickCallback(getGroupClick(1)));
if (sectionSettingsExpanded) {
items.add(UItem.asRoundCheckbox(FILTER_INFO, getString(isMegagroup ? R.string.EventLogFilterGroupInfo : R.string.EventLogFilterChannelInfo)).pad().setChecked(currentFilter.info || currentFilter.settings));
items.add(UItem.asRoundCheckbox(FILTER_INVITES, getString(R.string.EventLogFilterInvites)).pad().setChecked(currentFilter.invites));
items.add(UItem.asRoundCheckbox(FILTER_CALLS, getString(R.string.EventLogFilterCalls)).pad().setChecked(currentFilter.group_call));
}
items.add(UItem.asRoundGroupCheckbox(FILTER_SECTION_MESSAGES, getString(R.string.EventLogFilterSectionMessages), getGroupCount(2)).setChecked(
currentFilter.delete || currentFilter.edit || currentFilter.pinned
).setCollapsed(!sectionMessagesExpanded).setClickCallback(getGroupClick(2)));
if (sectionMessagesExpanded) {
items.add(UItem.asRoundCheckbox(FILTER_DELETE, getString(R.string.EventLogFilterDeletedMessages)).pad().setChecked(currentFilter.delete));
items.add(UItem.asRoundCheckbox(FILTER_EDIT, getString(R.string.EventLogFilterEditedMessages)).pad().setChecked(currentFilter.edit));
items.add(UItem.asRoundCheckbox(FILTER_PIN, getString(R.string.EventLogFilterPinnedMessages)).pad().setChecked(currentFilter.pinned));
}
items.add(UItem.asShadow(null));
items.add(UItem.asHeader(getString(R.string.EventLogFilterByAdmins)));
items.add(UItem.asRoundCheckbox(BUTTON_ALL_ADMINS, getString(R.string.EventLogFilterByAdminsAll)).setChecked((selectedAdmins == null ? 0 : selectedAdmins.size()) >= (currentAdmins == null ? 0 : currentAdmins.size())));
if (currentAdmins != null) {
for (int i = 0; i < currentAdmins.size(); ++i) {
TLRPC.ChannelParticipant admin = currentAdmins.get(i);
final long did = DialogObject.getPeerDialogId(admin.peer);
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did);
items.add(UItem.asUserCheckbox(-1 - i, user).pad().setChecked(selectedAdmins != null && selectedAdmins.containsKey(did)));
}
}
}
public void onClick(UItem item, View view, float x) {
if (item == null) return;
if (item.viewType == UniversalAdapter.VIEW_TYPE_ROUND_GROUP_CHECKBOX || item.viewType == UniversalAdapter.VIEW_TYPE_ROUND_CHECKBOX) {
saveScrollPosition();
final boolean clickedGroupExpand = item.viewType == UniversalAdapter.VIEW_TYPE_ROUND_GROUP_CHECKBOX && (LocaleController.isRTL ? x < view.getMeasuredWidth() - dp(60) : x > dp(60));
CheckBoxCell cell = (CheckBoxCell) view;
if (!clickedGroupExpand) {
cell.setChecked(!cell.isChecked(), true);
}
switch (item.id) {
case FILTER_SECTION_MEMBERS:
if (clickedGroupExpand) {
sectionMembersExpanded = !sectionMembersExpanded;
} else {
currentFilter.promote = currentFilter.demote = currentFilter.invite = currentFilter.join = currentFilter.leave = cell.isChecked();
if (isMegagroup) {
currentFilter.kick = currentFilter.ban = currentFilter.unkick = currentFilter.unban = cell.isChecked();
}
}
break;
case FILTER_NEW_ADMINS:
currentFilter.promote = currentFilter.demote = cell.isChecked();
break;
case FILTER_RESTRICTIONS:
currentFilter.kick = currentFilter.ban = currentFilter.unkick = currentFilter.unban = cell.isChecked();
break;
case FILTER_NEW_MEMBERS:
currentFilter.invite = currentFilter.join = cell.isChecked();
break;
case FILTER_MEMBERS_LEFT:
currentFilter.leave = cell.isChecked();
break;
case FILTER_SECTION_SETTINGS:
if (clickedGroupExpand) {
sectionSettingsExpanded = !sectionSettingsExpanded;
} else {
currentFilter.info = currentFilter.settings = currentFilter.invites = currentFilter.group_call = cell.isChecked();
}
break;
case FILTER_INFO:
currentFilter.info = currentFilter.settings = cell.isChecked();
break;
case FILTER_INVITES:
currentFilter.invites = cell.isChecked();
break;
case FILTER_CALLS:
currentFilter.group_call = cell.isChecked();
break;
case FILTER_SECTION_MESSAGES:
if (clickedGroupExpand) {
sectionMessagesExpanded = !sectionMessagesExpanded;
} else {
currentFilter.delete = currentFilter.edit = currentFilter.pinned = cell.isChecked();
}
break;
case FILTER_DELETE:
currentFilter.delete = cell.isChecked();
break;
case FILTER_EDIT:
currentFilter.edit = cell.isChecked();
break;
case FILTER_PIN:
currentFilter.pinned = cell.isChecked();
break;
case BUTTON_ALL_ADMINS:
if (selectedAdmins == null) {
selectedAdmins = new LongSparseArray<>();
}
selectedAdmins.clear();
if (cell.isChecked() && currentAdmins != null) {
for (TLRPC.ChannelParticipant admin : currentAdmins) {
final long did = DialogObject.getPeerDialogId(admin.peer);
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did);
selectedAdmins.put(did, user);
}
}
break;
}
adapter.update(true);
}
if (item.id < 0) {
CheckBoxCell cell = (CheckBoxCell) view;
int index = (-item.id) - 1;
if (index < 0 || index >= currentAdmins.size()) return;
TLRPC.ChannelParticipant admin = currentAdmins.get(index);
final long did = DialogObject.getPeerDialogId(admin.peer);
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did);
if (selectedAdmins == null) {
selectedAdmins = new LongSparseArray<>();
}
if (selectedAdmins.containsKey(did)) {
selectedAdmins.remove(did);
cell.setChecked(false, true);
} else {
selectedAdmins.put(did, user);
cell.setChecked(true, true);
}
adapter.update(true);
}
}
public void setCurrentAdmins(ArrayList<TLRPC.ChannelParticipant> admins) {
currentAdmins = admins;
if (currentAdmins != null && selectedAdmins == null) {
selectedAdmins = new LongSparseArray<>();
for (TLRPC.ChannelParticipant admin : currentAdmins) {
final long did = DialogObject.getPeerDialogId(admin.peer);
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did);
selectedAdmins.put(did, user);
}
}
if (adapter != null) {
adapter.update(true);
}
}
private AdminLogFilterAlertDelegate delegate;
public interface AdminLogFilterAlertDelegate {
void didSelectRights(
TLRPC.TL_channelAdminLogEventsFilter filter,
LongSparseArray<TLRPC.User> admins
);
}
public void setAdminLogFilterAlertDelegate(AdminLogFilterAlertDelegate adminLogFilterAlertDelegate) {
delegate = adminLogFilterAlertDelegate;
}
@Override
protected void onSmoothContainerViewLayout(float ty) {
super.onSmoothContainerViewLayout(ty);
buttonContainer.setTranslationY(-ty);
}
@Override
protected boolean canDismissWithSwipe() {
return !recyclerListView.canScrollVertically(-1);
}
}

View file

@ -9,7 +9,6 @@
package org.telegram.ui.Components; package org.telegram.ui.Components;
import static org.telegram.messenger.AndroidUtilities.dp; import static org.telegram.messenger.AndroidUtilities.dp;
import static org.telegram.messenger.LocaleController.formatDateOnline;
import static org.telegram.messenger.LocaleController.getString; import static org.telegram.messenger.LocaleController.getString;
import android.Manifest; import android.Manifest;
@ -47,11 +46,9 @@ import android.text.TextUtils;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.text.style.URLSpan; import android.text.style.URLSpan;
import android.util.Base64; import android.util.Base64;
import android.util.Log;
import android.util.SparseArray; import android.util.SparseArray;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.Gravity; import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent; import android.view.KeyEvent;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.View; import android.view.View;
@ -136,8 +133,13 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class AlertsCreator { public class AlertsCreator {
public final static int PERMISSIONS_REQUEST_TOP_ICON_SIZE = 72; public final static int PERMISSIONS_REQUEST_TOP_ICON_SIZE = 72;
@ -973,7 +975,7 @@ public class AlertsCreator {
return; return;
} }
boolean enabled; boolean enabled;
boolean defaultEnabled = NotificationsController.getInstance(currentAccount).isGlobalNotificationsEnabled(did); boolean defaultEnabled = NotificationsController.getInstance(currentAccount).isGlobalNotificationsEnabled(did, false, false);
String[] descriptions = new String[]{ String[] descriptions = new String[]{
LocaleController.getString("NotificationsTurnOn", R.string.NotificationsTurnOn), LocaleController.getString("NotificationsTurnOn", R.string.NotificationsTurnOn),
@ -3733,6 +3735,7 @@ public class AlertsCreator {
if (addPrivacyText != null) { if (addPrivacyText != null) {
FrameLayout frameLayout = new FrameLayout(context); FrameLayout frameLayout = new FrameLayout(context);
LinkSpanDrawable.LinksTextView textView = new LinkSpanDrawable.LinksTextView(context); LinkSpanDrawable.LinksTextView textView = new LinkSpanDrawable.LinksTextView(context);
textView.setPadding(dp(8), 0, dp(8), 0);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
textView.setTextColor(Theme.getColor(Theme.key_dialogTextGray2, resourcesProvider)); textView.setTextColor(Theme.getColor(Theme.key_dialogTextGray2, resourcesProvider));
textView.setLinkTextColor(Theme.getColor(Theme.key_chat_messageLinkIn, resourcesProvider)); textView.setLinkTextColor(Theme.getColor(Theme.key_chat_messageLinkIn, resourcesProvider));
@ -3763,7 +3766,7 @@ public class AlertsCreator {
bottomSheetParams.transitionFromLeft = true; bottomSheetParams.transitionFromLeft = true;
bottomSheetParams.allowNestedScroll = false; bottomSheetParams.allowNestedScroll = false;
fragment.showAsSheet(new PrivacyControlActivity(PrivacyControlActivity.PRIVACY_RULES_TYPE_BIRTHDAY), bottomSheetParams); fragment.showAsSheet(new PrivacyControlActivity(PrivacyControlActivity.PRIVACY_RULES_TYPE_BIRTHDAY), bottomSheetParams);
}), true)); }), true, dp(8f / 3f), dp(.66f)));
}; };
setText.run(); setText.run();
@ -5182,6 +5185,8 @@ public class AlertsCreator {
currentColor = preferences.getInt("GroupLed", 0xff0000ff); currentColor = preferences.getInt("GroupLed", 0xff0000ff);
} else if (globalType == NotificationsController.TYPE_STORIES) { } else if (globalType == NotificationsController.TYPE_STORIES) {
currentColor = preferences.getInt("StoriesLed", 0xff0000ff); currentColor = preferences.getInt("StoriesLed", 0xff0000ff);
} else if (globalType == NotificationsController.TYPE_REACTIONS_STORIES || globalType == NotificationsController.TYPE_REACTIONS_MESSAGES) {
currentColor = preferences.getInt("ReactionsLed", 0xff0000ff);
} else { } else {
currentColor = preferences.getInt("ChannelLed", 0xff0000ff); currentColor = preferences.getInt("ChannelLed", 0xff0000ff);
} }
@ -5229,6 +5234,8 @@ public class AlertsCreator {
editor.putInt("GroupLed", selectedColor[0]); editor.putInt("GroupLed", selectedColor[0]);
} else if (globalType == NotificationsController.TYPE_STORIES) { } else if (globalType == NotificationsController.TYPE_STORIES) {
editor.putInt("StoriesLed", selectedColor[0]); editor.putInt("StoriesLed", selectedColor[0]);
} else if (globalType == NotificationsController.TYPE_REACTIONS_STORIES || globalType == NotificationsController.TYPE_REACTIONS_MESSAGES) {
editor.putInt("ReactionLed", selectedColor[0]);
} else { } else {
editor.putInt("ChannelLed", selectedColor[0]); editor.putInt("ChannelLed", selectedColor[0]);
} }
@ -5250,6 +5257,8 @@ public class AlertsCreator {
editor.putInt("GroupLed", 0); editor.putInt("GroupLed", 0);
} else if (globalType == NotificationsController.TYPE_STORIES) { } else if (globalType == NotificationsController.TYPE_STORIES) {
editor.putInt("StoriesLed", 0); editor.putInt("StoriesLed", 0);
} else if (globalType == NotificationsController.TYPE_REACTIONS_STORIES || globalType == NotificationsController.TYPE_REACTIONS_MESSAGES) {
editor.putInt("ReactionsLed", 0);
} else { } else {
editor.putInt("ChannelLed", 0); editor.putInt("ChannelLed", 0);
} }
@ -5368,6 +5377,8 @@ public class AlertsCreator {
NotificationsController.getInstance(UserConfig.selectedAccount).deleteNotificationChannelGlobal(NotificationsController.TYPE_CHANNEL); NotificationsController.getInstance(UserConfig.selectedAccount).deleteNotificationChannelGlobal(NotificationsController.TYPE_CHANNEL);
} else if (prefKeyPrefix.equals("vibrate_group")) { } else if (prefKeyPrefix.equals("vibrate_group")) {
NotificationsController.getInstance(UserConfig.selectedAccount).deleteNotificationChannelGlobal(NotificationsController.TYPE_GROUP); NotificationsController.getInstance(UserConfig.selectedAccount).deleteNotificationChannelGlobal(NotificationsController.TYPE_GROUP);
} else if (prefKeyPrefix.equals("vibrate_react")) {
NotificationsController.getInstance(UserConfig.selectedAccount).deleteNotificationChannelGlobal(NotificationsController.TYPE_REACTIONS_MESSAGES);
} else { } else {
NotificationsController.getInstance(UserConfig.selectedAccount).deleteNotificationChannelGlobal(NotificationsController.TYPE_PRIVATE); NotificationsController.getInstance(UserConfig.selectedAccount).deleteNotificationChannelGlobal(NotificationsController.TYPE_PRIVATE);
} }
@ -5385,32 +5396,37 @@ public class AlertsCreator {
return builder.create(); return builder.create();
} }
public static Dialog createLocationUpdateDialog(final Activity parentActivity, TLRPC.User user, final MessagesStorage.IntCallback callback, Theme.ResourcesProvider resourcesProvider) { public static Dialog createLocationUpdateDialog(final Activity parentActivity, boolean expand, TLRPC.User user, final MessagesStorage.IntCallback callback, Theme.ResourcesProvider resourcesProvider) {
final int[] selected = new int[1]; final int[] selected = new int[1];
String[] descriptions = new String[]{ String[] descriptions = new String[]{
LocaleController.getString("SendLiveLocationFor15m", R.string.SendLiveLocationFor15m), getString(R.string.SendLiveLocationFor15m),
LocaleController.getString("SendLiveLocationFor1h", R.string.SendLiveLocationFor1h), getString(R.string.SendLiveLocationFor1h),
LocaleController.getString("SendLiveLocationFor8h", R.string.SendLiveLocationFor8h), getString(R.string.SendLiveLocationFor8h),
getString(R.string.SendLiveLocationForever)
}; };
final LinearLayout linearLayout = new LinearLayout(parentActivity); final LinearLayout linearLayout = new LinearLayout(parentActivity);
linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(0, 0, 0, dp(4));
TextView titleTextView = new TextView(parentActivity); TextView titleTextView = new TextView(parentActivity);
if (user != null) { if (expand) {
titleTextView.setText(LocaleController.formatString("LiveLocationAlertPrivate", R.string.LiveLocationAlertPrivate, UserObject.getFirstName(user))); titleTextView.setText(LocaleController.getString(R.string.LiveLocationAlertExpandMessage));
} else if (user != null) {
titleTextView.setText(LocaleController.formatString(R.string.LiveLocationAlertPrivate, UserObject.getFirstName(user)));
} else { } else {
titleTextView.setText(LocaleController.getString("LiveLocationAlertGroup", R.string.LiveLocationAlertGroup)); titleTextView.setText(LocaleController.getString(R.string.LiveLocationAlertGroup));
} }
int textColor = resourcesProvider != null ? resourcesProvider.getColorOrDefault(Theme.key_dialogTextBlack) : Theme.getColor(Theme.key_dialogTextBlack); int textColor = resourcesProvider != null ? resourcesProvider.getColorOrDefault(Theme.key_dialogTextBlack) : Theme.getColor(Theme.key_dialogTextBlack);
titleTextView.setTextColor(textColor); titleTextView.setTextColor(textColor);
titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
titleTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); titleTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP);
linearLayout.addView(titleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 24, 0, 24, 8)); linearLayout.addView(titleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 24, (expand ? 4 : 0), 24, 8));
for (int a = 0; a < descriptions.length; a++) { for (int a = 0; a < descriptions.length; a++) {
RadioColorCell cell = new RadioColorCell(parentActivity, resourcesProvider); RadioColorCell cell = new RadioColorCell(parentActivity, resourcesProvider);
cell.heightDp = 42;
cell.setPadding(dp(4), 0, dp(4), 0); cell.setPadding(dp(4), 0, dp(4), 0);
cell.setTag(a); cell.setTag(a);
int color1 = resourcesProvider != null ? resourcesProvider.getColorOrDefault(Theme.key_radioBackground) : Theme.getColor(Theme.key_radioBackground); int color1 = resourcesProvider != null ? resourcesProvider.getColorOrDefault(Theme.key_radioBackground) : Theme.getColor(Theme.key_radioBackground);
@ -5431,8 +5447,12 @@ public class AlertsCreator {
}); });
} }
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity, resourcesProvider); AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity, resourcesProvider);
if (expand) {
builder.setTitle(getString(R.string.LiveLocationAlertExpandTitle));
} else {
int topImageColor = resourcesProvider != null ? resourcesProvider.getColorOrDefault(Theme.key_dialogTopBackground) : Theme.getColor(Theme.key_dialogTopBackground); int topImageColor = resourcesProvider != null ? resourcesProvider.getColorOrDefault(Theme.key_dialogTopBackground) : Theme.getColor(Theme.key_dialogTopBackground);
builder.setTopImage(new ShareLocationDrawable(parentActivity, 0), topImageColor); builder.setTopImage(new ShareLocationDrawable(parentActivity, 0), topImageColor);
}
builder.setView(linearLayout); builder.setView(linearLayout);
builder.setPositiveButton(LocaleController.getString("ShareFile", R.string.ShareFile), (dialog, which) -> { builder.setPositiveButton(LocaleController.getString("ShareFile", R.string.ShareFile), (dialog, which) -> {
int time; int time;
@ -5440,8 +5460,10 @@ public class AlertsCreator {
time = 15 * 60; time = 15 * 60;
} else if (selected[0] == 1) { } else if (selected[0] == 1) {
time = 60 * 60; time = 60 * 60;
} else { } else if (selected[0] == 2) {
time = 8 * 60 * 60; time = 8 * 60 * 60;
} else {
time = 0x7FFFFFFF;
} }
callback.run(time); callback.run(time);
}); });
@ -5672,6 +5694,8 @@ public class AlertsCreator {
selected[0] = preferences.getInt("priority_channel", 1); selected[0] = preferences.getInt("priority_channel", 1);
} else if (globalType == NotificationsController.TYPE_STORIES) { } else if (globalType == NotificationsController.TYPE_STORIES) {
selected[0] = preferences.getInt("priority_stories", 1); selected[0] = preferences.getInt("priority_stories", 1);
} else if (globalType == NotificationsController.TYPE_REACTIONS_MESSAGES || globalType == NotificationsController.TYPE_REACTIONS_STORIES) {
selected[0] = preferences.getInt("priority_react", 1);
} }
if (selected[0] == 4) { if (selected[0] == 4) {
selected[0] = 0; selected[0] = 0;
@ -5744,6 +5768,9 @@ public class AlertsCreator {
} else if (globalType == NotificationsController.TYPE_STORIES) { } else if (globalType == NotificationsController.TYPE_STORIES) {
editor.putInt("priority_stories", option); editor.putInt("priority_stories", option);
selected[0] = preferences.getInt("priority_stories", 1); selected[0] = preferences.getInt("priority_stories", 1);
} else if (globalType == NotificationsController.TYPE_REACTIONS_MESSAGES || globalType == NotificationsController.TYPE_REACTIONS_STORIES) {
editor.putInt("priority_react", option);
selected[0] = preferences.getInt("priority_react", 1);
} }
NotificationsController.getInstance(UserConfig.selectedAccount).deleteNotificationChannelGlobal(globalType); NotificationsController.getInstance(UserConfig.selectedAccount).deleteNotificationChannelGlobal(globalType);
} }
@ -5945,7 +5972,7 @@ public class AlertsCreator {
void didPressedNewCard(); void didPressedNewCard();
} }
public static void createDeleteMessagesAlert(BaseFragment fragment, TLRPC.User user, TLRPC.Chat chat, TLRPC.EncryptedChat encryptedChat, TLRPC.ChatFull chatInfo, long mergeDialogId, MessageObject selectedMessage, SparseArray<MessageObject>[] selectedMessages, MessageObject.GroupedMessages selectedGroup, int topicId, int mode, int loadParticipant, Runnable onDelete, Runnable hideDim, Theme.ResourcesProvider resourcesProvider) { public static void createDeleteMessagesAlert(BaseFragment fragment, TLRPC.User user, TLRPC.Chat chat, TLRPC.EncryptedChat encryptedChat, TLRPC.ChatFull chatInfo, long mergeDialogId, MessageObject selectedMessage, SparseArray<MessageObject>[] selectedMessages, MessageObject.GroupedMessages selectedGroup, int topicId, int mode, TLRPC.ChannelParticipant[] channelParticipants, Runnable onDelete, Runnable hideDim, Theme.ResourcesProvider resourcesProvider) {
final boolean scheduled = mode == ChatActivity.MODE_SCHEDULED; final boolean scheduled = mode == ChatActivity.MODE_SCHEDULED;
final boolean isSavedMessages = mode == ChatActivity.MODE_SAVED; final boolean isSavedMessages = mode == ChatActivity.MODE_SAVED;
final boolean quickReplies = mode == ChatActivity.MODE_QUICK_REPLIES; final boolean quickReplies = mode == ChatActivity.MODE_QUICK_REPLIES;
@ -5994,10 +6021,7 @@ public class AlertsCreator {
} }
} }
final boolean[] checks = new boolean[3];
final boolean[] deleteForAll = new boolean[1]; final boolean[] deleteForAll = new boolean[1];
TLRPC.User actionUser = null;
TLRPC.Chat actionChat = null;
boolean canRevokeInbox = user != null && MessagesController.getInstance(currentAccount).canRevokePmInbox; boolean canRevokeInbox = user != null && MessagesController.getInstance(currentAccount).canRevokePmInbox;
int revokeTimeLimit; int revokeTimeLimit;
if (user != null) { if (user != null) {
@ -6010,18 +6034,16 @@ public class AlertsCreator {
int myMessagesCount = 0; int myMessagesCount = 0;
boolean canDeleteInbox = encryptedChat == null && user != null && canRevokeInbox && revokeTimeLimit == 0x7fffffff; boolean canDeleteInbox = encryptedChat == null && user != null && canRevokeInbox && revokeTimeLimit == 0x7fffffff;
if (chat != null && chat.megagroup && !scheduled && !isSavedMessages) { if (chat != null && chat.megagroup && !scheduled && !isSavedMessages) {
boolean canBan = ChatObject.canBlockUsers(chat); ArrayList<MessageObject> messages = new ArrayList<>();
if (selectedMessage != null) { if (selectedMessage != null) {
if (selectedMessage.messageOwner.action == null || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionEmpty || if (selectedMessage.messageOwner.action == null || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionEmpty ||
selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser ||
selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionChatJoinedByLink || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionChatJoinedByLink ||
selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) { selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) {
if (selectedMessage.messageOwner.from_id.user_id != 0) { if (selectedGroup != null) {
actionUser = MessagesController.getInstance(currentAccount).getUser(selectedMessage.messageOwner.from_id.user_id); messages.addAll(selectedGroup.messages);
} else if (selectedMessage.messageOwner.from_id.channel_id != 0) { } else {
actionChat = MessagesController.getInstance(currentAccount).getChat(selectedMessage.messageOwner.from_id.channel_id); messages.add(selectedMessage);
} else if (selectedMessage.messageOwner.from_id.chat_id != 0) {
actionChat = MessagesController.getInstance(currentAccount).getChat(selectedMessage.messageOwner.from_id.chat_id);
} }
} }
boolean hasOutgoing = !selectedMessage.isSendError() && selectedMessage.getDialogId() == mergeDialogId && (selectedMessage.messageOwner.action == null || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionEmpty) && selectedMessage.isOut() && (currentDate - selectedMessage.messageOwner.date) <= revokeTimeLimit; boolean hasOutgoing = !selectedMessage.isSendError() && selectedMessage.getDialogId() == mergeDialogId && (selectedMessage.messageOwner.action == null || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionEmpty) && selectedMessage.isOut() && (currentDate - selectedMessage.messageOwner.date) <= revokeTimeLimit;
@ -6029,23 +6051,6 @@ public class AlertsCreator {
myMessagesCount++; myMessagesCount++;
} }
} else { } else {
long from_id = -1;
for (int a = 1; a >= 0; a--) {
long channelId = 0;
for (int b = 0; b < selectedMessages[a].size(); b++) {
MessageObject msg = selectedMessages[a].valueAt(b);
if (from_id == -1) {
from_id = msg.getFromChatId();
}
if (from_id < 0 || from_id != msg.getSenderId()) {
from_id = -2;
break;
}
}
if (from_id == -2) {
break;
}
}
for (int a = 1; a >= 0; a--) { for (int a = 1; a >= 0; a--) {
for (int b = 0; b < selectedMessages[a].size(); b++) { for (int b = 0; b < selectedMessages[a].size(); b++) {
MessageObject msg = selectedMessages[a].valueAt(b); MessageObject msg = selectedMessages[a].valueAt(b);
@ -6056,77 +6061,97 @@ public class AlertsCreator {
} }
} }
} }
messages.add(msg);
} }
} }
if (from_id != -1) {
actionUser = MessagesController.getInstance(currentAccount).getUser(from_id);
} }
long clientUserId = UserConfig.getInstance(currentAccount).getClientUserId();
ArrayList<TLObject> actionParticipants = messages
.stream()
.mapToLong(MessageObject::getFromChatId)
.distinct()
.mapToObj(fromId -> {
if (fromId > 0) {
return MessagesController.getInstance(currentAccount).getUser(fromId);
} else {
return MessagesController.getInstance(currentAccount).getChat(-fromId);
} }
if ((actionUser != null && actionUser.id != UserConfig.getInstance(currentAccount).getClientUserId()) || (actionChat != null && !ChatObject.hasAdminRights(actionChat))) { })
if (loadParticipant == 1 && !chat.creator && actionUser != null) { .filter(Objects::nonNull)
.filter(userOrChat -> {
if (userOrChat instanceof TLRPC.User) {
TLRPC.User user1 = (TLRPC.User) userOrChat;
return user1.id != clientUserId;
} else if (userOrChat instanceof TLRPC.Chat) {
TLRPC.Chat chat1 = (TLRPC.Chat) userOrChat;
return !ChatObject.hasAdminRights(chat1);
}
return false;
})
.collect(Collectors.toCollection(ArrayList::new));
if (!actionParticipants.isEmpty()) {
if (channelParticipants == null) {
final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(activity, AlertDialog.ALERT_TYPE_SPINNER)}; final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(activity, AlertDialog.ALERT_TYPE_SPINNER)};
final int participantCount = actionParticipants.size();
TLRPC.ChannelParticipant[] channelParticipantsLoad = new TLRPC.ChannelParticipant[participantCount];
int[] requestIds = new int[participantCount];
int[] responseCounter = new int[1];
for (int i = 0; i < participantCount; i++) {
TLRPC.TL_channels_getParticipant req = new TLRPC.TL_channels_getParticipant(); TLRPC.TL_channels_getParticipant req = new TLRPC.TL_channels_getParticipant();
req.channel = MessagesController.getInputChannel(chat); req.channel = MessagesController.getInputChannel(chat);
req.participant = MessagesController.getInputPeer(actionUser); req.participant = MessagesController.getInputPeer(actionParticipants.get(i));
int requestId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { final int index = i;
requestIds[i] = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
responseCounter[0]++;
requestIds[index] = 0;
if (response != null) {
TLRPC.TL_channels_channelParticipant participant = (TLRPC.TL_channels_channelParticipant) response;
channelParticipantsLoad[index] = participant.participant;
}
if (responseCounter[0] == participantCount) {
try { try {
progressDialog[0].dismiss(); progressDialog[0].dismiss();
} catch (Throwable ignore) { } catch (Throwable ignore) {
} }
progressDialog[0] = null; progressDialog[0] = null;
int loadType = 2;
if (response != null) { createDeleteMessagesAlert(fragment, user, chat, encryptedChat, chatInfo, mergeDialogId, selectedMessage, selectedMessages, selectedGroup, topicId, mode, channelParticipantsLoad, onDelete, hideDim, resourcesProvider);
TLRPC.TL_channels_channelParticipant participant = (TLRPC.TL_channels_channelParticipant) response;
if (!(participant.participant instanceof TLRPC.TL_channelParticipantAdmin || participant.participant instanceof TLRPC.TL_channelParticipantCreator)) {
loadType = 0;
} }
} else if (error != null && "USER_NOT_PARTICIPANT".equals(error.text)) {
loadType = 0;
}
createDeleteMessagesAlert(fragment, user, chat, encryptedChat, chatInfo, mergeDialogId, selectedMessage, selectedMessages, selectedGroup, topicId, mode, loadType, onDelete, hideDim, resourcesProvider);
})); }));
}
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
if (progressDialog[0] == null) { if (progressDialog[0] == null) {
return; return;
} }
progressDialog[0].setOnCancelListener(dialog -> ConnectionsManager.getInstance(currentAccount).cancelRequest(requestId, true)); progressDialog[0].setOnCancelListener(dialog -> {
for (int requestId : requestIds) {
if (requestId != 0) {
ConnectionsManager.getInstance(currentAccount).cancelRequest(requestId, true);
}
}
if (hideDim != null) {
hideDim.run();
}
});
fragment.showDialog(progressDialog[0]); fragment.showDialog(progressDialog[0]);
}, 1000); }, 1000);
return; return;
} }
FrameLayout frameLayout = new FrameLayout(activity); DeleteMessagesBottomSheet deleteMessagesBottomSheet = new DeleteMessagesBottomSheet(fragment, chat, messages, actionParticipants, channelParticipants, mergeDialogId, topicId, mode, onDelete);
int num = 0; if (hideDim != null) {
String name = actionUser != null ? ContactsController.formatName(actionUser.first_name, actionUser.last_name) : actionChat.title; deleteMessagesBottomSheet.setOnHideListener(i -> {
for (int a = 0; a < 3; a++) { hideDim.run();
if ((loadParticipant == 2 || !canBan) && a == 0) {
continue;
}
CheckBoxCell cell = new CheckBoxCell(activity, 1, resourcesProvider);
cell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
cell.setTag(a);
if (a == 0) {
cell.setText(LocaleController.getString("DeleteBanUser", R.string.DeleteBanUser), "", false, false);
} else if (a == 1) {
cell.setText(LocaleController.getString("DeleteReportSpam", R.string.DeleteReportSpam), "", false, false);
} else {
cell.setText(LocaleController.formatString("DeleteAllFrom", R.string.DeleteAllFrom, name), "", false, false);
}
cell.setPadding(LocaleController.isRTL ? dp(16) : dp(8), 0, LocaleController.isRTL ? dp(8) : dp(16), 0);
frameLayout.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.TOP | Gravity.LEFT, 0, 48 * num, 0, 0));
cell.setOnClickListener(v -> {
if (!v.isEnabled()) {
return;
}
CheckBoxCell cell13 = (CheckBoxCell) v;
Integer num1 = (Integer) cell13.getTag();
checks[num1] = !checks[num1];
cell13.setChecked(checks[num1], true);
}); });
num++;
} }
builder.setView(frameLayout); deleteMessagesBottomSheet.show();
return;
} else if (!hasNotOut && myMessagesCount > 0 && hasNonDiceMessages) { } else if (!hasNotOut && myMessagesCount > 0 && hasNonDiceMessages) {
hasDeleteForAllCheck = true; hasDeleteForAllCheck = true;
FrameLayout frameLayout = new FrameLayout(activity); FrameLayout frameLayout = new FrameLayout(activity);
@ -6146,8 +6171,6 @@ public class AlertsCreator {
}); });
builder.setView(frameLayout); builder.setView(frameLayout);
builder.setCustomViewOffset(9); builder.setCustomViewOffset(9);
} else {
actionUser = null;
} }
} else if (!scheduled && !isSavedMessages && !ChatObject.isChannel(chat) && encryptedChat == null) { } else if (!scheduled && !isSavedMessages && !ChatObject.isChannel(chat) && encryptedChat == null) {
if (user != null && user.id != UserConfig.getInstance(currentAccount).getClientUserId() && (!user.bot || user.support) || chat != null) { if (user != null && user.id != UserConfig.getInstance(currentAccount).getClientUserId() && (!user.bot || user.support) || chat != null) {
@ -6209,8 +6232,6 @@ public class AlertsCreator {
builder.setCustomViewOffset(9); builder.setCustomViewOffset(9);
} }
} }
final TLRPC.User userFinal = actionUser;
final TLRPC.Chat chatFinal = actionChat;
DialogInterface.OnClickListener deleteAction = (dialogInterface, i) -> { DialogInterface.OnClickListener deleteAction = (dialogInterface, i) -> {
ArrayList<Integer> ids = null; ArrayList<Integer> ids = null;
@ -6239,6 +6260,9 @@ public class AlertsCreator {
random_ids.add(selectedMessage.messageOwner.random_id); random_ids.add(selectedMessage.messageOwner.random_id);
} }
} }
if (mergeDialogId != 0 && selectedMessage.messageOwner.peer_id != null && selectedMessage.messageOwner.peer_id.chat_id == -mergeDialogId) {
thisDialogId = mergeDialogId;
}
MessagesController.getInstance(currentAccount).deleteMessages(ids, random_ids, encryptedChat, thisDialogId, topicId, deleteForAll[0], mode); MessagesController.getInstance(currentAccount).deleteMessages(ids, random_ids, encryptedChat, thisDialogId, topicId, deleteForAll[0], mode);
} else { } else {
for (int a = 1; a >= 0; a--) { for (int a = 1; a >= 0; a--) {
@ -6256,31 +6280,10 @@ public class AlertsCreator {
} }
} }
} }
MessagesController.getInstance(currentAccount).deleteMessages(ids, random_ids, encryptedChat, thisDialogId, topicId, deleteForAll[0], mode); MessagesController.getInstance(currentAccount).deleteMessages(ids, random_ids, encryptedChat, (a == 1 && mergeDialogId != 0) ? mergeDialogId : thisDialogId, topicId, deleteForAll[0], mode);
selectedMessages[a].clear(); selectedMessages[a].clear();
} }
} }
if (userFinal != null || chatFinal != null) {
if (checks[0]) {
MessagesController.getInstance(currentAccount).deleteParticipantFromChat(chat.id, userFinal, chatFinal, false, false);
}
if (checks[1]) {
TLRPC.TL_channels_reportSpam req = new TLRPC.TL_channels_reportSpam();
req.channel = MessagesController.getInputChannel(chat);
if (userFinal != null) {
req.participant = MessagesController.getInputPeer(userFinal);
} else {
req.participant = MessagesController.getInputPeer(chatFinal);
}
req.id = ids;
ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {
});
}
if (checks[2]) {
MessagesController.getInstance(currentAccount).deleteUserChannelHistory(chat, userFinal, chatFinal, 0);
}
}
if (onDelete != null) { if (onDelete != null) {
onDelete.run(); onDelete.run();
} }
@ -6839,11 +6842,7 @@ public class AlertsCreator {
public static ActionBarPopupWindow showPopupMenu(ActionBarPopupWindow.ActionBarPopupWindowLayout popupLayout, View anchorView, int offsetX, int offsetY) { public static ActionBarPopupWindow showPopupMenu(ActionBarPopupWindow.ActionBarPopupWindowLayout popupLayout, View anchorView, int offsetX, int offsetY) {
Rect rect = new Rect(); Rect rect = new Rect();
ActionBarPopupWindow popupWindow = new ActionBarPopupWindow(popupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT); ActionBarPopupWindow popupWindow = new ActionBarPopupWindow(popupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT);
if (Build.VERSION.SDK_INT >= 19) {
popupWindow.setAnimationStyle(0);
} else {
popupWindow.setAnimationStyle(R.style.PopupAnimation); popupWindow.setAnimationStyle(R.style.PopupAnimation);
}
popupWindow.setAnimationEnabled(true); popupWindow.setAnimationEnabled(true);
@ -6866,7 +6865,8 @@ public class AlertsCreator {
popupWindow.showAsDropDown(anchorView, offsetX, offsetY); popupWindow.showAsDropDown(anchorView, offsetX, offsetY);
popupLayout.updateRadialSelectors(); popupLayout.updateRadialSelectors();
popupWindow.startAnimation(); // popupWindow.startAnimation();
ActionBarPopupWindow.startAnimation(popupLayout);
popupLayout.setOnTouchListener((v, event) -> { popupLayout.setOnTouchListener((v, event) -> {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {

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