Search in sources :

Example 1 with ContextProgressView

use of org.telegram.ui.Components.ContextProgressView in project Telegram-FOSS by Telegram-FOSS-Team.

the class ArticleViewer method setParentActivity.

public void setParentActivity(Activity activity, BaseFragment fragment) {
    parentFragment = fragment;
    currentAccount = UserConfig.selectedAccount;
    NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingProgressDidChanged);
    NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidReset);
    NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
    NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidStart);
    if (parentActivity == activity) {
        updatePaintColors();
        refreshThemeColors();
        return;
    }
    parentActivity = activity;
    SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("articles", Activity.MODE_PRIVATE);
    selectedFont = sharedPreferences.getInt("font_type", 0);
    createPaint(false);
    backgroundPaint = new Paint();
    layerShadowDrawable = activity.getResources().getDrawable(R.drawable.layer_shadow);
    slideDotDrawable = activity.getResources().getDrawable(R.drawable.slide_dot_small);
    slideDotBigDrawable = activity.getResources().getDrawable(R.drawable.slide_dot_big);
    scrimPaint = new Paint();
    windowView = new WindowView(activity);
    windowView.setWillNotDraw(false);
    windowView.setClipChildren(true);
    windowView.setFocusable(false);
    containerView = new FrameLayout(activity) {

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            if (windowView.movingPage) {
                int width = getMeasuredWidth();
                int translationX = (int) listView[0].getTranslationX();
                int clipLeft = 0;
                int clipRight = width;
                if (child == listView[1]) {
                    clipRight = translationX;
                } else if (child == listView[0]) {
                    clipLeft = translationX;
                }
                final int restoreCount = canvas.save();
                canvas.clipRect(clipLeft, 0, clipRight, getHeight());
                final boolean result = super.drawChild(canvas, child, drawingTime);
                canvas.restoreToCount(restoreCount);
                if (translationX != 0) {
                    if (child == listView[0]) {
                        final float alpha = Math.max(0, Math.min((width - translationX) / (float) AndroidUtilities.dp(20), 1.0f));
                        layerShadowDrawable.setBounds(translationX - layerShadowDrawable.getIntrinsicWidth(), child.getTop(), translationX, child.getBottom());
                        layerShadowDrawable.setAlpha((int) (0xff * alpha));
                        layerShadowDrawable.draw(canvas);
                    } else if (child == listView[1]) {
                        float opacity = Math.min(0.8f, (width - translationX) / (float) width);
                        if (opacity < 0) {
                            opacity = 0;
                        }
                        scrimPaint.setColor((int) (((0x99000000 & 0xff000000) >>> 24) * opacity) << 24);
                        canvas.drawRect(clipLeft, 0, clipRight, getHeight(), scrimPaint);
                    }
                }
                return result;
            } else {
                return super.drawChild(canvas, child, drawingTime);
            }
        }
    };
    windowView.addView(containerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
    // containerView.setFitsSystemWindows(true);
    if (Build.VERSION.SDK_INT >= 21) {
        windowView.setFitsSystemWindows(true);
        containerView.setOnApplyWindowInsetsListener((v, insets) -> {
            if (Build.VERSION.SDK_INT >= 30) {
                return WindowInsets.CONSUMED;
            } else {
                return insets.consumeSystemWindowInsets();
            }
        });
    }
    fullscreenVideoContainer = new FrameLayout(activity);
    fullscreenVideoContainer.setBackgroundColor(0xff000000);
    fullscreenVideoContainer.setVisibility(View.INVISIBLE);
    windowView.addView(fullscreenVideoContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    fullscreenAspectRatioView = new AspectRatioFrameLayout(activity);
    fullscreenAspectRatioView.setVisibility(View.GONE);
    fullscreenVideoContainer.addView(fullscreenAspectRatioView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER));
    fullscreenTextureView = new TextureView(activity);
    listView = new RecyclerListView[2];
    adapter = new WebpageAdapter[2];
    layoutManager = new LinearLayoutManager[2];
    for (int i = 0; i < listView.length; i++) {
        WebpageAdapter webpageAdapter = adapter[i] = new WebpageAdapter(parentActivity);
        listView[i] = new RecyclerListView(activity) {

            @Override
            protected void onLayout(boolean changed, int l, int t, int r, int b) {
                super.onLayout(changed, l, t, r, b);
                int count = getChildCount();
                for (int a = 0; a < count; a++) {
                    View child = getChildAt(a);
                    if (child.getTag() instanceof Integer) {
                        Integer tag = (Integer) child.getTag();
                        if (tag == 90) {
                            int bottom = child.getBottom();
                            if (bottom < getMeasuredHeight()) {
                                int height = getMeasuredHeight();
                                child.layout(0, height - child.getMeasuredHeight(), child.getMeasuredWidth(), height);
                                break;
                            }
                        }
                    }
                }
            }

            @Override
            public boolean onInterceptTouchEvent(MotionEvent e) {
                if (pressedLinkOwnerLayout != null && pressedLink == null && (popupWindow == null || !popupWindow.isShowing()) && (e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_CANCEL)) {
                    pressedLink = null;
                    pressedLinkOwnerLayout = null;
                    pressedLinkOwnerView = null;
                } else if (pressedLinkOwnerLayout != null && pressedLink != null && e.getAction() == MotionEvent.ACTION_UP) {
                    checkLayoutForLinks(webpageAdapter, e, pressedLinkOwnerView, pressedLinkOwnerLayout, 0, 0);
                }
                return super.onInterceptTouchEvent(e);
            }

            @Override
            public boolean onTouchEvent(MotionEvent e) {
                if (pressedLinkOwnerLayout != null && pressedLink == null && (popupWindow == null || !popupWindow.isShowing()) && (e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_CANCEL)) {
                    pressedLink = null;
                    pressedLinkOwnerLayout = null;
                    pressedLinkOwnerView = null;
                }
                return super.onTouchEvent(e);
            }

            @Override
            public void setTranslationX(float translationX) {
                super.setTranslationX(translationX);
                if (windowView.movingPage) {
                    containerView.invalidate();
                    float progress = translationX / getMeasuredWidth();
                    setCurrentHeaderHeight((int) (windowView.startMovingHeaderHeight + (AndroidUtilities.dp(56) - windowView.startMovingHeaderHeight) * progress));
                }
            }
        };
        ((DefaultItemAnimator) listView[i].getItemAnimator()).setDelayAnimations(false);
        listView[i].setLayoutManager(layoutManager[i] = new LinearLayoutManager(parentActivity, LinearLayoutManager.VERTICAL, false));
        listView[i].setAdapter(webpageAdapter);
        listView[i].setClipToPadding(false);
        listView[i].setVisibility(i == 0 ? View.VISIBLE : View.GONE);
        listView[i].setPadding(0, AndroidUtilities.dp(56), 0, 0);
        listView[i].setTopGlowOffset(AndroidUtilities.dp(56));
        containerView.addView(listView[i], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        listView[i].setOnItemLongClickListener((view, position) -> {
            if (view instanceof BlockRelatedArticlesCell) {
                BlockRelatedArticlesCell cell = (BlockRelatedArticlesCell) view;
                showCopyPopup(cell.currentBlock.parent.articles.get(cell.currentBlock.num).url);
                return true;
            }
            return false;
        });
        listView[i].setOnItemClickListener((view, position, x, y) -> {
            if (textSelectionHelper != null) {
                if (textSelectionHelper.isSelectionMode()) {
                    textSelectionHelper.clear();
                    return;
                }
                textSelectionHelper.clear();
            }
            if (view instanceof ReportCell && webpageAdapter.currentPage != null) {
                ReportCell cell = (ReportCell) view;
                if (previewsReqId != 0 || cell.hasViews && x < view.getMeasuredWidth() / 2) {
                    return;
                }
                TLObject object = MessagesController.getInstance(currentAccount).getUserOrChat("previews");
                if (object instanceof TLRPC.TL_user) {
                    openPreviewsChat((TLRPC.User) object, webpageAdapter.currentPage.id);
                } else {
                    final int currentAccount = UserConfig.selectedAccount;
                    final long pageId = webpageAdapter.currentPage.id;
                    showProgressView(true, true);
                    TLRPC.TL_contacts_resolveUsername req = new TLRPC.TL_contacts_resolveUsername();
                    req.username = "previews";
                    previewsReqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                        if (previewsReqId == 0) {
                            return;
                        }
                        previewsReqId = 0;
                        showProgressView(true, false);
                        if (response != null) {
                            TLRPC.TL_contacts_resolvedPeer res = (TLRPC.TL_contacts_resolvedPeer) response;
                            MessagesController.getInstance(currentAccount).putUsers(res.users, false);
                            MessagesStorage.getInstance(currentAccount).putUsersAndChats(res.users, res.chats, false, true);
                            if (!res.users.isEmpty()) {
                                openPreviewsChat(res.users.get(0), pageId);
                            }
                        }
                    }));
                }
            } else if (position >= 0 && position < webpageAdapter.localBlocks.size()) {
                TLRPC.PageBlock pageBlock = webpageAdapter.localBlocks.get(position);
                TLRPC.PageBlock originalBlock = pageBlock;
                pageBlock = getLastNonListPageBlock(pageBlock);
                if (pageBlock instanceof TL_pageBlockDetailsChild) {
                    TL_pageBlockDetailsChild detailsChild = (TL_pageBlockDetailsChild) pageBlock;
                    pageBlock = detailsChild.block;
                }
                if (pageBlock instanceof TLRPC.TL_pageBlockChannel) {
                    TLRPC.TL_pageBlockChannel pageBlockChannel = (TLRPC.TL_pageBlockChannel) pageBlock;
                    MessagesController.getInstance(currentAccount).openByUserName(pageBlockChannel.channel.username, parentFragment, 2);
                    close(false, true);
                } else if (pageBlock instanceof TL_pageBlockRelatedArticlesChild) {
                    TL_pageBlockRelatedArticlesChild pageBlockRelatedArticlesChild = (TL_pageBlockRelatedArticlesChild) pageBlock;
                    openWebpageUrl(pageBlockRelatedArticlesChild.parent.articles.get(pageBlockRelatedArticlesChild.num).url, null);
                } else if (pageBlock instanceof TLRPC.TL_pageBlockDetails) {
                    view = getLastNonListCell(view);
                    if (!(view instanceof BlockDetailsCell)) {
                        return;
                    }
                    pressedLinkOwnerLayout = null;
                    pressedLinkOwnerView = null;
                    int index = webpageAdapter.blocks.indexOf(originalBlock);
                    if (index < 0) {
                        return;
                    }
                    TLRPC.TL_pageBlockDetails pageBlockDetails = (TLRPC.TL_pageBlockDetails) pageBlock;
                    pageBlockDetails.open = !pageBlockDetails.open;
                    int oldCount = webpageAdapter.getItemCount();
                    webpageAdapter.updateRows();
                    int newCount = webpageAdapter.getItemCount();
                    int changeCount = Math.abs(newCount - oldCount);
                    BlockDetailsCell cell = (BlockDetailsCell) view;
                    cell.arrow.setAnimationProgressAnimated(pageBlockDetails.open ? 0.0f : 1.0f);
                    cell.invalidate();
                    if (changeCount != 0) {
                        if (pageBlockDetails.open) {
                            webpageAdapter.notifyItemRangeInserted(position + 1, changeCount);
                        } else {
                            webpageAdapter.notifyItemRangeRemoved(position + 1, changeCount);
                        }
                    }
                }
            }
        });
        listView[i].setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    textSelectionHelper.stopScrolling();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (recyclerView.getChildCount() == 0) {
                    return;
                }
                textSelectionHelper.onParentScrolled();
                headerView.invalidate();
                checkScroll(dy);
            }
        });
    }
    headerPaint.setColor(0xff000000);
    statusBarPaint.setColor(0xff000000);
    headerProgressPaint.setColor(0xff242426);
    headerView = new FrameLayout(activity) {

        @Override
        protected void onDraw(Canvas canvas) {
            int width = getMeasuredWidth();
            int height = getMeasuredHeight();
            canvas.drawRect(0, 0, width, height, headerPaint);
            if (layoutManager == null) {
                return;
            }
            int first = layoutManager[0].findFirstVisibleItemPosition();
            int last = layoutManager[0].findLastVisibleItemPosition();
            int count = layoutManager[0].getItemCount();
            View view;
            if (last >= count - 2) {
                view = layoutManager[0].findViewByPosition(count - 2);
            } else {
                view = layoutManager[0].findViewByPosition(first);
            }
            if (view == null) {
                return;
            }
            float itemProgress = width / (float) (count - 1);
            int childCount = layoutManager[0].getChildCount();
            float viewHeight = view.getMeasuredHeight();
            float viewProgress;
            if (last >= count - 2) {
                viewProgress = (count - 2 - first) * itemProgress * (listView[0].getMeasuredHeight() - view.getTop()) / viewHeight;
            } else {
                viewProgress = itemProgress * (1.0f - (Math.min(0, view.getTop() - listView[0].getPaddingTop()) + viewHeight) / viewHeight);
            }
            float progress = first * itemProgress + viewProgress;
            canvas.drawRect(0, 0, progress, height, headerProgressPaint);
        }
    };
    headerView.setWillNotDraw(false);
    containerView.addView(headerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 56));
    headerView.setOnClickListener(v -> listView[0].smoothScrollToPosition(0));
    titleTextView = new SimpleTextView(activity);
    titleTextView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
    titleTextView.setTextSize(20);
    titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    titleTextView.setTextColor(0xffb3b3b3);
    titleTextView.setPivotX(0.0f);
    titleTextView.setPivotY(AndroidUtilities.dp(28));
    headerView.addView(titleTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 56, Gravity.LEFT | Gravity.TOP, 72, 0, 48 * 2, 0));
    lineProgressView = new LineProgressView(activity);
    lineProgressView.setProgressColor(0xffffffff);
    lineProgressView.setPivotX(0.0f);
    lineProgressView.setPivotY(AndroidUtilities.dp(2));
    headerView.addView(lineProgressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 2, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 1));
    lineProgressTickRunnable = () -> {
        float progressLeft = 0.7f - lineProgressView.getCurrentProgress();
        if (progressLeft > 0.0f) {
            float tick;
            if (progressLeft < 0.25f) {
                tick = 0.01f;
            } else {
                tick = 0.02f;
            }
            lineProgressView.setProgress(lineProgressView.getCurrentProgress() + tick, true);
            AndroidUtilities.runOnUIThread(lineProgressTickRunnable, 100);
        }
    };
    menuContainer = new FrameLayout(activity);
    headerView.addView(menuContainer, LayoutHelper.createFrame(48, 56, Gravity.TOP | Gravity.RIGHT));
    searchShadow = new View(activity);
    searchShadow.setBackgroundResource(R.drawable.header_shadow);
    searchShadow.setAlpha(0.0f);
    containerView.addView(searchShadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.LEFT | Gravity.TOP, 0, 56, 0, 0));
    searchContainer = new FrameLayout(parentActivity);
    searchContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    searchContainer.setVisibility(View.INVISIBLE);
    if (Build.VERSION.SDK_INT < 21) {
        searchContainer.setAlpha(0.0f);
    }
    headerView.addView(searchContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 56));
    searchField = new EditTextBoldCursor(parentActivity) {

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (!AndroidUtilities.showKeyboard(this)) {
                    clearFocus();
                    requestFocus();
                }
            }
            return super.onTouchEvent(event);
        }
    };
    searchField.setCursorWidth(1.5f);
    searchField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    searchField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    searchField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    searchField.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    searchField.setSingleLine(true);
    searchField.setHint(LocaleController.getString("Search", R.string.Search));
    searchField.setBackgroundResource(0);
    searchField.setPadding(0, 0, 0, 0);
    int inputType = searchField.getInputType() | EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
    searchField.setInputType(inputType);
    if (Build.VERSION.SDK_INT < 23) {
        searchField.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public void onDestroyActionMode(ActionMode mode) {
            }

            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }
        });
    }
    searchField.setOnEditorActionListener((v, actionId, event) -> {
        if (event != null && (event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            AndroidUtilities.hideKeyboard(searchField);
        }
        return false;
    });
    searchField.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (ignoreOnTextChange) {
                ignoreOnTextChange = false;
                return;
            }
            processSearch(s.toString().toLowerCase());
            if (clearButton != null) {
                if (TextUtils.isEmpty(s)) {
                    if (clearButton.getTag() != null) {
                        clearButton.setTag(null);
                        clearButton.clearAnimation();
                        if (animateClear) {
                            clearButton.animate().setInterpolator(new DecelerateInterpolator()).alpha(0.0f).setDuration(180).scaleY(0.0f).scaleX(0.0f).rotation(45).withEndAction(() -> clearButton.setVisibility(View.INVISIBLE)).start();
                        } else {
                            clearButton.setAlpha(0.0f);
                            clearButton.setRotation(45);
                            clearButton.setScaleX(0.0f);
                            clearButton.setScaleY(0.0f);
                            clearButton.setVisibility(View.INVISIBLE);
                            animateClear = true;
                        }
                    }
                } else {
                    if (clearButton.getTag() == null) {
                        clearButton.setTag(1);
                        clearButton.clearAnimation();
                        clearButton.setVisibility(View.VISIBLE);
                        if (animateClear) {
                            clearButton.animate().setInterpolator(new DecelerateInterpolator()).alpha(1.0f).setDuration(180).scaleY(1.0f).scaleX(1.0f).rotation(0).start();
                        } else {
                            clearButton.setAlpha(1.0f);
                            clearButton.setRotation(0);
                            clearButton.setScaleX(1.0f);
                            clearButton.setScaleY(1.0f);
                            animateClear = true;
                        }
                    }
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    searchField.setImeOptions(EditorInfo.IME_FLAG_NO_FULLSCREEN | EditorInfo.IME_ACTION_SEARCH);
    searchField.setTextIsSelectable(false);
    searchContainer.addView(searchField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.CENTER_VERTICAL, 72, 0, 48, 0));
    clearButton = new ImageView(parentActivity) {

        @Override
        protected void onDetachedFromWindow() {
            super.onDetachedFromWindow();
            clearAnimation();
            if (getTag() == null) {
                clearButton.setVisibility(INVISIBLE);
                clearButton.setAlpha(0.0f);
                clearButton.setRotation(45);
                clearButton.setScaleX(0.0f);
                clearButton.setScaleY(0.0f);
            } else {
                clearButton.setAlpha(1.0f);
                clearButton.setRotation(0);
                clearButton.setScaleX(1.0f);
                clearButton.setScaleY(1.0f);
            }
        }
    };
    clearButton.setImageDrawable(new CloseProgressDrawable2());
    clearButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), PorterDuff.Mode.MULTIPLY));
    clearButton.setScaleType(ImageView.ScaleType.CENTER);
    clearButton.setAlpha(0.0f);
    clearButton.setRotation(45);
    clearButton.setScaleX(0.0f);
    clearButton.setScaleY(0.0f);
    clearButton.setOnClickListener(v -> {
        if (searchField.length() != 0) {
            searchField.setText("");
        }
        searchField.requestFocus();
        AndroidUtilities.showKeyboard(searchField);
    });
    clearButton.setContentDescription(LocaleController.getString("ClearButton", R.string.ClearButton));
    searchContainer.addView(clearButton, LayoutHelper.createFrame(48, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT));
    backButton = new ImageView(activity);
    backButton.setScaleType(ImageView.ScaleType.CENTER);
    backDrawable = new BackDrawable(false);
    backDrawable.setAnimationTime(200.0f);
    backDrawable.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    backDrawable.setRotatedColor(0xffb3b3b3);
    backDrawable.setRotation(1.0f, false);
    backButton.setImageDrawable(backDrawable);
    backButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    headerView.addView(backButton, LayoutHelper.createFrame(54, 56));
    backButton.setOnClickListener(v -> {
        /*if (collapsed) {
                uncollapse();
            } else {
                collapse();
            }*/
        if (searchContainer.getTag() != null) {
            showSearch(false);
        } else {
            close(true, true);
        }
    });
    backButton.setContentDescription(LocaleController.getString("AccDescrGoBack", R.string.AccDescrGoBack));
    menuButton = new ActionBarMenuItem(parentActivity, null, Theme.ACTION_BAR_WHITE_SELECTOR_COLOR, 0xffb3b3b3) {

        @Override
        public void toggleSubMenu() {
            super.toggleSubMenu();
            listView[0].stopScroll();
            checkScrollAnimated();
        }
    };
    menuButton.setLayoutInScreen(true);
    menuButton.setDuplicateParentStateEnabled(false);
    menuButton.setClickable(true);
    menuButton.setIcon(R.drawable.ic_ab_other);
    menuButton.addSubItem(search_item, R.drawable.msg_search, LocaleController.getString("Search", R.string.Search));
    menuButton.addSubItem(share_item, R.drawable.msg_share, LocaleController.getString("ShareFile", R.string.ShareFile));
    menuButton.addSubItem(open_item, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp));
    menuButton.addSubItem(settings_item, R.drawable.menu_settings, LocaleController.getString("Settings", R.string.Settings));
    menuButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    menuButton.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
    menuContainer.addView(menuButton, LayoutHelper.createFrame(48, 56));
    progressView = new ContextProgressView(activity, 2);
    progressView.setVisibility(View.GONE);
    menuContainer.addView(progressView, LayoutHelper.createFrame(48, 56));
    menuButton.setOnClickListener(v -> menuButton.toggleSubMenu());
    menuButton.setDelegate(id -> {
        if (adapter[0].currentPage == null || parentActivity == null) {
            return;
        }
        if (id == search_item) {
            showSearch(true);
        } else if (id == share_item) {
            showDialog(new ShareAlert(parentActivity, null, adapter[0].currentPage.url, false, adapter[0].currentPage.url, false));
        } else if (id == open_item) {
            String webPageUrl;
            if (!TextUtils.isEmpty(adapter[0].currentPage.cached_page.url)) {
                webPageUrl = adapter[0].currentPage.cached_page.url;
            } else {
                webPageUrl = adapter[0].currentPage.url;
            }
            Browser.openUrl(parentActivity, webPageUrl, true, false);
        } else if (id == settings_item) {
            BottomSheet.Builder builder = new BottomSheet.Builder(parentActivity);
            builder.setApplyTopPadding(false);
            LinearLayout settingsContainer = new LinearLayout(parentActivity);
            settingsContainer.setPadding(0, 0, 0, AndroidUtilities.dp(4));
            settingsContainer.setOrientation(LinearLayout.VERTICAL);
            HeaderCell headerCell = new HeaderCell(parentActivity);
            headerCell.setText(LocaleController.getString("FontSize", R.string.FontSize));
            settingsContainer.addView(headerCell, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 3, 1, 3, 0));
            TextSizeCell sizeCell = new TextSizeCell(parentActivity);
            settingsContainer.addView(sizeCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 3, 0, 3, 0));
            headerCell = new HeaderCell(parentActivity);
            headerCell.setText(LocaleController.getString("FontType", R.string.FontType));
            settingsContainer.addView(headerCell, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 3, 4, 3, 2));
            for (int a = 0; a < 2; a++) {
                fontCells[a] = new FontCell(parentActivity);
                switch(a) {
                    case 0:
                        fontCells[a].setTextAndTypeface(LocaleController.getString("Default", R.string.Default), Typeface.DEFAULT);
                        break;
                    case 1:
                        fontCells[a].setTextAndTypeface("Serif", Typeface.SERIF);
                        break;
                }
                fontCells[a].select(a == selectedFont, false);
                fontCells[a].setTag(a);
                fontCells[a].setOnClickListener(v -> {
                    int num = (Integer) v.getTag();
                    selectedFont = num;
                    for (int a1 = 0; a1 < 2; a1++) {
                        fontCells[a1].select(a1 == num, true);
                    }
                    updatePaintFonts();
                    for (int i = 0; i < listView.length; i++) {
                        adapter[i].notifyDataSetChanged();
                    }
                });
                settingsContainer.addView(fontCells[a], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50));
            }
            builder.setCustomView(settingsContainer);
            showDialog(linkSheet = builder.create());
        }
    });
    searchPanel = new FrameLayout(parentActivity) {

        @Override
        public void onDraw(Canvas canvas) {
            int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight();
            Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom);
            Theme.chat_composeShadowDrawable.draw(canvas);
            canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint);
        }
    };
    searchPanel.setOnTouchListener((v, event) -> true);
    searchPanel.setWillNotDraw(false);
    searchPanel.setVisibility(View.INVISIBLE);
    searchPanel.setFocusable(true);
    searchPanel.setFocusableInTouchMode(true);
    searchPanel.setClickable(true);
    searchPanel.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    containerView.addView(searchPanel, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
    searchUpButton = new ImageView(parentActivity);
    searchUpButton.setScaleType(ImageView.ScaleType.CENTER);
    searchUpButton.setImageResource(R.drawable.msg_go_up);
    searchUpButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), PorterDuff.Mode.MULTIPLY));
    searchUpButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), 1));
    searchPanel.addView(searchUpButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 48, 0));
    searchUpButton.setOnClickListener(view -> scrollToSearchIndex(currentSearchIndex - 1));
    searchUpButton.setContentDescription(LocaleController.getString("AccDescrSearchNext", R.string.AccDescrSearchNext));
    searchDownButton = new ImageView(parentActivity);
    searchDownButton.setScaleType(ImageView.ScaleType.CENTER);
    searchDownButton.setImageResource(R.drawable.msg_go_down);
    searchDownButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), PorterDuff.Mode.MULTIPLY));
    searchDownButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), 1));
    searchPanel.addView(searchDownButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 0, 0));
    searchDownButton.setOnClickListener(view -> scrollToSearchIndex(currentSearchIndex + 1));
    searchDownButton.setContentDescription(LocaleController.getString("AccDescrSearchPrev", R.string.AccDescrSearchPrev));
    searchCountText = new SimpleTextView(parentActivity);
    searchCountText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    searchCountText.setTextSize(15);
    searchCountText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    searchCountText.setGravity(Gravity.LEFT);
    searchPanel.addView(searchCountText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 18, 0, 108, 0));
    windowLayoutParams = new WindowManager.LayoutParams();
    windowLayoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
    windowLayoutParams.format = PixelFormat.TRANSLUCENT;
    windowLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
    windowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
    windowLayoutParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW - 1;
    windowLayoutParams.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
    windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
    if (Build.VERSION.SDK_INT >= 21) {
        windowLayoutParams.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
        if (Build.VERSION.SDK_INT >= 28) {
            windowLayoutParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }
    }
    textSelectionHelper = new TextSelectionHelper.ArticleTextSelectionHelper();
    textSelectionHelper.setParentView(listView[0]);
    if (MessagesController.getGlobalMainSettings().getBoolean("translate_button", false)) {
        textSelectionHelper.setOnTranslate((text, fromLang, toLang, onAlertDismiss) -> {
            TranslateAlert.showAlert(parentActivity, parentFragment, fromLang, toLang, text, false, null, onAlertDismiss);
        });
    }
    textSelectionHelper.layoutManager = layoutManager[0];
    textSelectionHelper.setCallback(new TextSelectionHelper.Callback() {

        @Override
        public void onStateChanged(boolean isSelected) {
            if (isSelected) {
                showSearch(false);
            }
        }

        @Override
        public void onTextCopied() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
                BulletinFactory.of(containerView, null).createCopyBulletin(LocaleController.getString("TextCopied", R.string.TextCopied)).show();
            }
        }
    });
    containerView.addView(textSelectionHelper.getOverlayView(activity));
    pinchToZoomHelper = new PinchToZoomHelper(containerView, windowView);
    pinchToZoomHelper.setClipBoundsListener(new PinchToZoomHelper.ClipBoundsListener() {

        @Override
        public void getClipTopBottom(float[] topBottom) {
            topBottom[0] = currentHeaderHeight;
            topBottom[1] = listView[0].getMeasuredHeight();
        }
    });
    pinchToZoomHelper.setCallback(new PinchToZoomHelper.Callback() {

        @Override
        public void onZoomStarted(MessageObject messageObject) {
            if (listView[0] != null) {
                listView[0].cancelClickRunnables(true);
            }
        }
    });
    updatePaintColors();
}
Also used : POSITION_FLAG_RIGHT(org.telegram.messenger.MessageObject.POSITION_FLAG_RIGHT) JavascriptInterface(android.webkit.JavascriptInterface) Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) ColorDrawable(android.graphics.drawable.ColorDrawable) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) Property(android.util.Property) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) MediaActionDrawable(org.telegram.ui.Components.MediaActionDrawable) HorizontalScrollView(android.widget.HorizontalScrollView) Keep(androidx.annotation.Keep) CookieManager(android.webkit.CookieManager) RadioButton(org.telegram.ui.Components.RadioButton) Canvas(android.graphics.Canvas) TargetApi(android.annotation.TargetApi) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) AnimationProperties(org.telegram.ui.Components.AnimationProperties) MetricAffectingSpan(android.text.style.MetricAffectingSpan) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) NotificationCenter(org.telegram.messenger.NotificationCenter) TextPaintSpan(org.telegram.ui.Components.TextPaintSpan) HapticFeedbackConstants(android.view.HapticFeedbackConstants) StaticLayoutEx(org.telegram.ui.Components.StaticLayoutEx) Layout(android.text.Layout) TextPaint(android.text.TextPaint) TextPaintMarkSpan(org.telegram.ui.Components.TextPaintMarkSpan) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Paint(android.graphics.Paint) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) TextWatcher(android.text.TextWatcher) FileLoader(org.telegram.messenger.FileLoader) ViewPager(androidx.viewpager.widget.ViewPager) Dialog(android.app.Dialog) AlertsCreator(org.telegram.ui.Components.AlertsCreator) Editable(android.text.Editable) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) DisplayCutout(android.view.DisplayCutout) WebSettings(android.webkit.WebSettings) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) Menu(android.view.Menu) WebChromeClient(android.webkit.WebChromeClient) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) URLSpan(android.text.style.URLSpan) R(org.telegram.messenger.R) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) TextUtils(android.text.TextUtils) POSITION_FLAG_TOP(org.telegram.messenger.MessageObject.POSITION_FLAG_TOP) File(java.io.File) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) MessagesStorage(org.telegram.messenger.MessagesStorage) ValueAnimator(android.animation.ValueAnimator) Rect(android.graphics.Rect) ActionMode(android.view.ActionMode) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) AnimatedArrowDrawable(org.telegram.ui.Components.AnimatedArrowDrawable) RadialProgress2(org.telegram.ui.Components.RadialProgress2) URLDecoder(java.net.URLDecoder) Spannable(android.text.Spannable) WindowManager(android.view.WindowManager) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) Animator(android.animation.Animator) POSITION_FLAG_BOTTOM(org.telegram.messenger.MessageObject.POSITION_FLAG_BOTTOM) TypefaceSpan(org.telegram.ui.Components.TypefaceSpan) WebFile(org.telegram.messenger.WebFile) ViewConfiguration(android.view.ViewConfiguration) JSONObject(org.json.JSONObject) ApplicationLoader(org.telegram.messenger.ApplicationLoader) Locale(java.util.Locale) WebViewClient(android.webkit.WebViewClient) MediaController(org.telegram.messenger.MediaController) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) WebView(android.webkit.WebView) DataSetObserver(android.database.DataSetObserver) POSITION_FLAG_LEFT(org.telegram.messenger.MessageObject.POSITION_FLAG_LEFT) RectF(android.graphics.RectF) ImageLoader(org.telegram.messenger.ImageLoader) IntEvaluator(android.animation.IntEvaluator) ContextProgressView(org.telegram.ui.Components.ContextProgressView) Utilities(org.telegram.messenger.Utilities) ObjectAnimator(android.animation.ObjectAnimator) GridLayoutManagerFixed(androidx.recyclerview.widget.GridLayoutManagerFixed) ImageLocation(org.telegram.messenger.ImageLocation) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ViewAnimationUtils(android.view.ViewAnimationUtils) TextPaintImageReceiverSpan(org.telegram.ui.Components.TextPaintImageReceiverSpan) PorterDuff(android.graphics.PorterDuff) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) TableLayout(org.telegram.ui.Components.TableLayout) ViewGroup(android.view.ViewGroup) ShareAlert(org.telegram.ui.Components.ShareAlert) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) SparseArray(android.util.SparseArray) UserConfig(org.telegram.messenger.UserConfig) List(java.util.List) TextView(android.widget.TextView) WebPlayerView(org.telegram.ui.Components.WebPlayerView) WindowInsets(android.view.WindowInsets) LinkPath(org.telegram.ui.Components.LinkPath) EditorInfo(android.view.inputmethod.EditorInfo) DecelerateInterpolator(android.view.animation.DecelerateInterpolator) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) Typeface(android.graphics.Typeface) Context(android.content.Context) StaticLayout(android.text.StaticLayout) AccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) TextSelectionHelper(org.telegram.ui.Cells.TextSelectionHelper) Spanned(android.text.Spanned) KeyEvent(android.view.KeyEvent) GridLayoutManager(androidx.recyclerview.widget.GridLayoutManager) Theme(org.telegram.ui.ActionBar.Theme) TextPaintWebpageUrlSpan(org.telegram.ui.Components.TextPaintWebpageUrlSpan) PagerAdapter(androidx.viewpager.widget.PagerAdapter) BulletinFactory(org.telegram.ui.Components.BulletinFactory) TextPaintUrlSpan(org.telegram.ui.Components.TextPaintUrlSpan) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) HeaderCell(org.telegram.ui.Cells.HeaderCell) TranslateAlert(org.telegram.ui.Components.TranslateAlert) PixelFormat(android.graphics.PixelFormat) MenuItem(android.view.MenuItem) SeekBar(org.telegram.ui.Components.SeekBar) VelocityTracker(android.view.VelocityTracker) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) ActionBar(org.telegram.ui.ActionBar.ActionBar) TLObject(org.telegram.tgnet.TLObject) AnimatorSet(android.animation.AnimatorSet) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) Build(android.os.Build) AnchorSpan(org.telegram.ui.Components.AnchorSpan) SeekBarView(org.telegram.ui.Components.SeekBarView) DownloadController(org.telegram.messenger.DownloadController) Browser(org.telegram.messenger.browser.Browser) LongSparseArray(androidx.collection.LongSparseArray) LayoutHelper(org.telegram.ui.Components.LayoutHelper) TextureView(android.view.TextureView) FileLog(org.telegram.messenger.FileLog) LineProgressView(org.telegram.ui.Components.LineProgressView) MessagesController(org.telegram.messenger.MessagesController) Color(android.graphics.Color) SoundEffectConstants(android.view.SoundEffectConstants) CloseProgressDrawable2(org.telegram.ui.Components.CloseProgressDrawable2) Activity(android.app.Activity) ImageReceiver(org.telegram.messenger.ImageReceiver) Collections(java.util.Collections) RecyclerListView(org.telegram.ui.Components.RecyclerListView) DecelerateInterpolator(android.view.animation.DecelerateInterpolator) SpannableStringBuilder(android.text.SpannableStringBuilder) HeaderCell(org.telegram.ui.Cells.HeaderCell) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) CloseProgressDrawable2(org.telegram.ui.Components.CloseProgressDrawable2) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) TLRPC(org.telegram.tgnet.TLRPC) ImageView(android.widget.ImageView) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Canvas(android.graphics.Canvas) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) ActionMode(android.view.ActionMode) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) ContextProgressView(org.telegram.ui.Components.ContextProgressView) ShareAlert(org.telegram.ui.Components.ShareAlert) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) RecyclerListView(org.telegram.ui.Components.RecyclerListView) WindowManager(android.view.WindowManager) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) TextureView(android.view.TextureView) Menu(android.view.Menu) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) SharedPreferences(android.content.SharedPreferences) TextSelectionHelper(org.telegram.ui.Cells.TextSelectionHelper) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) MenuItem(android.view.MenuItem) ImageView(android.widget.ImageView) HorizontalScrollView(android.widget.HorizontalScrollView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) WebView(android.webkit.WebView) ContextProgressView(org.telegram.ui.Components.ContextProgressView) TextView(android.widget.TextView) WebPlayerView(org.telegram.ui.Components.WebPlayerView) SeekBarView(org.telegram.ui.Components.SeekBarView) TextureView(android.view.TextureView) LineProgressView(org.telegram.ui.Components.LineProgressView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) TLObject(org.telegram.tgnet.TLObject) FrameLayout(android.widget.FrameLayout) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) RecyclerView(androidx.recyclerview.widget.RecyclerView) LineProgressView(org.telegram.ui.Components.LineProgressView) MessageObject(org.telegram.messenger.MessageObject) LinearLayout(android.widget.LinearLayout)

Example 2 with ContextProgressView

use of org.telegram.ui.Components.ContextProgressView in project Telegram-FOSS by Telegram-FOSS-Team.

the class WebviewActivity method createView.

@SuppressLint({ "SetJavaScriptEnabled", "AddJavascriptInterface" })
@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == share) {
                if (currentMessageObject != null) {
                    currentMessageObject.messageOwner.with_my_score = false;
                    showDialog(ShareAlert.createShareAlert(getParentActivity(), currentMessageObject, null, false, linkToCopy, false));
                }
            } else if (id == open_in) {
                openGameInBrowser(currentUrl, currentMessageObject, getParentActivity(), short_param, currentBot);
            }
        }
    });
    ActionBarMenu menu = actionBar.createMenu();
    progressItem = menu.addItemWithWidth(share, R.drawable.share, AndroidUtilities.dp(54));
    if (type == TYPE_GAME) {
        ActionBarMenuItem menuItem = menu.addItem(0, R.drawable.ic_ab_other);
        menuItem.addSubItem(open_in, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp));
        actionBar.setTitle(currentGame);
        actionBar.setSubtitle("@" + currentBot);
        progressView = new ContextProgressView(context, 1);
        progressItem.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        progressView.setAlpha(0.0f);
        progressView.setScaleX(0.1f);
        progressView.setScaleY(0.1f);
        progressView.setVisibility(View.INVISIBLE);
    } else if (type == TYPE_STAT) {
        actionBar.setBackgroundColor(Theme.getColor(Theme.key_player_actionBar));
        actionBar.setItemsColor(Theme.getColor(Theme.key_player_actionBarItems), false);
        actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_player_actionBarSelector), false);
        actionBar.setTitleColor(Theme.getColor(Theme.key_player_actionBarTitle));
        actionBar.setSubtitleColor(Theme.getColor(Theme.key_player_actionBarSubtitle));
        actionBar.setTitle(LocaleController.getString("Statistics", R.string.Statistics));
        progressView = new ContextProgressView(context, 3);
        progressItem.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        progressView.setAlpha(1.0f);
        progressView.setScaleX(1.0f);
        progressView.setScaleY(1.0f);
        progressView.setVisibility(View.VISIBLE);
        progressItem.getContentView().setVisibility(View.GONE);
        progressItem.setEnabled(false);
    }
    webView = new WebView(context);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    fragmentView = new FrameLayout(context);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    if (Build.VERSION.SDK_INT >= 19) {
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }
    if (Build.VERSION.SDK_INT >= 21) {
        webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptThirdPartyCookies(webView, true);
        if (type == TYPE_GAME) {
            webView.addJavascriptInterface(new TelegramWebviewProxy(), "TelegramWebviewProxy");
        }
    }
    webView.setWebViewClient(new WebViewClient() {

        private boolean isInternalUrl(String url) {
            if (TextUtils.isEmpty(url)) {
                return false;
            }
            Uri uri = Uri.parse(url);
            if ("tg".equals(uri.getScheme())) {
                if (type == TYPE_STAT) {
                    try {
                        uri = Uri.parse(url.replace("tg:statsrefresh", "tg://telegram.org"));
                        reloadStats(uri.getQueryParameter("params"));
                    } catch (Throwable e) {
                        FileLog.e(e);
                    }
                } else {
                    finishFragment(false);
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        ComponentName componentName = new ComponentName(ApplicationLoader.applicationContext.getPackageName(), LaunchActivity.class.getName());
                        intent.setComponent(componentName);
                        intent.putExtra(android.provider.Browser.EXTRA_APPLICATION_ID, ApplicationLoader.applicationContext.getPackageName());
                        ApplicationLoader.applicationContext.startActivity(intent);
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
                return true;
            }
            return false;
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            if (isInternalUrl(url)) {
                return;
            }
            super.onLoadResource(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return isInternalUrl(url) || super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (progressView != null && progressView.getVisibility() == View.VISIBLE) {
                AnimatorSet animatorSet = new AnimatorSet();
                if (type == TYPE_GAME) {
                    progressItem.getContentView().setVisibility(View.VISIBLE);
                    progressItem.setEnabled(true);
                    animatorSet.playTogether(ObjectAnimator.ofFloat(progressView, "scaleX", 1.0f, 0.1f), ObjectAnimator.ofFloat(progressView, "scaleY", 1.0f, 0.1f), ObjectAnimator.ofFloat(progressView, "alpha", 1.0f, 0.0f), ObjectAnimator.ofFloat(progressItem.getContentView(), "scaleX", 0.0f, 1.0f), ObjectAnimator.ofFloat(progressItem.getContentView(), "scaleY", 0.0f, 1.0f), ObjectAnimator.ofFloat(progressItem.getContentView(), "alpha", 0.0f, 1.0f));
                } else {
                    animatorSet.playTogether(ObjectAnimator.ofFloat(progressView, "scaleX", 1.0f, 0.1f), ObjectAnimator.ofFloat(progressView, "scaleY", 1.0f, 0.1f), ObjectAnimator.ofFloat(progressView, "alpha", 1.0f, 0.0f));
                }
                animatorSet.addListener(new AnimatorListenerAdapter() {

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        if (type == TYPE_STAT) {
                            progressItem.setVisibility(View.GONE);
                        } else {
                            progressView.setVisibility(View.INVISIBLE);
                        }
                    }
                });
                animatorSet.setDuration(150);
                animatorSet.start();
            }
        }
    });
    frameLayout.addView(webView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    return fragmentView;
}
Also used : ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) ContextProgressView(org.telegram.ui.Components.ContextProgressView) Intent(android.content.Intent) AnimatorSet(android.animation.AnimatorSet) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) Uri(android.net.Uri) SuppressLint(android.annotation.SuppressLint) Animator(android.animation.Animator) ObjectAnimator(android.animation.ObjectAnimator) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) FrameLayout(android.widget.FrameLayout) ComponentName(android.content.ComponentName) WebView(android.webkit.WebView) ActionBar(org.telegram.ui.ActionBar.ActionBar) CookieManager(android.webkit.CookieManager) WebViewClient(android.webkit.WebViewClient) SuppressLint(android.annotation.SuppressLint)

Example 3 with ContextProgressView

use of org.telegram.ui.Components.ContextProgressView in project Telegram-FOSS by Telegram-FOSS-Team.

the class NewContactActivity method createView.

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("AddContactTitle", R.string.AddContactTitle));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == done_button) {
                if (donePressed) {
                    return;
                }
                if (firstNameField.length() == 0) {
                    Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                    if (v != null) {
                        v.vibrate(200);
                    }
                    AndroidUtilities.shakeView(firstNameField, 2, 0);
                    return;
                }
                if (codeField.length() == 0) {
                    Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                    if (v != null) {
                        v.vibrate(200);
                    }
                    AndroidUtilities.shakeView(codeField, 2, 0);
                    return;
                }
                if (phoneField.length() == 0) {
                    Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                    if (v != null) {
                        v.vibrate(200);
                    }
                    AndroidUtilities.shakeView(phoneField, 2, 0);
                    return;
                }
                donePressed = true;
                showEditDoneProgress(true, true);
                final TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts();
                final TLRPC.TL_inputPhoneContact inputPhoneContact = new TLRPC.TL_inputPhoneContact();
                inputPhoneContact.first_name = firstNameField.getText().toString();
                inputPhoneContact.last_name = lastNameField.getText().toString();
                inputPhoneContact.phone = "+" + codeField.getText().toString() + phoneField.getText().toString();
                req.contacts.add(inputPhoneContact);
                int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {
                    final TLRPC.TL_contacts_importedContacts res = (TLRPC.TL_contacts_importedContacts) response;
                    AndroidUtilities.runOnUIThread(() -> {
                        donePressed = false;
                        if (res != null) {
                            if (!res.users.isEmpty()) {
                                MessagesController.getInstance(currentAccount).putUsers(res.users, false);
                                MessagesController.openChatOrProfileWith(res.users.get(0), null, NewContactActivity.this, 1, true);
                            } else {
                                if (getParentActivity() == null) {
                                    return;
                                }
                                showEditDoneProgress(false, true);
                                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                                builder.setTitle(LocaleController.getString("ContactNotRegisteredTitle", R.string.ContactNotRegisteredTitle));
                                builder.setMessage(LocaleController.formatString("ContactNotRegistered", R.string.ContactNotRegistered, ContactsController.formatName(inputPhoneContact.first_name, inputPhoneContact.last_name)));
                                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                                builder.setPositiveButton(LocaleController.getString("Invite", R.string.Invite), (dialog, which) -> {
                                    try {
                                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", inputPhoneContact.phone, null));
                                        intent.putExtra("sms_body", ContactsController.getInstance(currentAccount).getInviteText(1));
                                        getParentActivity().startActivityForResult(intent, 500);
                                    } catch (Exception e) {
                                        FileLog.e(e);
                                    }
                                });
                                showDialog(builder.create());
                            }
                        } else {
                            showEditDoneProgress(false, true);
                            AlertsCreator.processError(currentAccount, error, NewContactActivity.this, req);
                        }
                    });
                }, ConnectionsManager.RequestFlagFailOnServerErrors);
                ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid);
            }
        }
    });
    avatarDrawable = new AvatarDrawable();
    avatarDrawable.setInfo(5, "", "");
    ActionBarMenu menu = actionBar.createMenu();
    editDoneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));
    editDoneItem.setContentDescription(LocaleController.getString("Done", R.string.Done));
    editDoneItemProgress = new ContextProgressView(context, 1);
    editDoneItem.addView(editDoneItemProgress, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    editDoneItemProgress.setVisibility(View.INVISIBLE);
    fragmentView = new ScrollView(context);
    contentLayout = new LinearLayout(context);
    contentLayout.setPadding(AndroidUtilities.dp(24), 0, AndroidUtilities.dp(24), 0);
    contentLayout.setOrientation(LinearLayout.VERTICAL);
    ((ScrollView) fragmentView).addView(contentLayout, LayoutHelper.createScroll(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP));
    contentLayout.setOnTouchListener((v, event) -> true);
    FrameLayout frameLayout = new FrameLayout(context);
    contentLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 24, 0, 0));
    avatarImage = new BackupImageView(context);
    avatarImage.setImageDrawable(avatarDrawable);
    frameLayout.addView(avatarImage, LayoutHelper.createFrame(60, 60, Gravity.LEFT | Gravity.TOP, 0, 9, 0, 0));
    boolean needInvalidateAvatar = false;
    firstNameField = new EditTextBoldCursor(context);
    firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    firstNameField.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    firstNameField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    firstNameField.setMaxLines(1);
    firstNameField.setLines(1);
    firstNameField.setSingleLine(true);
    firstNameField.setBackgroundDrawable(Theme.createEditTextDrawable(context, false));
    firstNameField.setGravity(Gravity.LEFT);
    firstNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
    firstNameField.setImeOptions(EditorInfo.IME_ACTION_NEXT);
    firstNameField.setHint(LocaleController.getString("FirstName", R.string.FirstName));
    firstNameField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    firstNameField.setCursorSize(AndroidUtilities.dp(20));
    firstNameField.setCursorWidth(1.5f);
    if (initialFirstName != null) {
        firstNameField.setText(initialFirstName);
        initialFirstName = null;
        needInvalidateAvatar = true;
    }
    frameLayout.addView(firstNameField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 34, Gravity.LEFT | Gravity.TOP, 84, 0, 0, 0));
    firstNameField.setOnEditorActionListener((textView, i, keyEvent) -> {
        if (i == EditorInfo.IME_ACTION_NEXT) {
            lastNameField.requestFocus();
            lastNameField.setSelection(lastNameField.length());
            return true;
        }
        return false;
    });
    firstNameField.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            invalidateAvatar();
        }
    });
    lastNameField = new EditTextBoldCursor(context);
    lastNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    lastNameField.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    lastNameField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    lastNameField.setBackgroundDrawable(Theme.createEditTextDrawable(context, false));
    lastNameField.setMaxLines(1);
    lastNameField.setLines(1);
    lastNameField.setSingleLine(true);
    lastNameField.setGravity(Gravity.LEFT);
    lastNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
    lastNameField.setImeOptions(EditorInfo.IME_ACTION_NEXT);
    lastNameField.setHint(LocaleController.getString("LastName", R.string.LastName));
    lastNameField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    lastNameField.setCursorSize(AndroidUtilities.dp(20));
    lastNameField.setCursorWidth(1.5f);
    if (initialLastName != null) {
        lastNameField.setText(initialLastName);
        initialLastName = null;
        needInvalidateAvatar = true;
    }
    frameLayout.addView(lastNameField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 34, Gravity.LEFT | Gravity.TOP, 84, 44, 0, 0));
    lastNameField.setOnEditorActionListener((textView, i, keyEvent) -> {
        if (i == EditorInfo.IME_ACTION_NEXT) {
            phoneField.requestFocus();
            phoneField.setSelection(phoneField.length());
            return true;
        }
        return false;
    });
    lastNameField.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            invalidateAvatar();
        }
    });
    if (needInvalidateAvatar) {
        invalidateAvatar();
    }
    countryButton = new TextView(context);
    countryButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    countryButton.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4));
    countryButton.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    countryButton.setMaxLines(1);
    countryButton.setSingleLine(true);
    countryButton.setEllipsize(TextUtils.TruncateAt.END);
    countryButton.setGravity(Gravity.LEFT | Gravity.CENTER_HORIZONTAL);
    countryButton.setBackground(Theme.getSelectorDrawable(true));
    contentLayout.addView(countryButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 0, 24, 0, 14));
    countryButton.setOnClickListener(view -> {
        CountrySelectActivity fragment = new CountrySelectActivity(true);
        fragment.setCountrySelectActivityDelegate((country) -> {
            selectCountry(country.name);
            phoneField.requestFocus();
            phoneField.setSelection(phoneField.length());
        });
        presentFragment(fragment);
    });
    lineView = new View(context);
    lineView.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8), 0);
    lineView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayLine));
    contentLayout.addView(lineView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 1, 0, -17.5f, 0, 0));
    LinearLayout linearLayout2 = new LinearLayout(context);
    linearLayout2.setOrientation(HORIZONTAL);
    contentLayout.addView(linearLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 20, 0, 0));
    textView = new TextView(context);
    textView.setText("+");
    textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    textView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
    linearLayout2.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
    codeField = new EditTextBoldCursor(context);
    codeField.setInputType(InputType.TYPE_CLASS_PHONE);
    codeField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    codeField.setBackgroundDrawable(Theme.createEditTextDrawable(context, false));
    codeField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    codeField.setCursorSize(AndroidUtilities.dp(20));
    codeField.setCursorWidth(1.5f);
    codeField.setPadding(AndroidUtilities.dp(10), 0, 0, 0);
    codeField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    codeField.setMaxLines(1);
    codeField.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
    codeField.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    linearLayout2.addView(codeField, LayoutHelper.createLinear(55, 36, -9, 0, 16, 0));
    codeField.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (ignoreOnTextChange) {
                return;
            }
            ignoreOnTextChange = true;
            String text = PhoneFormat.stripExceptNumbers(codeField.getText().toString());
            codeField.setText(text);
            if (text.length() == 0) {
                countryButton.setText(LocaleController.getString("ChooseCountry", R.string.ChooseCountry));
                phoneField.setHintText(null);
                countryState = 1;
            } else {
                String country;
                boolean ok = false;
                String textToSet = null;
                if (text.length() > 4) {
                    ignoreOnTextChange = true;
                    for (int a = 4; a >= 1; a--) {
                        String sub = text.substring(0, a);
                        country = codesMap.get(sub);
                        if (country != null) {
                            ok = true;
                            textToSet = text.substring(a) + phoneField.getText().toString();
                            codeField.setText(text = sub);
                            break;
                        }
                    }
                    if (!ok) {
                        ignoreOnTextChange = true;
                        textToSet = text.substring(1) + phoneField.getText().toString();
                        codeField.setText(text = text.substring(0, 1));
                    }
                }
                country = codesMap.get(text);
                if (country != null) {
                    int index = countriesArray.indexOf(country);
                    if (index != -1) {
                        ignoreSelection = true;
                        countryButton.setText(countriesArray.get(index));
                        String hint = phoneFormatMap.get(text);
                        phoneField.setHintText(hint != null ? hint.replace('X', '–') : null);
                        countryState = 0;
                    } else {
                        countryButton.setText(LocaleController.getString("WrongCountry", R.string.WrongCountry));
                        phoneField.setHintText(null);
                        countryState = 2;
                    }
                } else {
                    countryButton.setText(LocaleController.getString("WrongCountry", R.string.WrongCountry));
                    phoneField.setHintText(null);
                    countryState = 2;
                }
                if (!ok) {
                    codeField.setSelection(codeField.getText().length());
                }
                if (textToSet != null) {
                    if (initialPhoneNumber == null) {
                        phoneField.requestFocus();
                    }
                    phoneField.setText(textToSet);
                    phoneField.setSelection(phoneField.length());
                }
            }
            ignoreOnTextChange = false;
        }
    });
    codeField.setOnEditorActionListener((textView, i, keyEvent) -> {
        if (i == EditorInfo.IME_ACTION_NEXT) {
            phoneField.requestFocus();
            phoneField.setSelection(phoneField.length());
            return true;
        }
        return false;
    });
    phoneField = new HintEditText(context);
    phoneField.setInputType(InputType.TYPE_CLASS_PHONE);
    phoneField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    phoneField.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    phoneField.setBackgroundDrawable(Theme.createEditTextDrawable(context, false));
    phoneField.setPadding(0, 0, 0, 0);
    phoneField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    phoneField.setCursorSize(AndroidUtilities.dp(20));
    phoneField.setCursorWidth(1.5f);
    phoneField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    phoneField.setMaxLines(1);
    phoneField.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
    phoneField.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    linearLayout2.addView(phoneField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36));
    phoneField.addTextChangedListener(new TextWatcher() {

        private int characterAction = -1;

        private int actionPosition;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (count == 0 && after == 1) {
                characterAction = 1;
            } else if (count == 1 && after == 0) {
                if (s.charAt(start) == ' ' && start > 0) {
                    characterAction = 3;
                    actionPosition = start - 1;
                } else {
                    characterAction = 2;
                }
            } else {
                characterAction = -1;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (ignoreOnPhoneChange) {
                return;
            }
            int start = phoneField.getSelectionStart();
            String phoneChars = "0123456789";
            String str = phoneField.getText().toString();
            if (characterAction == 3) {
                str = str.substring(0, actionPosition) + str.substring(actionPosition + 1);
                start--;
            }
            StringBuilder builder = new StringBuilder(str.length());
            for (int a = 0; a < str.length(); a++) {
                String ch = str.substring(a, a + 1);
                if (phoneChars.contains(ch)) {
                    builder.append(ch);
                }
            }
            ignoreOnPhoneChange = true;
            String hint = phoneField.getHintText();
            if (hint != null) {
                for (int a = 0; a < builder.length(); a++) {
                    if (a < hint.length()) {
                        if (hint.charAt(a) == ' ') {
                            builder.insert(a, ' ');
                            a++;
                            if (start == a && characterAction != 2 && characterAction != 3) {
                                start++;
                            }
                        }
                    } else {
                        builder.insert(a, ' ');
                        if (start == a + 1 && characterAction != 2 && characterAction != 3) {
                            start++;
                        }
                        break;
                    }
                }
            }
            phoneField.setText(builder);
            if (start >= 0) {
                phoneField.setSelection(Math.min(start, phoneField.length()));
            }
            phoneField.onTextChange();
            ignoreOnPhoneChange = false;
        }
    });
    phoneField.setOnEditorActionListener((textView, i, keyEvent) -> {
        if (i == EditorInfo.IME_ACTION_DONE) {
            editDoneItem.performClick();
            return true;
        }
        return false;
    });
    phoneField.setOnKeyListener((v, keyCode, event) -> {
        if (keyCode == KeyEvent.KEYCODE_DEL && phoneField.length() == 0) {
            codeField.requestFocus();
            codeField.setSelection(codeField.length());
            codeField.dispatchKeyEvent(event);
            return true;
        }
        return false;
    });
    HashMap<String, String> languageMap = new HashMap<>();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().getAssets().open("countries.txt")));
        String line;
        while ((line = reader.readLine()) != null) {
            String[] args = line.split(";");
            countriesArray.add(0, args[2]);
            countriesMap.put(args[2], args[0]);
            codesMap.put(args[0], args[2]);
            if (args.length > 3) {
                phoneFormatMap.put(args[0], args[3]);
            }
            languageMap.put(args[1], args[2]);
        }
        reader.close();
    } catch (Exception e) {
        FileLog.e(e);
    }
    Collections.sort(countriesArray, String::compareTo);
    if (!TextUtils.isEmpty(initialPhoneNumber)) {
        TLRPC.User user = getUserConfig().getCurrentUser();
        if (initialPhoneNumber.startsWith("+")) {
            codeField.setText(initialPhoneNumber.substring(1));
        } else if (initialPhoneNumberWithCountryCode || user == null || TextUtils.isEmpty(user.phone)) {
            codeField.setText(initialPhoneNumber);
        } else {
            String phone = user.phone;
            for (int a = 4; a >= 1; a--) {
                String sub = phone.substring(0, a);
                String country = codesMap.get(sub);
                if (country != null) {
                    codeField.setText(sub);
                    break;
                }
            }
            phoneField.setText(initialPhoneNumber);
        }
        initialPhoneNumber = null;
    } else {
        String country = null;
        try {
            TelephonyManager telephonyManager = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE);
            if (telephonyManager != null) {
                country = telephonyManager.getSimCountryIso().toUpperCase();
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
        if (country != null) {
            String countryName = languageMap.get(country);
            if (countryName != null) {
                int index = countriesArray.indexOf(countryName);
                if (index != -1) {
                    codeField.setText(countriesMap.get(countryName));
                    countryState = 0;
                }
            }
        }
        if (codeField.length() == 0) {
            countryButton.setText(LocaleController.getString("ChooseCountry", R.string.ChooseCountry));
            phoneField.setHintText(null);
            countryState = 1;
        }
    }
    return fragmentView;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) HashMap(java.util.HashMap) ContextProgressView(org.telegram.ui.Components.ContextProgressView) TLRPC(org.telegram.tgnet.TLRPC) TelephonyManager(android.telephony.TelephonyManager) BackupImageView(org.telegram.ui.Components.BackupImageView) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) TextView(android.widget.TextView) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) ActionBar(org.telegram.ui.ActionBar.ActionBar) InputStreamReader(java.io.InputStreamReader) Intent(android.content.Intent) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) View(android.view.View) AdapterView(android.widget.AdapterView) ContextProgressView(org.telegram.ui.Components.ContextProgressView) TextView(android.widget.TextView) BackupImageView(org.telegram.ui.Components.BackupImageView) ScrollView(android.widget.ScrollView) HintEditText(org.telegram.ui.Components.HintEditText) ScrollView(android.widget.ScrollView) FrameLayout(android.widget.FrameLayout) BufferedReader(java.io.BufferedReader) Vibrator(android.os.Vibrator) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) LinearLayout(android.widget.LinearLayout)

Example 4 with ContextProgressView

use of org.telegram.ui.Components.ContextProgressView in project Telegram-FOSS by Telegram-FOSS-Team.

the class GroupStickersActivity method createView.

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("GroupStickers", R.string.GroupStickers));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == done_button) {
                if (donePressed) {
                    return;
                }
                donePressed = true;
                if (searching) {
                    showEditDoneProgress(true);
                    return;
                }
                saveStickerSet();
            }
        }
    });
    ActionBarMenu menu = actionBar.createMenu();
    doneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56), LocaleController.getString("Done", R.string.Done));
    progressView = new ContextProgressView(context, 1);
    progressView.setAlpha(0.0f);
    progressView.setScaleX(0.1f);
    progressView.setScaleY(0.1f);
    progressView.setVisibility(View.INVISIBLE);
    doneItem.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    nameContainer = new LinearLayout(context) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(42), MeasureSpec.EXACTLY));
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if (selectedStickerSet != null) {
                canvas.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1, Theme.dividerPaint);
            }
        }
    };
    nameContainer.setWeightSum(1.0f);
    nameContainer.setWillNotDraw(false);
    nameContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    nameContainer.setOrientation(LinearLayout.HORIZONTAL);
    nameContainer.setPadding(AndroidUtilities.dp(17), 0, AndroidUtilities.dp(14), 0);
    editText = new EditTextBoldCursor(context);
    editText.setText(MessagesController.getInstance(currentAccount).linkPrefix + "/addstickers/");
    editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
    editText.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    editText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    editText.setMaxLines(1);
    editText.setLines(1);
    editText.setEnabled(false);
    editText.setFocusable(false);
    editText.setBackgroundDrawable(null);
    editText.setPadding(0, 0, 0, 0);
    editText.setGravity(Gravity.CENTER_VERTICAL);
    editText.setSingleLine(true);
    editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
    editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
    nameContainer.addView(editText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 42));
    usernameTextView = new EditTextBoldCursor(context);
    usernameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
    usernameTextView.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    usernameTextView.setCursorSize(AndroidUtilities.dp(20));
    usernameTextView.setCursorWidth(1.5f);
    usernameTextView.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    usernameTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    usernameTextView.setMaxLines(1);
    usernameTextView.setLines(1);
    usernameTextView.setBackgroundDrawable(null);
    usernameTextView.setPadding(0, 0, 0, 0);
    usernameTextView.setSingleLine(true);
    usernameTextView.setGravity(Gravity.CENTER_VERTICAL);
    usernameTextView.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
    usernameTextView.setImeOptions(EditorInfo.IME_ACTION_DONE);
    usernameTextView.setHint(LocaleController.getString("ChooseStickerSetPlaceholder", R.string.ChooseStickerSetPlaceholder));
    usernameTextView.addTextChangedListener(new TextWatcher() {

        boolean ignoreTextChange;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (eraseImageView != null) {
                eraseImageView.setVisibility(s.length() > 0 ? View.VISIBLE : View.INVISIBLE);
            }
            if (ignoreTextChange || ignoreTextChanges) {
                return;
            }
            if (s.length() > 5) {
                ignoreTextChange = true;
                try {
                    Uri uri = Uri.parse(s.toString());
                    if (uri != null) {
                        List<String> segments = uri.getPathSegments();
                        if (segments.size() == 2) {
                            if (segments.get(0).toLowerCase().equals("addstickers")) {
                                usernameTextView.setText(segments.get(1));
                                usernameTextView.setSelection(usernameTextView.length());
                            }
                        }
                    }
                } catch (Exception ignore) {
                }
                ignoreTextChange = false;
            }
            resolveStickerSet();
        }
    });
    nameContainer.addView(usernameTextView, LayoutHelper.createLinear(0, 42, 1.0f));
    eraseImageView = new ImageView(context);
    eraseImageView.setScaleType(ImageView.ScaleType.CENTER);
    eraseImageView.setImageResource(R.drawable.ic_close_white);
    eraseImageView.setPadding(AndroidUtilities.dp(16), 0, 0, 0);
    eraseImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3), PorterDuff.Mode.MULTIPLY));
    eraseImageView.setVisibility(View.INVISIBLE);
    eraseImageView.setOnClickListener(v -> {
        searchWas = false;
        selectedStickerSet = null;
        usernameTextView.setText("");
        updateRows();
    });
    nameContainer.addView(eraseImageView, LayoutHelper.createLinear(42, 42, 0.0f));
    if (info != null && info.stickerset != null) {
        ignoreTextChanges = true;
        usernameTextView.setText(info.stickerset.short_name);
        usernameTextView.setSelection(usernameTextView.length());
        ignoreTextChanges = false;
    }
    listAdapter = new ListAdapter(context);
    fragmentView = new FrameLayout(context);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
    listView = new RecyclerListView(context);
    listView.setFocusable(true);
    listView.setItemAnimator(null);
    listView.setLayoutAnimation(null);
    layoutManager = new LinearLayoutManager(context) {

        @Override
        public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect, boolean immediate, boolean focusedChildVisible) {
            return false;
        }

        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    listView.setLayoutManager(layoutManager);
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener((view, position) -> {
        if (getParentActivity() == null) {
            return;
        }
        if (position == selectedStickerRow) {
            if (selectedStickerSet == null) {
                return;
            }
            showDialog(new StickersAlert(getParentActivity(), GroupStickersActivity.this, null, selectedStickerSet, null));
        } else if (position >= stickersStartRow && position < stickersEndRow) {
            boolean needScroll = selectedStickerRow == -1;
            int row = layoutManager.findFirstVisibleItemPosition();
            int top = Integer.MAX_VALUE;
            RecyclerListView.Holder holder = (RecyclerListView.Holder) listView.findViewHolderForAdapterPosition(row);
            if (holder != null) {
                top = holder.itemView.getTop();
            }
            selectedStickerSet = MediaDataController.getInstance(currentAccount).getStickerSets(MediaDataController.TYPE_IMAGE).get(position - stickersStartRow);
            ignoreTextChanges = true;
            usernameTextView.setText(selectedStickerSet.set.short_name);
            usernameTextView.setSelection(usernameTextView.length());
            ignoreTextChanges = false;
            AndroidUtilities.hideKeyboard(usernameTextView);
            updateRows();
            if (needScroll && top != Integer.MAX_VALUE) {
                layoutManager.scrollToPositionWithOffset(row + 1, top);
            }
        }
    });
    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        }
    });
    return fragmentView;
}
Also used : ContextProgressView(org.telegram.ui.Components.ContextProgressView) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) RecyclerListView(org.telegram.ui.Components.RecyclerListView) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) Uri(android.net.Uri) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) List(java.util.List) ArrayList(java.util.ArrayList) ImageView(android.widget.ImageView) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) ActionBar(org.telegram.ui.ActionBar.ActionBar) Rect(android.graphics.Rect) Canvas(android.graphics.Canvas) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) ContextProgressView(org.telegram.ui.Components.ContextProgressView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) StickersAlert(org.telegram.ui.Components.StickersAlert) FrameLayout(android.widget.FrameLayout) RecyclerView(androidx.recyclerview.widget.RecyclerView) LinearLayout(android.widget.LinearLayout)

Example 5 with ContextProgressView

use of org.telegram.ui.Components.ContextProgressView in project Telegram-FOSS by Telegram-FOSS-Team.

the class ThemeDescription method setColor.

public void setColor(int color, boolean useDefault, boolean save) {
    if (save) {
        Theme.setColor(currentKey, color, useDefault);
    }
    currentColor = color;
    if (alphaOverride > 0) {
        color = Color.argb(alphaOverride, Color.red(color), Color.green(color), Color.blue(color));
    }
    if (paintToUpdate != null) {
        for (int a = 0; a < paintToUpdate.length; a++) {
            if ((changeFlags & FLAG_LINKCOLOR) != 0 && paintToUpdate[a] instanceof TextPaint) {
                ((TextPaint) paintToUpdate[a]).linkColor = color;
            } else {
                paintToUpdate[a].setColor(color);
            }
        }
    }
    if (drawablesToUpdate != null) {
        for (int a = 0; a < drawablesToUpdate.length; a++) {
            if (drawablesToUpdate[a] == null) {
                continue;
            }
            if (drawablesToUpdate[a] instanceof BackDrawable) {
                ((BackDrawable) drawablesToUpdate[a]).setColor(color);
            } else if (drawablesToUpdate[a] instanceof ScamDrawable) {
                ((ScamDrawable) drawablesToUpdate[a]).setColor(color);
            } else if (drawablesToUpdate[a] instanceof RLottieDrawable) {
                if (lottieLayerName != null) {
                    ((RLottieDrawable) drawablesToUpdate[a]).setLayerColor(lottieLayerName + ".**", color);
                }
            } else if (drawablesToUpdate[a] instanceof CombinedDrawable) {
                if ((changeFlags & FLAG_BACKGROUNDFILTER) != 0) {
                    ((CombinedDrawable) drawablesToUpdate[a]).getBackground().setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
                } else {
                    ((CombinedDrawable) drawablesToUpdate[a]).getIcon().setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
                }
            } else if (drawablesToUpdate[a] instanceof AvatarDrawable) {
                ((AvatarDrawable) drawablesToUpdate[a]).setColor(color);
            } else if (drawablesToUpdate[a] instanceof AnimatedArrowDrawable) {
                ((AnimatedArrowDrawable) drawablesToUpdate[a]).setColor(color);
            } else {
                drawablesToUpdate[a].setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
            }
        }
    }
    if (viewToInvalidate != null && listClasses == null && listClassesFieldName == null) {
        if ((changeFlags & FLAG_CHECKTAG) == 0 || checkTag(currentKey, viewToInvalidate)) {
            if ((changeFlags & FLAG_BACKGROUND) != 0) {
                Drawable background = viewToInvalidate.getBackground();
                if (background instanceof MessageBackgroundDrawable) {
                    ((MessageBackgroundDrawable) background).setColor(color);
                    ((MessageBackgroundDrawable) background).setCustomPaint(null);
                } else {
                    viewToInvalidate.setBackgroundColor(color);
                }
            }
            if ((changeFlags & FLAG_BACKGROUNDFILTER) != 0) {
                if ((changeFlags & FLAG_PROGRESSBAR) != 0) {
                    if (viewToInvalidate instanceof EditTextBoldCursor) {
                        ((EditTextBoldCursor) viewToInvalidate).setErrorLineColor(color);
                    }
                } else {
                    Drawable drawable = viewToInvalidate.getBackground();
                    if (drawable instanceof CombinedDrawable) {
                        if ((changeFlags & FLAG_DRAWABLESELECTEDSTATE) != 0) {
                            drawable = ((CombinedDrawable) drawable).getBackground();
                        } else {
                            drawable = ((CombinedDrawable) drawable).getIcon();
                        }
                    }
                    if (drawable != null) {
                        if (drawable instanceof StateListDrawable || Build.VERSION.SDK_INT >= 21 && drawable instanceof RippleDrawable) {
                            Theme.setSelectorDrawableColor(drawable, color, (changeFlags & FLAG_DRAWABLESELECTEDSTATE) != 0);
                        } else if (drawable instanceof ShapeDrawable) {
                            ((ShapeDrawable) drawable).getPaint().setColor(color);
                        } else {
                            drawable.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
                        }
                    }
                }
            }
        }
    }
    if (viewToInvalidate instanceof ActionBar) {
        if ((changeFlags & FLAG_AB_ITEMSCOLOR) != 0) {
            ((ActionBar) viewToInvalidate).setItemsColor(color, false);
        }
        if ((changeFlags & FLAG_AB_TITLECOLOR) != 0) {
            ((ActionBar) viewToInvalidate).setTitleColor(color);
        }
        if ((changeFlags & FLAG_AB_SELECTORCOLOR) != 0) {
            ((ActionBar) viewToInvalidate).setItemsBackgroundColor(color, false);
        }
        if ((changeFlags & FLAG_AB_AM_SELECTORCOLOR) != 0) {
            ((ActionBar) viewToInvalidate).setItemsBackgroundColor(color, true);
        }
        if ((changeFlags & FLAG_AB_AM_ITEMSCOLOR) != 0) {
            ((ActionBar) viewToInvalidate).setItemsColor(color, true);
        }
        if ((changeFlags & FLAG_AB_SUBTITLECOLOR) != 0) {
            ((ActionBar) viewToInvalidate).setSubtitleColor(color);
        }
        if ((changeFlags & FLAG_AB_AM_BACKGROUND) != 0) {
            ((ActionBar) viewToInvalidate).setActionModeColor(color);
        }
        if ((changeFlags & FLAG_AB_AM_TOPBACKGROUND) != 0) {
            ((ActionBar) viewToInvalidate).setActionModeTopColor(color);
        }
        if ((changeFlags & FLAG_AB_SEARCHPLACEHOLDER) != 0) {
            ((ActionBar) viewToInvalidate).setSearchTextColor(color, true);
        }
        if ((changeFlags & FLAG_AB_SEARCH) != 0) {
            ((ActionBar) viewToInvalidate).setSearchTextColor(color, false);
        }
        if ((changeFlags & FLAG_AB_SUBMENUITEM) != 0) {
            ((ActionBar) viewToInvalidate).setPopupItemsColor(color, (changeFlags & FLAG_IMAGECOLOR) != 0, false);
        }
        if ((changeFlags & FLAG_AB_SUBMENUBACKGROUND) != 0) {
            ((ActionBar) viewToInvalidate).setPopupBackgroundColor(color, false);
        }
    }
    if (viewToInvalidate instanceof VideoTimelineView) {
        ((VideoTimelineView) viewToInvalidate).setColor(color);
    }
    if (viewToInvalidate instanceof EmptyTextProgressView) {
        if ((changeFlags & FLAG_TEXTCOLOR) != 0) {
            ((EmptyTextProgressView) viewToInvalidate).setTextColor(color);
        } else if ((changeFlags & FLAG_PROGRESSBAR) != 0) {
            ((EmptyTextProgressView) viewToInvalidate).setProgressBarColor(color);
        }
    }
    if (viewToInvalidate instanceof RadialProgressView) {
        ((RadialProgressView) viewToInvalidate).setProgressColor(color);
    } else if (viewToInvalidate instanceof LineProgressView) {
        if ((changeFlags & FLAG_PROGRESSBAR) != 0) {
            ((LineProgressView) viewToInvalidate).setProgressColor(color);
        } else {
            ((LineProgressView) viewToInvalidate).setBackColor(color);
        }
    } else if (viewToInvalidate instanceof ContextProgressView) {
        ((ContextProgressView) viewToInvalidate).updateColors();
    } else if (viewToInvalidate instanceof SeekBarView) {
        if ((changeFlags & FLAG_PROGRESSBAR) != 0) {
            ((SeekBarView) viewToInvalidate).setOuterColor(color);
        }
    }
    if ((changeFlags & FLAG_TEXTCOLOR) != 0) {
        if ((changeFlags & FLAG_CHECKTAG) == 0 || checkTag(currentKey, viewToInvalidate)) {
            if (viewToInvalidate instanceof TextView) {
                ((TextView) viewToInvalidate).setTextColor(color);
            } else if (viewToInvalidate instanceof NumberTextView) {
                ((NumberTextView) viewToInvalidate).setTextColor(color);
            } else if (viewToInvalidate instanceof SimpleTextView) {
                ((SimpleTextView) viewToInvalidate).setTextColor(color);
            } else if (viewToInvalidate instanceof ChatBigEmptyView) {
                ((ChatBigEmptyView) viewToInvalidate).setTextColor(color);
            }
        }
    }
    if ((changeFlags & FLAG_CURSORCOLOR) != 0) {
        if (viewToInvalidate instanceof EditTextBoldCursor) {
            ((EditTextBoldCursor) viewToInvalidate).setCursorColor(color);
        }
    }
    if ((changeFlags & FLAG_HINTTEXTCOLOR) != 0) {
        if (viewToInvalidate instanceof EditTextBoldCursor) {
            if ((changeFlags & FLAG_PROGRESSBAR) != 0) {
                ((EditTextBoldCursor) viewToInvalidate).setHeaderHintColor(color);
            } else {
                ((EditTextBoldCursor) viewToInvalidate).setHintColor(color);
            }
        } else if (viewToInvalidate instanceof EditText) {
            ((EditText) viewToInvalidate).setHintTextColor(color);
        }
    }
    if (viewToInvalidate != null && (changeFlags & FLAG_SERVICEBACKGROUND) != 0) {
    }
    if ((changeFlags & FLAG_IMAGECOLOR) != 0) {
        if ((changeFlags & FLAG_CHECKTAG) == 0 || checkTag(currentKey, viewToInvalidate)) {
            if (viewToInvalidate instanceof ImageView) {
                if ((changeFlags & FLAG_USEBACKGROUNDDRAWABLE) != 0) {
                    Drawable drawable = ((ImageView) viewToInvalidate).getDrawable();
                    if (drawable instanceof StateListDrawable || Build.VERSION.SDK_INT >= 21 && drawable instanceof RippleDrawable) {
                        Theme.setSelectorDrawableColor(drawable, color, (changeFlags & FLAG_DRAWABLESELECTEDSTATE) != 0);
                    }
                } else {
                    ((ImageView) viewToInvalidate).setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
                }
            } else if (viewToInvalidate instanceof BackupImageView) {
            // ((BackupImageView) viewToInvalidate).setResourceImageColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
            } else if (viewToInvalidate instanceof SimpleTextView) {
                SimpleTextView textView = (SimpleTextView) viewToInvalidate;
                textView.setSideDrawablesColor(color);
            } else if (viewToInvalidate instanceof TextView) {
                Drawable[] drawables = ((TextView) viewToInvalidate).getCompoundDrawables();
                if (drawables != null) {
                    for (int a = 0; a < drawables.length; a++) {
                        if (drawables[a] != null) {
                            drawables[a].setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
                        }
                    }
                }
            }
        }
    }
    if (viewToInvalidate instanceof ScrollView) {
        if ((changeFlags & FLAG_LISTGLOWCOLOR) != 0) {
            AndroidUtilities.setScrollViewEdgeEffectColor((ScrollView) viewToInvalidate, color);
        }
    }
    if (viewToInvalidate instanceof ViewPager) {
        if ((changeFlags & FLAG_LISTGLOWCOLOR) != 0) {
            AndroidUtilities.setViewPagerEdgeEffectColor((ViewPager) viewToInvalidate, color);
        }
    }
    if (viewToInvalidate instanceof RecyclerListView) {
        RecyclerListView recyclerListView = (RecyclerListView) viewToInvalidate;
        if ((changeFlags & FLAG_SELECTOR) != 0) {
            recyclerListView.setListSelectorColor(color);
        }
        if ((changeFlags & FLAG_FASTSCROLL) != 0) {
            recyclerListView.updateFastScrollColors();
        }
        if ((changeFlags & FLAG_LISTGLOWCOLOR) != 0) {
            recyclerListView.setGlowColor(color);
        }
        if ((changeFlags & FLAG_SECTIONS) != 0) {
            ArrayList<View> headers = recyclerListView.getHeaders();
            if (headers != null) {
                for (int a = 0; a < headers.size(); a++) {
                    processViewColor(headers.get(a), color);
                }
            }
            headers = recyclerListView.getHeadersCache();
            if (headers != null) {
                for (int a = 0; a < headers.size(); a++) {
                    processViewColor(headers.get(a), color);
                }
            }
            View header = recyclerListView.getPinnedHeader();
            if (header != null) {
                processViewColor(header, color);
            }
        }
    } else if (viewToInvalidate != null && (listClasses == null || listClasses.length == 0)) {
        if ((changeFlags & FLAG_SELECTOR) != 0) {
            viewToInvalidate.setBackgroundDrawable(Theme.getSelectorDrawable(false));
        } else if ((changeFlags & FLAG_SELECTORWHITE) != 0) {
            viewToInvalidate.setBackgroundDrawable(Theme.getSelectorDrawable(true));
        }
    }
    if (listClasses != null) {
        if (viewToInvalidate instanceof RecyclerListView) {
            RecyclerListView recyclerListView = (RecyclerListView) viewToInvalidate;
            recyclerListView.getRecycledViewPool().clear();
            int count = recyclerListView.getHiddenChildCount();
            for (int a = 0; a < count; a++) {
                processViewColor(recyclerListView.getHiddenChildAt(a), color);
            }
            count = recyclerListView.getCachedChildCount();
            for (int a = 0; a < count; a++) {
                processViewColor(recyclerListView.getCachedChildAt(a), color);
            }
            count = recyclerListView.getAttachedScrapChildCount();
            for (int a = 0; a < count; a++) {
                processViewColor(recyclerListView.getAttachedScrapChildAt(a), color);
            }
        }
        if (viewToInvalidate instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) viewToInvalidate;
            int count = viewGroup.getChildCount();
            for (int a = 0; a < count; a++) {
                processViewColor(viewGroup.getChildAt(a), color);
            }
        }
        processViewColor(viewToInvalidate, color);
    }
    if (delegate != null) {
        delegate.didSetColor();
    }
    if (viewToInvalidate != null) {
        viewToInvalidate.invalidate();
    }
}
Also used : ContextProgressView(org.telegram.ui.Components.ContextProgressView) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) StateListDrawable(android.graphics.drawable.StateListDrawable) RecyclerListView(org.telegram.ui.Components.RecyclerListView) ScamDrawable(org.telegram.ui.Components.ScamDrawable) MessageBackgroundDrawable(org.telegram.ui.Components.MessageBackgroundDrawable) BackupImageView(org.telegram.ui.Components.BackupImageView) TextView(android.widget.TextView) NumberTextView(org.telegram.ui.Components.NumberTextView) NumberTextView(org.telegram.ui.Components.NumberTextView) ImageView(android.widget.ImageView) RLottieImageView(org.telegram.ui.Components.RLottieImageView) BackupImageView(org.telegram.ui.Components.BackupImageView) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) VideoTimelineView(org.telegram.ui.Components.VideoTimelineView) EditText(android.widget.EditText) RadialProgressView(org.telegram.ui.Components.RadialProgressView) ChatBigEmptyView(org.telegram.ui.Components.ChatBigEmptyView) ViewGroup(android.view.ViewGroup) AnimatedArrowDrawable(org.telegram.ui.Components.AnimatedArrowDrawable) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) StateListDrawable(android.graphics.drawable.StateListDrawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) LetterDrawable(org.telegram.ui.Components.LetterDrawable) ScamDrawable(org.telegram.ui.Components.ScamDrawable) RippleDrawable(android.graphics.drawable.RippleDrawable) MessageBackgroundDrawable(org.telegram.ui.Components.MessageBackgroundDrawable) GradientDrawable(android.graphics.drawable.GradientDrawable) ShapeDrawable(android.graphics.drawable.ShapeDrawable) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) SeekBarView(org.telegram.ui.Components.SeekBarView) ViewPager(androidx.viewpager.widget.ViewPager) ImageView(android.widget.ImageView) RadialProgressView(org.telegram.ui.Components.RadialProgressView) View(android.view.View) ContextProgressView(org.telegram.ui.Components.ContextProgressView) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) RLottieImageView(org.telegram.ui.Components.RLottieImageView) TextView(android.widget.TextView) VideoTimelineView(org.telegram.ui.Components.VideoTimelineView) ChatBigEmptyView(org.telegram.ui.Components.ChatBigEmptyView) SeekBarView(org.telegram.ui.Components.SeekBarView) BackupImageView(org.telegram.ui.Components.BackupImageView) LineProgressView(org.telegram.ui.Components.LineProgressView) NumberTextView(org.telegram.ui.Components.NumberTextView) ScrollView(android.widget.ScrollView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) TextPaint(android.text.TextPaint) RippleDrawable(android.graphics.drawable.RippleDrawable) ScrollView(android.widget.ScrollView) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) ShapeDrawable(android.graphics.drawable.ShapeDrawable) LineProgressView(org.telegram.ui.Components.LineProgressView) AnimatedArrowDrawable(org.telegram.ui.Components.AnimatedArrowDrawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable)

Aggregations

ContextProgressView (org.telegram.ui.Components.ContextProgressView)10 View (android.view.View)9 FrameLayout (android.widget.FrameLayout)9 ImageView (android.widget.ImageView)8 ActionBar (org.telegram.ui.ActionBar.ActionBar)8 SuppressLint (android.annotation.SuppressLint)7 TextView (android.widget.TextView)7 AvatarDrawable (org.telegram.ui.Components.AvatarDrawable)7 PorterDuffColorFilter (android.graphics.PorterDuffColorFilter)6 LinearLayout (android.widget.LinearLayout)6 ActionBarMenu (org.telegram.ui.ActionBar.ActionBarMenu)6 EditTextBoldCursor (org.telegram.ui.Components.EditTextBoldCursor)6 Canvas (android.graphics.Canvas)5 Paint (android.graphics.Paint)5 TextPaint (android.text.TextPaint)5 ScrollView (android.widget.ScrollView)5 ArrayList (java.util.ArrayList)5 TLRPC (org.telegram.tgnet.TLRPC)5 BackupImageView (org.telegram.ui.Components.BackupImageView)5 Animator (android.animation.Animator)4