Example usage for android.text SpannableStringBuilder length

List of usage examples for android.text SpannableStringBuilder length

Introduction

In this page you can find the example usage for android.text SpannableStringBuilder length.

Prototype

public int length() 

Source Link

Document

Return the number of chars in the buffer.

Usage

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void showChannelSelectionInternal(final String selection, final String title, final String help,
        final boolean delete) {
    String[] projection = {/*  w  w w .  j a  va 2s  . com*/
            TvBrowserContentProvider.CHANNEL_TABLE + "." + TvBrowserContentProvider.KEY_ID + " AS "
                    + TvBrowserContentProvider.KEY_ID,
            TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID, TvBrowserContentProvider.CHANNEL_KEY_NAME,
            TvBrowserContentProvider.CHANNEL_KEY_SELECTION, TvBrowserContentProvider.CHANNEL_KEY_CATEGORY,
            TvBrowserContentProvider.CHANNEL_KEY_LOGO, TvBrowserContentProvider.CHANNEL_KEY_ALL_COUNTRIES };

    ContentResolver cr = getContentResolver();
    Cursor channels = cr.query(TvBrowserContentProvider.CONTENT_URI_CHANNELS_WITH_GROUP, projection, selection,
            null, TvBrowserContentProvider.CHANNEL_KEY_NAME);
    channels.moveToPosition(-1);

    // populate array list with all available channels
    final ArrayListWrapper channelSelectionList = new ArrayListWrapper();
    ArrayList<Country> countryList = new ArrayList<Country>();

    int channelIdColumn = channels.getColumnIndex(TvBrowserContentProvider.KEY_ID);
    int categoryColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_CATEGORY);
    int logoColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_LOGO);
    int dataServiceColumn = channels.getColumnIndex(TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID);
    int nameColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_NAME);
    int countyColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_ALL_COUNTRIES);
    int selectionColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_SELECTION);
    ;
    while (channels.moveToNext()) {
        int channelID = channels.getInt(channelIdColumn);
        int category = channels.getInt(categoryColumn);
        byte[] logo = channels.getBlob(logoColumn);
        String dataService = channels.getString(dataServiceColumn);
        String name = channels.getString(nameColumn);
        String countries = channels.getString(countyColumn);
        boolean isSelected = channels.getInt(selectionColumn) == 1 && !delete;

        if (countries.contains("$")) {
            String[] values = countries.split("\\$");

            for (String country : values) {
                Country test = new Country(new Locale(country, country));

                if (!countryList.contains(test) && test.mLocale.getDisplayCountry().trim().length() > 0) {
                    countryList.add(test);
                }
            }
        } else {
            Country test = new Country(new Locale(countries, countries));

            if (!countryList.contains(test) && test.mLocale.getDisplayCountry().trim().length() > 0) {
                countryList.add(test);
            }
        }

        Bitmap channelLogo = UiUtils.createBitmapFromByteArray(logo);

        if (channelLogo != null) {
            BitmapDrawable l = new BitmapDrawable(getResources(), channelLogo);

            ColorDrawable background = new ColorDrawable(SettingConstants.LOGO_BACKGROUND_COLOR);
            background.setBounds(0, 0, channelLogo.getWidth() + 2, channelLogo.getHeight() + 2);

            LayerDrawable logoDrawable = new LayerDrawable(new Drawable[] { background, l });
            logoDrawable.setBounds(background.getBounds());

            l.setBounds(2, 2, channelLogo.getWidth(), channelLogo.getHeight());

            channelLogo = UiUtils.drawableToBitmap(logoDrawable);
        }

        channelSelectionList.add(new ChannelSelection(channelID, name, category, countries, channelLogo,
                isSelected, SettingConstants.EPG_DONATE_KEY.equals(dataService)));
    }

    // sort countries for filtering
    Collections.sort(countryList, new Comparator<Country>() {
        @Override
        public int compare(Country lhs, Country rhs) {
            return lhs.toString().compareToIgnoreCase(rhs.toString());
        }
    });

    countryList.add(0, new Country(null));

    channels.close();

    // create filter for filtering of category and country
    final ChannelFilter filter = new ChannelFilter(SettingConstants.TV_CATEGORY, null);

    // create default logo for channels without logo
    final Bitmap defaultLogo = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

    final Set<String> firstDeletedChannels = PrefUtils.getStringSetValue(R.string.PREF_FIRST_DELETED_CHANNELS,
            new HashSet<String>());
    final Set<String> keptDeletedChannels = PrefUtils.getStringSetValue(R.string.PREF_KEPT_DELETED_CHANNELS,
            new HashSet<String>());

    final int firstDeletedColor = getResources().getColor(R.color.pref_first_deleted_channels);
    final int keptDeletedColor = getResources().getColor(R.color.pref_kept_deleted_channels);

    // Custom array adapter for channel selection
    final ArrayAdapter<ChannelSelection> channelSelectionAdapter = new ArrayAdapter<ChannelSelection>(
            TvBrowser.this, R.layout.channel_row, channelSelectionList) {
        public View getView(int position, View convertView, ViewGroup parent) {
            ChannelSelection value = getItem(position);
            ViewHolder holder = null;

            if (convertView == null) {
                LayoutInflater mInflater = (LayoutInflater) getContext()
                        .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

                holder = new ViewHolder();

                convertView = mInflater.inflate(R.layout.channel_row, getParentViewGroup(), false);

                holder.mTextView = (TextView) convertView.findViewById(R.id.row_of_channel_text);
                holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.row_of_channel_selection);
                holder.mLogo = (ImageView) convertView.findViewById(R.id.row_of_channel_icon);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            SpannableStringBuilder nameBuilder = new SpannableStringBuilder(value.toString());

            String channelID = String.valueOf(value.getChannelID());

            if (keptDeletedChannels.contains(channelID)) {
                nameBuilder.setSpan(new ForegroundColorSpan(keptDeletedColor), 0, value.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (firstDeletedChannels.contains(channelID)) {
                nameBuilder.setSpan(new ForegroundColorSpan(firstDeletedColor), 0, value.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            if (value.isEpgDonateChannel()) {
                nameBuilder.append("\n(EPGdonate)");
                nameBuilder.setSpan(new RelativeSizeSpan(0.65f), value.toString().length(),
                        nameBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            holder.mTextView.setText(nameBuilder);
            holder.mCheckBox.setChecked(value.isSelected());

            Bitmap logo = value.getLogo();

            if (logo != null) {
                holder.mLogo.setImageBitmap(logo);
            } else {
                holder.mLogo.setImageBitmap(defaultLogo);
            }

            return convertView;
        }
    };

    // inflate channel selection view
    View channelSelectionView = getLayoutInflater().inflate(R.layout.dialog_channel_selection_list,
            getParentViewGroup(), false);
    channelSelectionView.findViewById(R.id.channel_selection_selection_buttons).setVisibility(View.GONE);
    channelSelectionView.findViewById(R.id.channel_selection_input_id_name).setVisibility(View.GONE);

    TextView infoView = (TextView) channelSelectionView.findViewById(R.id.channel_selection_label_id_name);

    if (help != null) {
        infoView.setText(help);
        infoView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                getResources().getDimension(R.dimen.epg_donate_info_font_size));
    } else {
        infoView.setVisibility(View.GONE);
    }

    // get spinner for country filtering and create array adapter with all available countries
    Spinner country = (Spinner) channelSelectionView.findViewById(R.id.channel_country_value);

    final ArrayAdapter<Country> countryListAdapter = new ArrayAdapter<Country>(this,
            android.R.layout.simple_spinner_item, countryList);
    countryListAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    country.setAdapter(countryListAdapter);

    // add item selection listener to react of user setting filter for country
    country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Country country = countryListAdapter.getItem(position);

            filter.mCountry = country.getCountry();
            channelSelectionList.setFilter(filter);
            channelSelectionAdapter.notifyDataSetChanged();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    // get spinner for category selection and add listener to react to user category selection
    Spinner category = (Spinner) channelSelectionView.findViewById(R.id.channel_category_value);
    category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
            case 1:
                filter.mCategory = SettingConstants.TV_CATEGORY;
                break;
            case 2:
                filter.mCategory = SettingConstants.RADIO_CATEGORY;
                break;
            case 3:
                filter.mCategory = SettingConstants.CINEMA_CATEGORY;
                break;

            default:
                filter.mCategory = SettingConstants.NO_CATEGORY;
                break;
            }

            channelSelectionList.setFilter(filter);
            channelSelectionAdapter.notifyDataSetChanged();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    if (delete) {
        channelSelectionView.findViewById(R.id.channel_country_label).setVisibility(View.GONE);
        channelSelectionView.findViewById(R.id.channel_category_label).setVisibility(View.GONE);

        country.setVisibility(View.GONE);
        category.setVisibility(View.GONE);
    }

    // get the list view of the layout and add adapter with available channels
    ListView list = (ListView) channelSelectionView.findViewById(R.id.channel_selection_list);
    list.setAdapter(channelSelectionAdapter);

    // add listener to react to user selection of channels
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            CheckBox check = (CheckBox) view.findViewById(R.id.row_of_channel_selection);

            if (check != null) {
                check.setChecked(!check.isChecked());
                channelSelectionAdapter.getItem(position).setSelected(check.isChecked());
            }
        }
    });

    // show dialog only if channels are available
    if (!channelSelectionList.isEmpty()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this);

        if (title == null) {
            builder.setTitle(R.string.select_channels);
        } else {
            builder.setTitle(title);
        }

        builder.setView(channelSelectionView);

        builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                boolean somethingSelected = false;
                boolean somethingChanged = false;

                Iterator<ChannelSelection> it = channelSelectionList.superIterator();

                StringBuilder deleteWhere = new StringBuilder();
                HashSet<String> keep = new HashSet<String>();

                while (it.hasNext()) {
                    ChannelSelection sel = it.next();

                    if (sel.isSelected() && !sel.wasSelected()) {
                        somethingChanged = somethingSelected = true;

                        if (delete) {
                            if (deleteWhere.length() > 0) {
                                deleteWhere.append(", ");
                            }

                            deleteWhere.append(sel.getChannelID());
                        } else {
                            ContentValues values = new ContentValues();

                            values.put(TvBrowserContentProvider.CHANNEL_KEY_SELECTION, 1);

                            getContentResolver().update(
                                    ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                            sel.getChannelID()),
                                    values, null, null);
                        }
                    } else if (!sel.isSelected() && sel.wasSelected()) {
                        somethingChanged = true;

                        ContentValues values = new ContentValues();

                        values.put(TvBrowserContentProvider.CHANNEL_KEY_SELECTION, 0);

                        getContentResolver().update(
                                ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                        sel.getChannelID()),
                                values, null, null);

                        getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_DATA_VERSION,
                                TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID + "=" + sel.getChannelID(),
                                null);
                        getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_DATA,
                                TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID + "=" + sel.getChannelID(),
                                null);
                    } else if (delete && !sel.isSelected()) {
                        keep.add(String.valueOf(sel.getChannelID()));
                    }
                }

                if (delete) {
                    if (deleteWhere.length() > 0) {
                        deleteWhere.insert(0, TvBrowserContentProvider.KEY_ID + " IN ( ");
                        deleteWhere.append(" ) ");

                        Log.d("info2", "DELETE WHERE FOR REMOVED CHANNELS " + deleteWhere.toString());

                        int count = getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                deleteWhere.toString(), null);

                        Log.d("info2", "REMOVED CHANNELS COUNT " + count);
                    }

                    Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit();
                    edit.putStringSet(getString(R.string.PREF_KEPT_DELETED_CHANNELS), keep);
                    edit.commit();
                }

                // if something was changed we need to update channel list bar in program list and the complete program table
                if (somethingChanged) {
                    SettingConstants.initializeLogoMap(TvBrowser.this, true);
                    updateProgramListChannelBar();
                }

                // if something was selected we need to download new data
                if (somethingSelected && !delete) {
                    checkTermsAccepted();
                }
            }
        });

        builder.setNegativeButton(android.R.string.cancel, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (delete) {
                    HashSet<String> keep = new HashSet<String>();
                    Iterator<ChannelSelection> it = channelSelectionList.superIterator();

                    while (it.hasNext()) {
                        ChannelSelection sel = it.next();

                        keep.add(String.valueOf(sel.getChannelID()));
                    }

                    Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit();
                    edit.putStringSet(getString(R.string.PREF_KEPT_DELETED_CHANNELS), keep);
                    edit.commit();
                }
            }
        });

        builder.show();
    }

    selectingChannels = false;
}

From source file:org.telegram.ui.ArticleViewer.java

private CharSequence getText(TLRPC.RichText parentRichText, TLRPC.RichText richText,
        TLRPC.PageBlock parentBlock) {//w w  w .  j a va2  s  .  c om
    if (richText instanceof TLRPC.TL_textFixed) {
        return getText(parentRichText, ((TLRPC.TL_textFixed) richText).text, parentBlock);
    } else if (richText instanceof TLRPC.TL_textItalic) {
        return getText(parentRichText, ((TLRPC.TL_textItalic) richText).text, parentBlock);
    } else if (richText instanceof TLRPC.TL_textBold) {
        return getText(parentRichText, ((TLRPC.TL_textBold) richText).text, parentBlock);
    } else if (richText instanceof TLRPC.TL_textUnderline) {
        return getText(parentRichText, ((TLRPC.TL_textUnderline) richText).text, parentBlock);
    } else if (richText instanceof TLRPC.TL_textStrike) {
        return getText(parentRichText, ((TLRPC.TL_textStrike) richText).text, parentBlock);
    } else if (richText instanceof TLRPC.TL_textEmail) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(
                getText(parentRichText, ((TLRPC.TL_textEmail) richText).text, parentBlock));
        MetricAffectingSpan innerSpans[] = spannableStringBuilder.getSpans(0, spannableStringBuilder.length(),
                MetricAffectingSpan.class);
        spannableStringBuilder.setSpan(
                new TextPaintUrlSpan(innerSpans == null || innerSpans.length == 0
                        ? getTextPaint(parentRichText, richText, parentBlock)
                        : null, getUrl(richText)),
                0, spannableStringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableStringBuilder;
    } else if (richText instanceof TLRPC.TL_textUrl) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(
                getText(parentRichText, ((TLRPC.TL_textUrl) richText).text, parentBlock));
        MetricAffectingSpan innerSpans[] = spannableStringBuilder.getSpans(0, spannableStringBuilder.length(),
                MetricAffectingSpan.class);
        spannableStringBuilder.setSpan(
                new TextPaintUrlSpan(innerSpans == null || innerSpans.length == 0
                        ? getTextPaint(parentRichText, richText, parentBlock)
                        : null, getUrl(richText)),
                0, spannableStringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableStringBuilder;
    } else if (richText instanceof TLRPC.TL_textPlain) {
        return ((TLRPC.TL_textPlain) richText).text;
    } else if (richText instanceof TLRPC.TL_textEmpty) {
        return "";
    } else if (richText instanceof TLRPC.TL_textConcat) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        int count = richText.texts.size();
        for (int a = 0; a < count; a++) {
            TLRPC.RichText innerRichText = richText.texts.get(a);
            CharSequence innerText = getText(parentRichText, innerRichText, parentBlock);
            int flags = getTextFlags(innerRichText);
            int startLength = spannableStringBuilder.length();
            spannableStringBuilder.append(innerText);
            if (flags != 0 && !(innerText instanceof SpannableStringBuilder)) {
                if ((flags & TEXT_FLAG_URL) != 0) {
                    String url = getUrl(innerRichText);
                    if (url == null) {
                        url = getUrl(parentRichText);
                    }
                    spannableStringBuilder.setSpan(
                            new TextPaintUrlSpan(getTextPaint(parentRichText, innerRichText, parentBlock), url),
                            startLength, spannableStringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                } else {
                    spannableStringBuilder.setSpan(
                            new TextPaintSpan(getTextPaint(parentRichText, innerRichText, parentBlock)),
                            startLength, spannableStringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        }
        return spannableStringBuilder;
    }
    return "not supported " + richText;
}

From source file:org.telegram.ui.Cells.DialogCell.java

public void buildLayout() {
    String nameString = "";
    String timeString = "";
    String countString = null;//from w  w w.j  a va2  s.c  o  m
    CharSequence messageString = "";
    CharSequence printingString = null;
    if (isDialogCell) {
        printingString = MessagesController.getInstance().printingStrings.get(currentDialogId);
    }
    TextPaint currentNamePaint = namePaint;
    TextPaint currentMessagePaint = messagePaint;
    boolean checkMessage = true;

    drawNameGroup = false;
    drawNameBroadcast = false;
    drawNameLock = false;
    drawNameBot = false;
    drawVerified = false;

    if (encryptedChat != null) {
        drawNameLock = true;
        nameLockTop = AndroidUtilities.dp(16.5f);
        if (!LocaleController.isRTL) {
            nameLockLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline);
            nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline + 4)
                    + lockDrawable.getIntrinsicWidth();
        } else {
            nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline)
                    - lockDrawable.getIntrinsicWidth();
            nameLeft = AndroidUtilities.dp(14);
        }
    } else {
        if (chat != null) {
            if (chat.id < 0 || ChatObject.isChannel(chat) && !chat.megagroup) {
                drawNameBroadcast = true;
                nameLockTop = AndroidUtilities.dp(16.5f);
            } else {
                drawNameGroup = true;
                nameLockTop = AndroidUtilities.dp(17.5f);
            }
            drawVerified = chat.verified;

            if (!LocaleController.isRTL) {
                nameLockLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline);
                nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline + 4)
                        + (drawNameGroup ? groupDrawable.getIntrinsicWidth()
                                : broadcastDrawable.getIntrinsicWidth());
            } else {
                nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline)
                        - (drawNameGroup ? groupDrawable.getIntrinsicWidth()
                                : broadcastDrawable.getIntrinsicWidth());
                nameLeft = AndroidUtilities.dp(14);
            }
        } else {
            if (!LocaleController.isRTL) {
                nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline);
            } else {
                nameLeft = AndroidUtilities.dp(14);
            }
            if (user != null) {
                if (user.bot) {
                    drawNameBot = true;
                    nameLockTop = AndroidUtilities.dp(16.5f);
                    if (!LocaleController.isRTL) {
                        nameLockLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline);
                        nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline + 4)
                                + botDrawable.getIntrinsicWidth();
                    } else {
                        nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline)
                                - botDrawable.getIntrinsicWidth();
                        nameLeft = AndroidUtilities.dp(14);
                    }
                }
                drawVerified = user.verified;
            }
        }
    }

    int lastDate = lastMessageDate;
    if (lastMessageDate == 0 && message != null) {
        lastDate = message.messageOwner.date;
    }

    if (isDialogCell) {
        draftMessage = DraftQuery.getDraft(currentDialogId);
        if (draftMessage != null
                && (TextUtils.isEmpty(draftMessage.message) && draftMessage.reply_to_msg_id == 0
                        || lastDate > draftMessage.date && unreadCount != 0)
                || ChatObject.isChannel(chat) && !chat.megagroup && !chat.creator && !chat.editor
                || chat != null && (chat.left || chat.kicked)) {
            draftMessage = null;
        }
    } else {
        draftMessage = null;
    }

    if (printingString != null) {
        lastPrintString = messageString = printingString;
        currentMessagePaint = messagePrintingPaint;
    } else {
        lastPrintString = null;

        if (draftMessage != null) {
            checkMessage = false;
            if (TextUtils.isEmpty(draftMessage.message)) {
                String draftString = LocaleController.getString("Draft", R.string.Draft);
                SpannableStringBuilder stringBuilder = SpannableStringBuilder.valueOf(draftString);
                stringBuilder.setSpan(new ForegroundColorSpan(Theme.DIALOGS_DRAFT_TEXT_COLOR), 0,
                        draftString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                messageString = stringBuilder;
            } else {
                String mess = draftMessage.message;
                if (mess.length() > 150) {
                    mess = mess.substring(0, 150);
                }
                String draftString = LocaleController.getString("Draft", R.string.Draft);
                SpannableStringBuilder stringBuilder = SpannableStringBuilder
                        .valueOf(String.format("%s: %s", draftString, mess.replace('\n', ' ')));
                stringBuilder.setSpan(new ForegroundColorSpan(Theme.DIALOGS_DRAFT_TEXT_COLOR), 0,
                        draftString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                messageString = Emoji.replaceEmoji(stringBuilder, messagePaint.getFontMetricsInt(),
                        AndroidUtilities.dp(20), false);
            }
        } else {
            if (message == null) {
                if (encryptedChat != null) {
                    currentMessagePaint = messagePrintingPaint;
                    if (encryptedChat instanceof TLRPC.TL_encryptedChatRequested) {
                        messageString = LocaleController.getString("EncryptionProcessing",
                                R.string.EncryptionProcessing);
                    } else if (encryptedChat instanceof TLRPC.TL_encryptedChatWaiting) {
                        if (user != null && user.first_name != null) {
                            messageString = LocaleController.formatString("AwaitingEncryption",
                                    R.string.AwaitingEncryption, user.first_name);
                        } else {
                            messageString = LocaleController.formatString("AwaitingEncryption",
                                    R.string.AwaitingEncryption, "");
                        }
                    } else if (encryptedChat instanceof TLRPC.TL_encryptedChatDiscarded) {
                        messageString = LocaleController.getString("EncryptionRejected",
                                R.string.EncryptionRejected);
                    } else if (encryptedChat instanceof TLRPC.TL_encryptedChat) {
                        if (encryptedChat.admin_id == UserConfig.getClientUserId()) {
                            if (user != null && user.first_name != null) {
                                messageString = LocaleController.formatString("EncryptedChatStartedOutgoing",
                                        R.string.EncryptedChatStartedOutgoing, user.first_name);
                            } else {
                                messageString = LocaleController.formatString("EncryptedChatStartedOutgoing",
                                        R.string.EncryptedChatStartedOutgoing, "");
                            }
                        } else {
                            messageString = LocaleController.getString("EncryptedChatStartedIncoming",
                                    R.string.EncryptedChatStartedIncoming);
                        }
                    }
                }
            } else {
                TLRPC.User fromUser = null;
                TLRPC.Chat fromChat = null;
                if (message.isFromUser()) {
                    fromUser = MessagesController.getInstance().getUser(message.messageOwner.from_id);
                } else {
                    fromChat = MessagesController.getInstance().getChat(message.messageOwner.to_id.channel_id);
                }
                if (message.messageOwner instanceof TLRPC.TL_messageService) {
                    messageString = message.messageText;
                    currentMessagePaint = messagePrintingPaint;
                } else {
                    if (chat != null && chat.id > 0 && fromChat == null) {
                        String name;
                        if (message.isOutOwner()) {
                            name = LocaleController.getString("FromYou", R.string.FromYou);
                        } else if (fromUser != null) {
                            name = UserObject.getFirstName(fromUser).replace("\n", "");
                        } else if (fromChat != null) {
                            name = fromChat.title.replace("\n", "");
                        } else {
                            name = "DELETED";
                        }
                        checkMessage = false;
                        SpannableStringBuilder stringBuilder;
                        if (message.caption != null) {
                            String mess = message.caption.toString();
                            if (mess.length() > 150) {
                                mess = mess.substring(0, 150);
                            }
                            stringBuilder = SpannableStringBuilder
                                    .valueOf(String.format("%s: %s", name, mess.replace('\n', ' ')));
                        } else if (message.messageOwner.media != null && !message.isMediaEmpty()) {
                            currentMessagePaint = messagePrintingPaint;
                            if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
                                stringBuilder = SpannableStringBuilder.valueOf(String.format("%s: %s", name,
                                        "\uD83C\uDFAE " + message.messageOwner.media.game.title));
                            } else {
                                stringBuilder = SpannableStringBuilder
                                        .valueOf(String.format("%s: %s", name, message.messageText));
                            }
                            stringBuilder.setSpan(new ForegroundColorSpan(Theme.DIALOGS_ATTACH_TEXT_COLOR),
                                    name.length() + 2, stringBuilder.length(),
                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        } else if (message.messageOwner.message != null) {
                            String mess = message.messageOwner.message;
                            if (mess.length() > 150) {
                                mess = mess.substring(0, 150);
                            }
                            stringBuilder = SpannableStringBuilder
                                    .valueOf(String.format("%s: %s", name, mess.replace('\n', ' ')));
                        } else {
                            stringBuilder = SpannableStringBuilder.valueOf("");
                        }
                        if (stringBuilder.length() > 0) {
                            stringBuilder.setSpan(new ForegroundColorSpan(Theme.DIALOGS_NAME_TEXT_COLOR), 0,
                                    name.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                        messageString = Emoji.replaceEmoji(stringBuilder, messagePaint.getFontMetricsInt(),
                                AndroidUtilities.dp(20), false);
                    } else {
                        if (message.caption != null) {
                            messageString = message.caption;
                        } else {
                            if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
                                messageString = "\uD83C\uDFAE " + message.messageOwner.media.game.title;
                            } else {
                                messageString = message.messageText;
                            }
                            if (message.messageOwner.media != null && !message.isMediaEmpty()) {
                                currentMessagePaint = messagePrintingPaint;
                            }
                        }
                    }
                }
            }
        }
    }

    if (draftMessage != null) {
        timeString = LocaleController.stringForMessageListDate(draftMessage.date);
    } else if (lastMessageDate != 0) {
        timeString = LocaleController.stringForMessageListDate(lastMessageDate);
    } else if (message != null) {
        timeString = LocaleController.stringForMessageListDate(message.messageOwner.date);
    }

    if (message == null) {
        drawCheck1 = false;
        drawCheck2 = false;
        drawClock = false;
        drawCount = false;
        drawError = false;
    } else {
        if (unreadCount != 0) {
            drawCount = true;
            countString = String.format("%d", unreadCount);
        } else {
            drawCount = false;
        }

        if (message.isOut() && draftMessage == null) {
            if (message.isSending()) {
                drawCheck1 = false;
                drawCheck2 = false;
                drawClock = true;
                drawError = false;
            } else if (message.isSendError()) {
                drawCheck1 = false;
                drawCheck2 = false;
                drawClock = false;
                drawError = true;
                drawCount = false;
            } else if (message.isSent()) {
                drawCheck1 = !message.isUnread() || ChatObject.isChannel(chat) && !chat.megagroup;
                drawCheck2 = true;
                drawClock = false;
                drawError = false;
            }
        } else {
            drawCheck1 = false;
            drawCheck2 = false;
            drawClock = false;
            drawError = false;
        }
    }

    int timeWidth = (int) Math.ceil(timePaint.measureText(timeString));
    timeLayout = new StaticLayout(timeString, timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f,
            false);
    if (!LocaleController.isRTL) {
        timeLeft = getMeasuredWidth() - AndroidUtilities.dp(15) - timeWidth;
    } else {
        timeLeft = AndroidUtilities.dp(15);
    }

    if (chat != null) {
        nameString = chat.title;
    } else if (user != null) {
        if (user.id == UserConfig.getClientUserId()) {
            nameString = LocaleController.getString("ChatYourSelfName", R.string.ChatYourSelfName);
        } else if (user.id / 1000 != 777 && user.id / 1000 != 333
                && ContactsController.getInstance().contactsDict.get(user.id) == null) {
            if (ContactsController.getInstance().contactsDict.size() == 0
                    && (!ContactsController.getInstance().contactsLoaded
                            || ContactsController.getInstance().isLoadingContacts())) {
                nameString = UserObject.getUserName(user);
            } else {
                if (user.phone != null && user.phone.length() != 0) {
                    nameString = PhoneFormat.getInstance().format("+" + user.phone);
                } else {
                    nameString = UserObject.getUserName(user);
                }
            }
        } else {
            nameString = UserObject.getUserName(user);
        }
        if (encryptedChat != null) {
            currentNamePaint = nameEncryptedPaint;
        }
    }
    if (nameString.length() == 0) {
        nameString = LocaleController.getString("HiddenName", R.string.HiddenName);
    }

    int nameWidth;

    if (!LocaleController.isRTL) {
        nameWidth = getMeasuredWidth() - nameLeft - AndroidUtilities.dp(14) - timeWidth;
    } else {
        nameWidth = getMeasuredWidth() - nameLeft - AndroidUtilities.dp(AndroidUtilities.leftBaseline)
                - timeWidth;
        nameLeft += timeWidth;
    }
    if (drawNameLock) {
        nameWidth -= AndroidUtilities.dp(4) + lockDrawable.getIntrinsicWidth();
    } else if (drawNameGroup) {
        nameWidth -= AndroidUtilities.dp(4) + groupDrawable.getIntrinsicWidth();
    } else if (drawNameBroadcast) {
        nameWidth -= AndroidUtilities.dp(4) + broadcastDrawable.getIntrinsicWidth();
    } else if (drawNameBot) {
        nameWidth -= AndroidUtilities.dp(4) + botDrawable.getIntrinsicWidth();
    }
    if (drawClock) {
        int w = clockDrawable.getIntrinsicWidth() + AndroidUtilities.dp(5);
        nameWidth -= w;
        if (!LocaleController.isRTL) {
            checkDrawLeft = timeLeft - w;
        } else {
            checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(5);
            nameLeft += w;
        }
    } else if (drawCheck2) {
        int w = checkDrawable.getIntrinsicWidth() + AndroidUtilities.dp(5);
        nameWidth -= w;
        if (drawCheck1) {
            nameWidth -= halfCheckDrawable.getIntrinsicWidth() - AndroidUtilities.dp(8);
            if (!LocaleController.isRTL) {
                halfCheckDrawLeft = timeLeft - w;
                checkDrawLeft = halfCheckDrawLeft - AndroidUtilities.dp(5.5f);
            } else {
                checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(5);
                halfCheckDrawLeft = checkDrawLeft + AndroidUtilities.dp(5.5f);
                nameLeft += w + halfCheckDrawable.getIntrinsicWidth() - AndroidUtilities.dp(8);
            }
        } else {
            if (!LocaleController.isRTL) {
                checkDrawLeft = timeLeft - w;
            } else {
                checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(5);
                nameLeft += w;
            }
        }
    }

    if (dialogMuted && !drawVerified) {
        int w = AndroidUtilities.dp(6) + muteDrawable.getIntrinsicWidth();
        nameWidth -= w;
        if (LocaleController.isRTL) {
            nameLeft += w;
        }
    } else if (drawVerified) {
        int w = AndroidUtilities.dp(6) + verifiedDrawable.getIntrinsicWidth();
        nameWidth -= w;
        if (LocaleController.isRTL) {
            nameLeft += w;
        }
    }

    nameWidth = Math.max(AndroidUtilities.dp(12), nameWidth);
    try {
        CharSequence nameStringFinal = TextUtils.ellipsize(nameString.replace('\n', ' '), currentNamePaint,
                nameWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END);
        nameLayout = new StaticLayout(nameStringFinal, currentNamePaint, nameWidth,
                Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }

    int messageWidth = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline + 16);
    int avatarLeft;
    if (!LocaleController.isRTL) {
        messageLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline);
        avatarLeft = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 13 : 9);
    } else {
        messageLeft = AndroidUtilities.dp(16);
        avatarLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.isTablet() ? 65 : 61);
    }
    avatarImage.setImageCoords(avatarLeft, avatarTop, AndroidUtilities.dp(52), AndroidUtilities.dp(52));
    if (drawError) {
        int w = errorDrawable.getIntrinsicWidth() + AndroidUtilities.dp(8);
        messageWidth -= w;
        if (!LocaleController.isRTL) {
            errorLeft = getMeasuredWidth() - errorDrawable.getIntrinsicWidth() - AndroidUtilities.dp(11);
        } else {
            errorLeft = AndroidUtilities.dp(11);
            messageLeft += w;
        }
    } else if (countString != null) {
        countWidth = Math.max(AndroidUtilities.dp(12), (int) Math.ceil(countPaint.measureText(countString)));
        countLayout = new StaticLayout(countString, countPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f,
                0.0f, false);
        int w = countWidth + AndroidUtilities.dp(18);
        messageWidth -= w;
        if (!LocaleController.isRTL) {
            countLeft = getMeasuredWidth() - countWidth - AndroidUtilities.dp(19);
        } else {
            countLeft = AndroidUtilities.dp(19);
            messageLeft += w;
        }
        drawCount = true;
    } else {
        drawCount = false;
    }

    if (checkMessage) {
        if (messageString == null) {
            messageString = "";
        }
        String mess = messageString.toString();
        if (mess.length() > 150) {
            mess = mess.substring(0, 150);
        }
        mess = mess.replace('\n', ' ');
        messageString = Emoji.replaceEmoji(mess, messagePaint.getFontMetricsInt(), AndroidUtilities.dp(17),
                false);
    }
    messageWidth = Math.max(AndroidUtilities.dp(12), messageWidth);
    CharSequence messageStringFinal = TextUtils.ellipsize(messageString, currentMessagePaint,
            messageWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END);
    try {
        messageLayout = new StaticLayout(messageStringFinal, currentMessagePaint, messageWidth,
                Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }

    double widthpx;
    float left;
    if (LocaleController.isRTL) {
        if (nameLayout != null && nameLayout.getLineCount() > 0) {
            left = nameLayout.getLineLeft(0);
            widthpx = Math.ceil(nameLayout.getLineWidth(0));
            if (dialogMuted && !drawVerified) {
                nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - AndroidUtilities.dp(6)
                        - muteDrawable.getIntrinsicWidth());
            } else if (drawVerified) {
                nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - AndroidUtilities.dp(6)
                        - verifiedDrawable.getIntrinsicWidth());
            }
            if (left == 0) {
                if (widthpx < nameWidth) {
                    nameLeft += (nameWidth - widthpx);
                }
            }
        }
        if (messageLayout != null && messageLayout.getLineCount() > 0) {
            left = messageLayout.getLineLeft(0);
            if (left == 0) {
                widthpx = Math.ceil(messageLayout.getLineWidth(0));
                if (widthpx < messageWidth) {
                    messageLeft += (messageWidth - widthpx);
                }
            }
        }
    } else {
        if (nameLayout != null && nameLayout.getLineCount() > 0) {
            left = nameLayout.getLineRight(0);
            if (left == nameWidth) {
                widthpx = Math.ceil(nameLayout.getLineWidth(0));
                if (widthpx < nameWidth) {
                    nameLeft -= (nameWidth - widthpx);
                }
            }
            if (dialogMuted || drawVerified) {
                nameMuteLeft = (int) (nameLeft + left + AndroidUtilities.dp(6));
            }
        }
        if (messageLayout != null && messageLayout.getLineCount() > 0) {
            left = messageLayout.getLineRight(0);
            if (left == messageWidth) {
                widthpx = Math.ceil(messageLayout.getLineWidth(0));
                if (widthpx < messageWidth) {
                    messageLeft -= (messageWidth - widthpx);
                }
            }
        }
    }
}

From source file:org.telegram.ui.PassportActivity.java

private void checkTopErrorCell(boolean init) {
    if (topErrorCell == null) {
        return;//www .j a  v  a 2 s  .  c  o m
    }
    SpannableStringBuilder stringBuilder = null;
    if (fieldsErrors != null && (init || errorsValues.containsKey("error_all"))) {
        String errorText = fieldsErrors.get("error_all");
        if (errorText != null) {
            stringBuilder = new SpannableStringBuilder(errorText);
            if (init) {
                errorsValues.put("error_all", "");
            }
        }
    }
    if (documentsErrors != null && (init || errorsValues.containsKey("error_document_all"))) {
        String errorText = documentsErrors.get("error_all");
        if (errorText != null) {
            if (stringBuilder == null) {
                stringBuilder = new SpannableStringBuilder(errorText);
            } else {
                stringBuilder.append("\n\n").append(errorText);
            }
            if (init) {
                errorsValues.put("error_document_all", "");
            }
        }
    }
    if (stringBuilder != null) {
        stringBuilder.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteRedText3)),
                0, stringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        topErrorCell.setText(stringBuilder);
        topErrorCell.setVisibility(View.VISIBLE);
    } else if (topErrorCell.getVisibility() != View.GONE) {
        topErrorCell.setVisibility(View.GONE);
    }
}

From source file:kr.wdream.ui.ChatActivity.java

private void applyDraftMaybe(boolean canClear) {
    if (chatActivityEnterView == null) {
        return;//from   w  ww .j a v a2s  .co  m
    }
    TLRPC.DraftMessage draftMessage = DraftQuery.getDraft(dialog_id);
    TLRPC.Message draftReplyMessage = draftMessage != null && draftMessage.reply_to_msg_id != 0
            ? DraftQuery.getDraftMessage(dialog_id)
            : null;
    if (chatActivityEnterView.getFieldText() == null) {
        if (draftMessage != null) {
            chatActivityEnterView.setWebPage(null, !draftMessage.no_webpage);
            CharSequence message;
            if (!draftMessage.entities.isEmpty()) {
                SpannableStringBuilder stringBuilder = SpannableStringBuilder.valueOf(draftMessage.message);
                MessagesQuery.sortEntities(draftMessage.entities);
                int addToOffset = 0;
                for (int a = 0; a < draftMessage.entities.size(); a++) {
                    TLRPC.MessageEntity entity = draftMessage.entities.get(a);
                    if (entity instanceof TLRPC.TL_inputMessageEntityMentionName
                            || entity instanceof TLRPC.TL_messageEntityMentionName) {
                        int user_id;
                        if (entity instanceof TLRPC.TL_inputMessageEntityMentionName) {
                            user_id = ((TLRPC.TL_inputMessageEntityMentionName) entity).user_id.user_id;
                        } else {
                            user_id = ((TLRPC.TL_messageEntityMentionName) entity).user_id;
                        }
                        if (entity.offset + addToOffset + entity.length < stringBuilder.length()
                                && stringBuilder.charAt(entity.offset + addToOffset + entity.length) == ' ') {
                            entity.length++;
                        }
                        stringBuilder.setSpan(new URLSpanUserMention("" + user_id), entity.offset + addToOffset,
                                entity.offset + addToOffset + entity.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    } else if (entity instanceof TLRPC.TL_messageEntityCode) {
                        stringBuilder.insert(entity.offset + entity.length + addToOffset, "`");
                        stringBuilder.insert(entity.offset + addToOffset, "`");
                        addToOffset += 2;
                    } else if (entity instanceof TLRPC.TL_messageEntityPre) {
                        stringBuilder.insert(entity.offset + entity.length + addToOffset, "```");
                        stringBuilder.insert(entity.offset + addToOffset, "```");
                        addToOffset += 6;
                    }
                }
                message = stringBuilder;
            } else {
                message = draftMessage.message;
            }
            chatActivityEnterView.setFieldText(message);
            if (getArguments().getBoolean("hasUrl", false)) {
                chatActivityEnterView.setSelection(draftMessage.message.indexOf('\n') + 1);
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (chatActivityEnterView != null) {
                            chatActivityEnterView.setFieldFocused(true);
                            chatActivityEnterView.openKeyboard();
                        }
                    }
                }, 700);
            }
        }
    } else if (canClear && draftMessage == null) {
        chatActivityEnterView.setFieldText("");
        showReplyPanel(false, null, null, null, false, true);
    }
    if (replyingMessageObject == null && draftReplyMessage != null) {
        replyingMessageObject = new MessageObject(draftReplyMessage,
                MessagesController.getInstance().getUsers(), false);
        showReplyPanel(true, replyingMessageObject, null, null, false, false);
    }
}