-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathBotWebViewSheet.java
More file actions
2696 lines (2434 loc) · 126 KB
/
Copy pathBotWebViewSheet.java
File metadata and controls
2696 lines (2434 loc) · 126 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.telegram.ui.bots;
import static org.telegram.messenger.AndroidUtilities.dp;
import static org.telegram.messenger.AndroidUtilities.lerp;
import static org.telegram.ui.Components.Bulletin.DURATION_PROLONG;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Pair;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.ColorUtils;
import androidx.core.math.MathUtils;
import androidx.core.view.WindowInsetsCompat;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
import org.json.JSONObject;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.AnimationNotificationsLocker;
import org.telegram.messenger.BotFullscreenButtons;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.DialogObject;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.ImageLocation;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaDataController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities;
import org.telegram.messenger.browser.Browser;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.tgnet.tl.TL_bots;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenu;
import org.telegram.ui.ActionBar.ActionBarMenuItem;
import org.telegram.ui.ActionBar.ActionBarMenuSubItem;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.BottomSheetTabDialog;
import org.telegram.ui.ActionBar.BottomSheetTabs;
import org.telegram.ui.ActionBar.BottomSheetTabsOverlay;
import org.telegram.ui.ActionBar.INavigationLayout;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.ArticleViewer;
import org.telegram.ui.ChatActivity;
import org.telegram.ui.Components.Bulletin;
import org.telegram.ui.Components.BulletinFactory;
import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.ItemOptions;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.OverlayActionBarLayoutDialog;
import org.telegram.ui.Components.PasscodeView;
import org.telegram.ui.Components.SimpleFloatPropertyCompat;
import org.telegram.ui.Components.SizeNotifierFrameLayout;
import org.telegram.ui.DialogsActivity;
import org.telegram.ui.LaunchActivity;
import org.telegram.ui.PaymentFormActivity;
import org.telegram.ui.ProfileActivity;
import org.telegram.ui.Stars.StarsController;
import org.telegram.ui.web.BotWebViewContainer;
import java.io.File;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class BotWebViewSheet extends Dialog implements NotificationCenter.NotificationCenterDelegate, BottomSheetTabsOverlay.Sheet {
public final static int TYPE_WEB_VIEW_BUTTON = 0, TYPE_SIMPLE_WEB_VIEW_BUTTON = 1, TYPE_BOT_MENU_BUTTON = 2, TYPE_WEB_VIEW_BOT_APP = 3, TYPE_WEB_VIEW_BOT_MAIN = 4;
public final static int FLAG_FROM_INLINE_SWITCH = 1;
public final static int FLAG_FROM_SIDE_MENU = 2;
private int lineColor;
public static HashSet<BotWebViewSheet> activeSheets = new HashSet<>();
public void showJustAddedBulletin() {
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(botId);
TLRPC.TL_attachMenuBot currentBot = null;
for (TLRPC.TL_attachMenuBot bot : MediaDataController.getInstance(currentAccount).getAttachMenuBots().bots) {
if (bot.bot_id == botId) {
currentBot = bot;
break;
}
}
if (currentBot == null) {
return;
}
String str;
if (currentBot.show_in_side_menu && currentBot.show_in_attach_menu) {
str = LocaleController.formatString(R.string.BotAttachMenuShortcatAddedAttachAndSide, user.first_name);
} else if (currentBot.show_in_side_menu) {
str = LocaleController.formatString(R.string.BotAttachMenuShortcatAddedSide, user.first_name);
} else {
str = LocaleController.formatString(R.string.BotAttachMenuShortcatAddedAttach, user.first_name);
}
AndroidUtilities.runOnUIThread(() -> {
showBulletin(b ->
b
.createSimpleBulletin(R.raw.contact_check, AndroidUtilities.replaceTags(str))
.setDuration(DURATION_PROLONG)
);
}, 200);
}
@Retention(RetentionPolicy.SOURCE)
@IntDef(value = {
TYPE_WEB_VIEW_BUTTON,
TYPE_SIMPLE_WEB_VIEW_BUTTON,
TYPE_BOT_MENU_BUTTON,
TYPE_WEB_VIEW_BOT_APP,
TYPE_WEB_VIEW_BOT_MAIN
})
public @interface WebViewType {}
private final static int POLL_PERIOD = 60000;
private final static SimpleFloatPropertyCompat<BotWebViewSheet> ACTION_BAR_TRANSITION_PROGRESS_VALUE = new SimpleFloatPropertyCompat<BotWebViewSheet>("actionBarTransitionProgress", obj -> obj.actionBarTransitionProgress, (obj, value) -> {
obj.actionBarTransitionProgress = value;
obj.windowView.invalidate();
obj.actionBar.setAlpha(value);
obj.updateLightStatusBar();
obj.updateDownloadBulletinArrow();
}).setMultiplier(100f);
private float actionBarTransitionProgress = 0f;
private SpringAnimation springAnimation;
private Boolean wasLightStatusBar;
private WindowView windowView;
private final Rect navInsets = new Rect();
private final Rect insets = new Rect();
private int keyboardInset = 0;
private BottomSheetTabs bottomTabs;
private BottomSheetTabs.ClipTools bottomTabsClip;
private long lastSwipeTime;
private ChatAttachAlertBotWebViewLayout.WebViewSwipeContainer swipeContainer;
private FrameLayout.LayoutParams swipeContainerLayoutParams;
private BotWebViewContainer webViewContainer;
private ChatAttachAlertBotWebViewLayout.WebProgressView progressView;
private Theme.ResourcesProvider resourcesProvider;
private boolean ignoreLayout;
private int currentAccount;
private long botId;
private long peerId;
private long queryId;
private int replyToMsgId;
private long monoforumTopicId;
private boolean silent;
private String buttonText;
private Paint linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint dimPaint = new Paint();
private Paint backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int actionBarColor;
private int navBarColor;
private boolean actionBarIsLight;
private Paint actionBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private boolean overrideActionBarColor;
private boolean overrideBackgroundColor;
private ActionBar actionBar;
private FrameLayout.LayoutParams actionBarLayoutParams;
private Drawable actionBarShadow;
private ActionBarMenuItem optionsItem;
private BotFullscreenButtons.OptionsIcon optionsIcon;
private boolean hasSettings;
private TLRPC.BotApp currentWebApp;
private boolean dismissed;
private boolean fullscreen;
private boolean fullscreenBlur;
private float fullscreenProgress;
private float fullscreenTransitionProgress;
private boolean fullscreenInProgress;
private int swipeContainerFromWidth, swipeContainerFromHeight;
private Activity parentActivity;
private BotButtons botButtons;
private FrameLayout.LayoutParams botButtonsLayoutParams;
private BotFullscreenButtons fullscreenButtons;
private Bulletin downloadBulletin;
private BotDownloads.DownloadBulletin downloadBulletinLayout;
private FrameLayout bulletinContainer;
private FrameLayout.LayoutParams bulletinContainerLayoutParams;
private boolean needCloseConfirmation;
private PasscodeView passcodeView;
private Runnable pollRunnable = () -> {
if (!dismissed && queryId != 0) {
TLRPC.TL_messages_prolongWebView prolongWebView = new TLRPC.TL_messages_prolongWebView();
prolongWebView.bot = MessagesController.getInstance(currentAccount).getInputUser(botId);
prolongWebView.peer = MessagesController.getInstance(currentAccount).getInputPeer(peerId);
prolongWebView.query_id = queryId;
prolongWebView.silent = silent;
if (replyToMsgId != 0) {
prolongWebView.reply_to = SendMessagesHelper.getInstance(currentAccount).createReplyInput(replyToMsgId);
if (monoforumTopicId != 0) {
prolongWebView.reply_to.monoforum_peer_id = MessagesController.getInstance(currentAccount).getInputPeer(monoforumTopicId);
prolongWebView.reply_to.flags |= 32;
}
prolongWebView.flags |= 1;
} else if (monoforumTopicId != 0) {
prolongWebView.reply_to = new TLRPC.TL_inputReplyToMonoForum();
prolongWebView.reply_to.monoforum_peer_id = MessagesController.getInstance(currentAccount).getInputPeer(monoforumTopicId);
prolongWebView.flags |= 1;
}
ConnectionsManager.getInstance(currentAccount).sendRequest(prolongWebView, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (dismissed) {
return;
}
if (error != null) {
dismiss();
} else {
AndroidUtilities.runOnUIThread(this.pollRunnable, POLL_PERIOD);
}
}));
}
};
private int actionBarColorKey = -1;
private WebViewRequestProps requestProps;
private boolean backButtonShown;
private boolean forceExpnaded;
private boolean defaultFullsize = false;
private Boolean fullsize = null;
private boolean needsContext;
private BotSensors sensors;
private boolean orientationLocked;
private BottomSheetTabs.WebTabData lastTab;
public BottomSheetTabs.WebTabData saveState() {
BottomSheetTabs.WebTabData tab = new BottomSheetTabs.WebTabData();
tab.actionBarColor = actionBarColor;
tab.actionBarColorKey = actionBarColorKey;
tab.overrideActionBarColor = overrideActionBarColor;
tab.overrideBackgroundColor = overrideBackgroundColor;
tab.backgroundColor = backgroundPaint.getColor();
tab.props = requestProps;
tab.ready = webViewContainer != null && webViewContainer.isPageLoaded();
tab.themeIsDark = Theme.isCurrentThemeDark();
tab.lastUrl = webViewContainer != null ? webViewContainer.getUrlLoaded() : null;
tab.expanded = swipeContainer != null && swipeContainer.getSwipeOffsetY() < 0 || forceExpnaded || isFullSize() || fullscreen;
tab.fullscreen = fullscreen;
tab.fullscreenBlur = fullscreenBlur;
tab.fullsize = (fullsize == null ? defaultFullsize : fullsize);
tab.expandedOffset = swipeContainer != null ? swipeContainer.getOffsetY() : Float.MAX_VALUE;
tab.needsContext = needsContext;
tab.backButton = backButtonShown;
tab.confirmDismiss = needCloseConfirmation;
tab.settings = hasSettings;
tab.allowSwipes = swipeContainer == null || swipeContainer.isAllowedSwipes();
tab.buttons = botButtons.state;
tab.navigationBarColor = navBarColor;
if (sensors != null) {
sensors.pause();
}
tab.sensors = sensors;
BotWebViewContainer.MyWebView webView = webViewContainer == null ? null : webViewContainer.getWebView();
if (webView != null) {
webViewContainer.preserveWebView();
tab.webView = webView;
tab.proxy = webViewContainer == null ? null : webViewContainer.getBotProxy();
tab.viewWidth = webView.getWidth();
tab.viewHeight = webView.getHeight();
webView.onPause();
// webView.pauseTimers();
}
if (tab.error = errorShown) {
tab.errorDescription = errorCode;
}
tab.orientationLocked = orientationLocked;
return lastTab = tab;
}
public Activity getActivity() {
Activity a = getOwnerActivity();
if (a == null) a = LaunchActivity.instance;
if (a == null) a = AndroidUtilities.findActivity(getContext());
return a;
}
public boolean fromTab;
public boolean showExpanded;
public float showOffsetY;
public boolean restoreState(BaseFragment fragment, BottomSheetTabs.WebTabData tab) {
if (tab == null || tab.props == null) return false;
fromTab = true;
if (overrideBackgroundColor = tab.overrideBackgroundColor) {
setBackgroundColor(tab.backgroundColor, true, false);
}
setActionBarColor(!tab.overrideActionBarColor ? Theme.getColor(tab.actionBarColorKey < 0 ? Theme.key_windowBackgroundWhite : tab.actionBarColorKey, resourcesProvider) : tab.actionBarColor, tab.overrideActionBarColor, false);
setNavigationBarColor(tab.navigationBarColor, false);
showExpanded = tab.expanded;
showOffsetY = tab.expandedOffset;
webViewContainer.setIsBackButtonVisible(backButtonShown = tab.backButton);
swipeContainer.setAllowSwipes(tab.allowSwipes);
AndroidUtilities.updateImageViewImageAnimated(actionBar.getBackButton(), backButtonShown ? R.drawable.ic_ab_back : R.drawable.ic_close_white);
if (fullscreenButtons != null) {
fullscreenButtons.setBack(backButtonShown, false);
}
needCloseConfirmation = tab.confirmDismiss;
fullsize = tab.fullsize;
needsContext = tab.needsContext;
sensors = tab.sensors;
if (sensors != null) {
sensors.resume();
}
if (tab.buttons != null) {
// setMainButton(tab.main);
botButtons.setState(tab.buttons, false);
}
setFullscreen(tab.fullscreen, false, tab.fullscreenBlur);
currentAccount = tab.props != null ? tab.props.currentAccount : UserConfig.selectedAccount;
if (tab.webView != null) {
// tab.webView.resumeTimers();
tab.webView.onResume();
webViewContainer.replaceWebView(currentAccount, tab.webView, tab.proxy);
webViewContainer.setState(tab.ready || tab.webView.isPageLoaded(), tab.lastUrl);
if (Theme.isCurrentThemeDark() != tab.themeIsDark) {
webViewContainer.notifyThemeChanged();
// if (webViewContainer.getWebView() != null) {
// webViewContainer.getWebView().animate().cancel();
// webViewContainer.getWebView().animate().alpha(0).start();
// }
//
// progressView.setLoadProgress(0);
// progressView.setAlpha(1f);
// progressView.setVisibility(View.VISIBLE);
//
// webViewContainer.setBotUser(MessagesController.getInstance(currentAccount).getUser(botId));
// webViewContainer.loadFlickerAndSettingsItem(currentAccount, botId, null);
// webViewContainer.setState(false, null);
// if (webViewContainer.getWebView() != null) {
// webViewContainer.getWebView().loadUrl("about:blank");
// }
//
// tab.props.response = null;
// tab.props.responseTime = 0;
}
} else {
tab.props.response = null;
tab.props.responseTime = 0;
}
requestWebView(fragment, tab.props);
hasSettings = tab.settings;
if (tab.error) {
errorShown = true;
createErrorContainer();
errorContainer.set(UserObject.getUserName(MessagesController.getInstance(currentAccount).getUser(botId)), errorCode = tab.errorDescription);
errorContainer.setDark(AndroidUtilities.computePerceivedBrightness(backgroundPaint.getColor()) <= .721f, false);
errorContainer.setBackgroundColor(backgroundPaint.getColor());
errorContainer.setVisibility(View.VISIBLE);
errorContainer.setAlpha(1f);
}
lockOrientation(tab.orientationLocked);
return true;
}
public BotWebViewSheet(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) {
super(context, R.style.TransparentDialog);
this.resourcesProvider = resourcesProvider;
lineColor = Theme.getColor(Theme.key_sheet_scrollUp);
swipeContainer = new ChatAttachAlertBotWebViewLayout.WebViewSwipeContainer(context) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int availableHeight = MeasureSpec.getSize(heightMeasureSpec);
int padding;
if (!AndroidUtilities.isTablet() && AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y) {
padding = (int) (availableHeight / 3.5f);
} else {
padding = (availableHeight / 5 * 2);
}
if (padding < 0) {
padding = 0;
}
if (getOffsetY() != padding && !dismissed && resetOffsetY) {
ignoreLayout = true;
setOffsetY(padding);
ignoreLayout = false;
resetOffsetY = false;
}
if (!fullscreen && AndroidUtilities.isTablet() && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isSmallTablet()) {
widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.8f), MeasureSpec.EXACTLY);
}
int height = MeasureSpec.getSize(heightMeasureSpec);
if (!fullscreen) {
height -= AndroidUtilities.statusBarHeight;
height -= ActionBar.getCurrentActionBarHeight();
}
if (botButtons != null && botButtons.getTotalHeight() > 0) {
height -= botButtons.getTotalHeight();
// if (fullscreen) {
// height -= insets.bottom;
// }
}
height += dp(24);
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
@Override
public void requestLayout() {
if (ignoreLayout) {
return;
}
super.requestLayout();
}
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
if (fullscreenButtons != null) {
fullscreenButtons.setTranslationY(dp(24) + translationY);
}
if (bulletinContainer != null) {
bulletinContainer.setTranslationY(lerp(ActionBar.getCurrentActionBarHeight() - dp(24), insets.top + dp(24 + 8 + 30 + 8), fullscreenProgress) + swipeContainer.getTranslationY());
}
}
};
swipeContainer.setAllowFullSizeSwipe(true);
swipeContainer.setShouldWaitWebViewScroll(true);
webViewContainer = new BotWebViewContainer(context, resourcesProvider, getColor(Theme.key_windowBackgroundWhite), true) {
@Override
public void onWebViewCreated(MyWebView webView) {
super.onWebViewCreated(webView);
swipeContainer.setWebView(webView);
if (sensors != null) {
sensors.attachWebView(webView);
}
fullscreenButtons.setWebView(webView);
updateWebViewBackgroundColor();
}
@Override
public void onWebViewDestroyed(MyWebView webView) {
if (sensors != null) {
sensors.detachWebView(webView);
}
fullscreenButtons.setWebView(null);
}
@Override
protected void onErrorShown(boolean shown, int errorCode, String description) {
if (shown) {
createErrorContainer();
errorContainer.set(UserObject.getUserName(MessagesController.getInstance(currentAccount).getUser(botId)), description);
errorContainer.setDark(AndroidUtilities.computePerceivedBrightness(backgroundPaint.getColor()) <= .721f, false);
errorContainer.setBackgroundColor(backgroundPaint.getColor());
BotWebViewSheet.this.errorCode = description;
}
AndroidUtilities.updateViewVisibilityAnimated(errorContainer, errorShown = shown, 1f, false);
invalidate();
}
};
webViewContainer.setOnVerifiedAge(onVerifiedAge);
webViewContainer.setDelegate(new BotWebViewContainer.Delegate() {
private boolean sentWebViewData;
@Override
public void onCloseRequested(Runnable callback) {
dismiss(callback);
}
@Override
public void onWebAppSetupClosingBehavior(boolean needConfirmation) {
BotWebViewSheet.this.needCloseConfirmation = needConfirmation;
}
@Override
public void onWebAppSwipingBehavior(boolean allowSwiping) {
if (swipeContainer != null) {
swipeContainer.setAllowSwipes(allowSwiping);
}
}
@Override
public void onCloseToTabs() {
dismiss(true);
}
@Override
public void onSharedTo(ArrayList<Long> dialogIds) {
String message;
if (dialogIds.size() == 1) {
message = LocaleController.formatString(R.string.BotSharedToOne, MessagesController.getInstance(currentAccount).getPeerName(dialogIds.get(0)));
} else {
message = LocaleController.formatPluralString("BotSharedToMany", dialogIds.size());
}
showBulletin(b -> b.createSimpleBulletin(R.raw.forward, AndroidUtilities.replaceTags(message)));
}
@Override
public void onOrientationLockChanged(boolean locked) {
lockOrientation(locked);
}
@Override
public void onOpenBackFromTabs() {
if (lastTab != null) {
final BottomSheetTabs tabs = LaunchActivity.instance.getBottomSheetTabs();
if (tabs != null) {
tabs.openTab(lastTab);
}
lastTab = null;
}
}
@Override
public void onSendWebViewData(String data) {
if (queryId != 0 || sentWebViewData) {
return;
}
sentWebViewData = true;
TLRPC.TL_messages_sendWebViewData sendWebViewData = new TLRPC.TL_messages_sendWebViewData();
sendWebViewData.bot = MessagesController.getInstance(currentAccount).getInputUser(botId);
sendWebViewData.random_id = Utilities.random.nextLong();
sendWebViewData.button_text = buttonText;
sendWebViewData.data = data;
ConnectionsManager.getInstance(currentAccount).sendRequest(sendWebViewData, (response, error) -> {
if (response instanceof TLRPC.TL_updates) {
MessagesController.getInstance(currentAccount).processUpdates((TLRPC.TL_updates) response, false);
}
AndroidUtilities.runOnUIThread(BotWebViewSheet.this::dismiss);
});
}
@Override
public void onWebAppSetActionBarColor(int colorKey, int color, boolean isOverrideColor) {
actionBarColorKey = colorKey;
setActionBarColor(color, isOverrideColor, true);
}
@Override
public void onWebAppSetNavigationBarColor(int color) {
setNavigationBarColor(color, true);
}
@Override
public void onWebAppSetBackgroundColor(int color) {
setBackgroundColor(color, true, true);
}
@Override
public void onLocationGranted(boolean granted) {
final TLRPC.User bot = MessagesController.getInstance(currentAccount).getUser(botId);
if (granted) {
BulletinFactory.UndoObject undo = new BulletinFactory.UndoObject();
undo.undoText = LocaleController.getString(R.string.Undo);
undo.onUndo = () -> {
BotLocation.get(getContext(), currentAccount, botId).setGranted(false, null);
};
showBulletin(b ->
b
.createUsersBulletin(Arrays.asList(bot), AndroidUtilities.replaceTags(LocaleController.formatString(R.string.BotLocationPermissionRequestGranted, UserObject.getUserName(bot))), null, undo)
.setDuration(DURATION_PROLONG)
);
} else {
SpannableStringBuilder text = new SpannableStringBuilder();
text.append(AndroidUtilities.replaceTags(LocaleController.formatString(R.string.BotLocationPermissionRequestDeniedApp, UserObject.getUserName(bot))));
text.append(" ");
text.append(AndroidUtilities.replaceArrows(AndroidUtilities.makeClickable(LocaleController.getString(R.string.BotLocationPermissionRequestDeniedAppSettings), () -> {
BaseFragment lastFragment = LaunchActivity.getSafeLastFragment();
if (lastFragment == null || lastFragment.getParentLayout() == null) return;
final INavigationLayout parentLayout = lastFragment.getParentLayout();
lastFragment.presentFragment(ProfileActivity.of(botId));
AndroidUtilities.scrollToFragmentRow(parentLayout, "botPermissionLocation");
dismiss(true);
}), true));
showBulletin(b ->
b.createSimpleBulletinDetail(R.raw.error, text)
.setDuration(DURATION_PROLONG)
);
}
}
@Override
public void onEmojiStatusGranted(boolean granted) {
final TLRPC.User bot = MessagesController.getInstance(currentAccount).getUser(botId);
if (granted) {
BulletinFactory.UndoObject undo = new BulletinFactory.UndoObject();
undo.onUndo = () -> {
TL_bots.toggleUserEmojiStatusPermission req = new TL_bots.toggleUserEmojiStatusPermission();
req.bot = MessagesController.getInstance(currentAccount).getInputUser(botId);
req.enabled = false;
ConnectionsManager.getInstance(currentAccount).sendRequest(req, (res, err) -> AndroidUtilities.runOnUIThread(() -> {
if (res instanceof TLRPC.TL_boolTrue) {
webViewContainer.notifyEmojiStatusAccess("cancelled");
} else {
showBulletin(b -> b.makeForError(err));
}
}));
};
showBulletin(b ->
b
.createUsersBulletin(Arrays.asList(bot), AndroidUtilities.replaceTags(LocaleController.formatString(R.string.BotEmojiStatusPermissionRequestGranted, UserObject.getUserName(bot))), null, undo)
.setDuration(DURATION_PROLONG)
);
}
}
@Override
public void onEmojiStatusSet(TLRPC.Document document) {
showBulletin(b -> b.createEmojiBulletin(document, LocaleController.getString(R.string.BotEmojiStatusUpdated)));
}
@Override
public void onSetBackButtonVisible(boolean visible) {
AndroidUtilities.updateImageViewImageAnimated(actionBar.getBackButton(), (backButtonShown = visible) ? R.drawable.ic_ab_back : R.drawable.ic_close_white);
if (fullscreenButtons != null) {
fullscreenButtons.setBack(visible, true);
}
}
@Override
public void onSetSettingsButtonVisible(boolean visible) {
hasSettings = visible;
}
@Override
public void onWebAppOpenInvoice(TLRPC.InputInvoice inputInvoice, String slug, TLObject response) {
BaseFragment parentFragment = ((LaunchActivity) parentActivity).getActionBarLayout().getLastFragment();
PaymentFormActivity paymentFormActivity = null;
if (response instanceof TLRPC.TL_payments_paymentFormStars) {
AndroidUtilities.hideKeyboard(windowView);
final AlertDialog progressDialog = new AlertDialog(getContext(), AlertDialog.ALERT_TYPE_SPINNER);
progressDialog.showDelayed(150);
StarsController.getInstance(currentAccount).openPaymentForm(null, inputInvoice, (TLRPC.TL_payments_paymentFormStars) response, () -> {
progressDialog.dismiss();
}, status -> {
webViewContainer.onInvoiceStatusUpdate(slug, status);
});
return;
} else if (response instanceof TLRPC.PaymentForm) {
TLRPC.PaymentForm form = (TLRPC.PaymentForm) response;
MessagesController.getInstance(currentAccount).putUsers(form.users, false);
paymentFormActivity = new PaymentFormActivity(form, slug, parentFragment);
} else if (response instanceof TLRPC.PaymentReceipt) {
paymentFormActivity = new PaymentFormActivity((TLRPC.PaymentReceipt) response);
}
if (paymentFormActivity != null) {
swipeContainer.stickTo(-swipeContainer.getOffsetY() + swipeContainer.getTopActionBarOffsetY());
AndroidUtilities.hideKeyboard(windowView);
OverlayActionBarLayoutDialog overlayActionBarLayoutDialog = new OverlayActionBarLayoutDialog(context, resourcesProvider);
overlayActionBarLayoutDialog.show();
paymentFormActivity.setPaymentFormCallback(status -> {
if (status != PaymentFormActivity.InvoiceStatus.PENDING) {
overlayActionBarLayoutDialog.dismiss();
}
webViewContainer.onInvoiceStatusUpdate(slug, status.name().toLowerCase(Locale.ROOT));
});
paymentFormActivity.setResourcesProvider(resourcesProvider);
overlayActionBarLayoutDialog.addFragment(paymentFormActivity);
}
}
@Override
public void onWebAppExpand() {
if (/* System.currentTimeMillis() - lastSwipeTime <= 1000 || */ swipeContainer.isSwipeInProgress()) {
return;
}
swipeContainer.stickTo(-swipeContainer.getOffsetY() + swipeContainer.getTopActionBarOffsetY());
}
@Override
public void onWebAppSwitchInlineQuery(TLRPC.User botUser, String query, List<String> chatTypes) {
if (chatTypes.isEmpty()) {
if (parentActivity instanceof LaunchActivity) {
BaseFragment lastFragment = ((LaunchActivity) parentActivity).getActionBarLayout().getLastFragment();
if (lastFragment instanceof ChatActivity) {
((ChatActivity) lastFragment).getChatActivityEnterView().setFieldText("@" + UserObject.getPublicUsername(botUser) + " " + query);
dismiss();
}
}
} else {
Bundle args = new Bundle();
args.putInt("dialogsType", DialogsActivity.DIALOGS_TYPE_START_ATTACH_BOT);
args.putBoolean("onlySelect", true);
args.putBoolean("allowGroups", chatTypes.contains("groups"));
args.putBoolean("allowMegagroups", chatTypes.contains("groups"));
args.putBoolean("allowLegacyGroups", chatTypes.contains("groups"));
args.putBoolean("allowUsers", chatTypes.contains("users"));
args.putBoolean("allowChannels", chatTypes.contains("channels"));
args.putBoolean("allowBots", chatTypes.contains("bots"));
DialogsActivity dialogsActivity = new DialogsActivity(args);
AndroidUtilities.hideKeyboard(windowView);
OverlayActionBarLayoutDialog overlayActionBarLayoutDialog = new OverlayActionBarLayoutDialog(context, resourcesProvider);
dialogsActivity.setDelegate((fragment, dids, message1, param, notify, scheduleDate, scheduleRepeatPeriod, topicsFragment) -> {
long did = dids.get(0).dialogId;
Bundle args1 = new Bundle();
args1.putBoolean("scrollToTopOnResume", true);
if (DialogObject.isEncryptedDialog(did)) {
args1.putInt("enc_id", DialogObject.getEncryptedChatId(did));
} else if (DialogObject.isUserDialog(did)) {
args1.putLong("user_id", did);
} else {
args1.putLong("chat_id", -did);
}
args1.putString("start_text", "@" + UserObject.getPublicUsername(botUser) + " " + query);
if (parentActivity instanceof LaunchActivity) {
BaseFragment lastFragment = ((LaunchActivity) parentActivity).getActionBarLayout().getLastFragment();
if (MessagesController.getInstance(currentAccount).checkCanOpenChat(args1, lastFragment)) {
overlayActionBarLayoutDialog.dismiss();
dismissed = true;
AndroidUtilities.cancelRunOnUIThread(pollRunnable);
webViewContainer.destroyWebView();
NotificationCenter.getInstance(currentAccount).removeObserver(BotWebViewSheet.this, NotificationCenter.webViewResultSent);
NotificationCenter.getGlobalInstance().removeObserver(BotWebViewSheet.this, NotificationCenter.didSetNewTheme);
if (!superDismissed) {
BotWebViewSheet.super.dismiss();
superDismissed = true;
}
lastFragment.presentFragment(new INavigationLayout.NavigationParams(new ChatActivity(args1)).setRemoveLast(true));
}
}
return true;
});
overlayActionBarLayoutDialog.show();
overlayActionBarLayoutDialog.addFragment(dialogsActivity);
}
}
@Override
public void onSetupMainButton(boolean isVisible, boolean isActive, String text, int color, int textColor, boolean isProgressVisible, boolean hasShineEffect) {
botButtons.setMainState(BotButtons.ButtonState.of(isVisible, isActive, isProgressVisible, hasShineEffect, text, color, textColor), true);
if (fullscreen) {
updateFullscreenLayout();
updateWindowFlags();
}
}
@Override
public void onSetupSecondaryButton(boolean isVisible, boolean isActive, String text, int color, int textColor, boolean isProgressVisible, boolean hasShineEffect, String position) {
botButtons.setSecondaryState(BotButtons.ButtonState.of(isVisible, isActive, isProgressVisible, hasShineEffect, text, color, textColor, position), true);
if (fullscreen) {
updateFullscreenLayout();
updateWindowFlags();
}
}
@Override
public String getWebAppName() {
if (currentWebApp != null) {
return currentWebApp.title;
}
return null;
}
@Override
public boolean isClipboardAvailable() {
return MediaDataController.getInstance(currentAccount).botInAttachMenu(botId) || MessagesController.getInstance(currentAccount).whitelistedBots.contains(botId);
}
@Override
public String onFullscreenRequested(boolean fullscreen, boolean blur) {
if (BotWebViewSheet.this.fullscreen == fullscreen) {
if (BotWebViewSheet.this.fullscreen)
return "ALREADY_FULLSCREEN";
return null;
}
setFullscreen(fullscreen, true, blur);
return null;
}
@Override
public BotSensors getBotSensors() {
if (sensors == null) {
sensors = new BotSensors(context, botId);
sensors.attachWebView(webViewContainer.getWebView());
}
return sensors;
}
});
linePaint.setStyle(Paint.Style.FILL_AND_STROKE);
linePaint.setStrokeWidth(AndroidUtilities.dp(4));
linePaint.setStrokeCap(Paint.Cap.ROUND);
dimPaint.setColor(0x40000000);
actionBarColor = getColor(Theme.key_windowBackgroundWhite);
navBarColor = getColor(Theme.key_windowBackgroundGray);
AndroidUtilities.setNavigationBarColor(this, navBarColor, false);
windowView = new WindowView(context);
windowView.setDelegate((keyboardHeight, isWidthGreater) -> {
if (keyboardHeight > AndroidUtilities.dp(20)) {
swipeContainer.stickTo(-swipeContainer.getOffsetY() + swipeContainer.getTopActionBarOffsetY());
}
});
windowView.addView(swipeContainer, swipeContainerLayoutParams = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL));
botButtons = new BotButtons(getContext(), resourcesProvider) {
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (!fullscreen && AndroidUtilities.isTablet() && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isSmallTablet()) {
widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.8f), MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
};
botButtons.setOnButtonClickListener(main -> {
if (webViewContainer != null) {
if (main) {
webViewContainer.onMainButtonPressed();
} else {
webViewContainer.onSecondaryButtonPressed();
}
}
});
botButtons.setOnResizeListener(() -> {
swipeContainer.requestLayout();
});
windowView.addView(botButtons, botButtonsLayoutParams = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL));
fullscreenButtons = new BotFullscreenButtons(getContext());
fullscreenButtons.setAlpha(0f);
fullscreenButtons.setVisibility(View.GONE);
fullscreenBlur = !MessagesController.getInstance(currentAccount).disableBotFullscreenBlur && SharedConfig.getDevicePerformanceClass() >= SharedConfig.PERFORMANCE_CLASS_HIGH;
fullscreenButtons.setParentRenderNode(fullscreenBlur ? swipeContainer.getRenderNode() : null);
windowView.addView(fullscreenButtons, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.FILL));
fullscreenButtons.setOnCloseClickListener(() -> {
if (!webViewContainer.onBackPressed()) {
onCheckDismissByUser();
}
});
fullscreenButtons.setOnCollapseClickListener(() -> {
forceExpnaded = true;
dismiss(true, null);
});
fullscreenButtons.setOnMenuClickListener(this::openOptions);
bulletinContainer = new FrameLayout(context);
windowView.addView(bulletinContainer, bulletinContainerLayoutParams = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 200, Gravity.TOP | Gravity.FILL_HORIZONTAL));
actionBarShadow = ContextCompat.getDrawable(getContext(), R.drawable.header_shadow).mutate();
actionBar = new ActionBar(context, resourcesProvider) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (AndroidUtilities.isTablet() && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isSmallTablet()) {
widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.8f), MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
};
actionBar.setBackgroundColor(Color.TRANSPARENT);
actionBar.setBackButtonImage(R.drawable.ic_close_white);
updateActionBarColors();
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
onCheckDismissByUser();
}
}
});
actionBar.setAlpha(0f);
windowView.addView(actionBar, actionBarLayoutParams = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL));
windowView.addView(progressView = new ChatAttachAlertBotWebViewLayout.WebProgressView(context, resourcesProvider) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (AndroidUtilities.isTablet() && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isSmallTablet()) {
widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.8f), MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0, 0, 0));
webViewContainer.setWebViewProgressListener(progress -> {
progressView.setLoadProgressAnimated(progress);
if (progress == 1f) {
ValueAnimator animator = ValueAnimator.ofFloat(1, 0).setDuration(200);
animator.setInterpolator(CubicBezierInterpolator.DEFAULT);
animator.addUpdateListener(animation -> progressView.setAlpha((Float) animation.getAnimatedValue()));
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
progressView.setVisibility(View.GONE);
}
});
animator.start();
}
});
swipeContainer.addView(webViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
swipeContainer.setScrollListener(()->{
if (swipeContainer.getSwipeOffsetY() > 0) {
dimPaint.setAlpha((int) (0x40 * (1f - MathUtils.clamp(swipeContainer.getSwipeOffsetY() / (float)swipeContainer.getHeight(), 0, 1))));
} else {
dimPaint.setAlpha(0x40);
}
windowView.invalidate();
webViewContainer.invalidateViewPortHeight();
if (springAnimation != null) {
float progress = (1f - Math.min(swipeContainer.getTopActionBarOffsetY(), swipeContainer.getTranslationY() - swipeContainer.getTopActionBarOffsetY()) / swipeContainer.getTopActionBarOffsetY());
float newPos = (progress > 0.5f ? 1 : 0) * 100f;
if (springAnimation.getSpring().getFinalPosition() != newPos) {
springAnimation.getSpring().setFinalPosition(newPos);
springAnimation.start();
}
}
float offsetY = fullscreen ? insets.bottom : Math.max(0, swipeContainer.getSwipeOffsetY());
lastSwipeTime = System.currentTimeMillis();
});
swipeContainer.setScrollEndListener(()-> webViewContainer.invalidateViewPortHeight(true));
swipeContainer.setDelegate(byTap -> {
if (fullscreen && byTap) return;
dismiss(true, null);
});
swipeContainer.setIsKeyboardVisible(obj -> windowView.getKeyboardHeight() >= AndroidUtilities.dp(20));
passcodeView = new PasscodeView(context);
windowView.addView(passcodeView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
setContentView(windowView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));