diff --git a/mastodon/src/main/java/com/hootsuite/nachos/ChipConfiguration.java b/mastodon/src/main/java/com/hootsuite/nachos/ChipConfiguration.java new file mode 100644 index 000000000..0b8fb3b7a --- /dev/null +++ b/mastodon/src/main/java/com/hootsuite/nachos/ChipConfiguration.java @@ -0,0 +1,78 @@ +package com.hootsuite.nachos; + +import android.content.res.ColorStateList; + +public class ChipConfiguration { + + private final int mChipHorizontalSpacing; + private final ColorStateList mChipBackground; + private final int mChipCornerRadius; + private final int mChipTextColor; + private final int mChipTextSize; + private final int mChipHeight; + private final int mChipVerticalSpacing; + private final int mMaxAvailableWidth; + + /** + * Creates a new ChipConfiguration. You can pass in {@code -1} or {@code null} for any of the parameters to indicate that parameter should be + * ignored. + * + * @param chipHorizontalSpacing the amount of horizontal space (in pixels) to put between consecutive chips + * @param chipBackground the {@link ColorStateList} to set as the background of the chips + * @param chipCornerRadius the corner radius of the chip background, in pixels + * @param chipTextColor the color to set as the text color of the chips + * @param chipTextSize the font size (in pixels) to use for the text of the chips + * @param chipHeight the height (in pixels) of each chip + * @param chipVerticalSpacing the amount of vertical space (in pixels) to put between chips on consecutive lines + * @param maxAvailableWidth the maximum available with for a chip (the width of a full line of text in the text view) + */ + ChipConfiguration(int chipHorizontalSpacing, + ColorStateList chipBackground, + int chipCornerRadius, + int chipTextColor, + int chipTextSize, + int chipHeight, + int chipVerticalSpacing, + int maxAvailableWidth) { + mChipHorizontalSpacing = chipHorizontalSpacing; + mChipBackground = chipBackground; + mChipCornerRadius = chipCornerRadius; + mChipTextColor = chipTextColor; + mChipTextSize = chipTextSize; + mChipHeight = chipHeight; + mChipVerticalSpacing = chipVerticalSpacing; + mMaxAvailableWidth = maxAvailableWidth; + } + + public int getChipHorizontalSpacing() { + return mChipHorizontalSpacing; + } + + public ColorStateList getChipBackground() { + return mChipBackground; + } + + public int getChipCornerRadius() { + return mChipCornerRadius; + } + + public int getChipTextColor() { + return mChipTextColor; + } + + public int getChipTextSize() { + return mChipTextSize; + } + + public int getChipHeight() { + return mChipHeight; + } + + public int getChipVerticalSpacing() { + return mChipVerticalSpacing; + } + + public int getMaxAvailableWidth() { + return mMaxAvailableWidth; + } +} diff --git a/mastodon/src/main/java/com/hootsuite/nachos/NachoTextView.java b/mastodon/src/main/java/com/hootsuite/nachos/NachoTextView.java new file mode 100644 index 000000000..b4b9de7ed --- /dev/null +++ b/mastodon/src/main/java/com/hootsuite/nachos/NachoTextView.java @@ -0,0 +1,1132 @@ +package com.hootsuite.nachos; + +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; +import android.content.res.ColorStateList; +import android.content.res.TypedArray; +import android.graphics.Color; +import android.graphics.Paint; +import android.text.Editable; +import android.text.Layout; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.util.AttributeSet; +import android.util.Log; +import android.util.Pair; +import android.view.GestureDetector; +import android.view.MotionEvent; +import android.view.View; +import android.view.inputmethod.EditorInfo; +import android.widget.Adapter; +import android.widget.AdapterView; +import android.widget.AutoCompleteTextView; +import android.widget.ListAdapter; +import android.widget.MultiAutoCompleteTextView; + +import com.hootsuite.nachos.chip.Chip; +import com.hootsuite.nachos.chip.ChipInfo; +import com.hootsuite.nachos.chip.ChipSpan; +import com.hootsuite.nachos.chip.ChipSpanChipCreator; +import com.hootsuite.nachos.terminator.ChipTerminatorHandler; +import com.hootsuite.nachos.terminator.DefaultChipTerminatorHandler; +import com.hootsuite.nachos.tokenizer.ChipTokenizer; +import com.hootsuite.nachos.tokenizer.SpanChipTokenizer; +import com.hootsuite.nachos.validator.ChipifyingNachoValidator; +import com.hootsuite.nachos.validator.IllegalCharacterIdentifier; +import com.hootsuite.nachos.validator.NachoValidator; + +import org.joinmastodon.android.R; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import androidx.annotation.ColorInt; +import androidx.annotation.ColorRes; +import androidx.annotation.DimenRes; +import androidx.annotation.Dimension; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +/** + * An editable TextView extending {@link MultiAutoCompleteTextView} that supports "chipifying" pieces of text and displaying suggestions for segments of the text. + *
+ * nachoTextView.setNachoValidator(new ChipifyingNachoValidator()); + *+ * Note: The NachoValidator will be ignored if a ChipTokenizer is not set. To perform validation without a ChipTokenizer you can use + * {@link AutoCompleteTextView}'s built-in {@link Validator Validator} through {@link #setValidator(Validator)} + *
+ * String[] suggestions = new String[]{"suggestion 1", "suggestion 2"};
+ * ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, suggestions);
+ * nachoTextView.setAdapter(adapter);
+ * nachoTextView.addChipTerminator('\n', ChipTerminatorHandler.BEHAVIOR_CHIPIFY_ALL);
+ * nachoTextView.addChipTerminator(' ', ChipTerminatorHandler.BEHAVIOR_CHIPIFY_TO_TERMINATOR);
+ * nachoTextView.setIllegalCharacters('@');
+ * nachoTextView.setNachoValidator(new ChipifyingNachoValidator());
+ * nachoTextView.enableEditChipOnTouch(true, true);
+ * nachoTextView.setOnChipClickListener(new NachoTextView.OnChipClickListener() {
+ * {@literal @Override}
+ * public void onChipClick(Chip chip, MotionEvent motionEvent) {
+ * // Handle click event
+ * }
+ * });
+ * nachoTextView.setOnChipRemoveListener(new NachoTextView.OnChipRemoveListener() {
+ * {@literal @Override}
+ * public void onChipRemove(Chip chip) {
+ * // Handle remove event
+ * }
+ * });
+ *
+ *
+ * @see SpanChipTokenizer
+ * @see DefaultChipTerminatorHandler
+ * @see ChipifyingNachoValidator
+ */
+public class NachoTextView extends MultiAutoCompleteTextView implements TextWatcher, AdapterView.OnItemClickListener {
+
+ // UI Attributes
+ private int mChipHorizontalSpacing = -1;
+ private ColorStateList mChipBackground = null;
+ private int mChipCornerRadius = -1;
+ private int mChipTextColor = Color.TRANSPARENT;
+ private int mChipTextSize = -1;
+ private int mChipHeight = -1;
+ private int mChipVerticalSpacing = -1;
+
+ private int mDefaultPaddingTop = 0;
+ private int mDefaultPaddingBottom = 0;
+ /**
+ * Flag to keep track of the padding state so we only update the padding when necessary
+ */
+ private boolean mUsingDefaultPadding = true;
+
+ // Touch events
+ @Nullable
+ private OnChipClickListener mOnChipClickListener;
+ private GestureDetector singleTapDetector;
+ private boolean mEditChipOnTouchEnabled;
+ private boolean mMoveChipToEndOnEdit;
+ private boolean mChipifyUnterminatedTokensOnEdit;
+
+ // Text entry
+ @Nullable
+ private ChipTokenizer mChipTokenizer;
+ @Nullable
+ private ChipTerminatorHandler mChipTerminatorHandler;
+ @Nullable
+ private NachoValidator mNachoValidator;
+ @Nullable
+ private IllegalCharacterIdentifier illegalCharacterIdentifier;
+
+ @Nullable
+ private OnChipRemoveListener mOnChipRemoveListener;
+ private List+ * Note: If an {@link OnChipClickListener} is set it's behavior will override the behavior described here if it's + * {@link OnChipClickListener#onChipClick(Chip, MotionEvent)} method returns true. If that method returns false, the touched chip will be put + * in editing mode as expected. + *
+ * + * @param moveChipToEnd if true, the chip will also be moved to the end of the text when it is put in editing mode + * @param chipifyUnterminatedTokens if true, all unterminated tokens will be chipified before the touched chip is put in editing mode + * @see #disableEditChipOnTouch() + */ + public void enableEditChipOnTouch(boolean moveChipToEnd, boolean chipifyUnterminatedTokens) { + mEditChipOnTouchEnabled = true; + mMoveChipToEndOnEdit = moveChipToEnd; + mChipifyUnterminatedTokensOnEdit = chipifyUnterminatedTokens; + } + + /** + * Disables editing chips on touch events. To re-enable this behavior call {@link #enableEditChipOnTouch(boolean, boolean)}. + * + * @see #enableEditChipOnTouch(boolean, boolean) + */ + public void disableEditChipOnTouch() { + mEditChipOnTouchEnabled = false; + } + + /** + * Puts the provided Chip in editing mode (i.e. reverts it to an unchipified token whose text can be edited). + * + * @param chip the chip to edit + * @param moveChipToEnd if true, the chip will also be moved to the end of the text + */ + public void setEditingChip(Chip chip, boolean moveChipToEnd) { + if (mChipTokenizer == null) { + return; + } + + beginUnwatchedTextChange(); + + Editable text = getText(); + if (moveChipToEnd) { + // Move the chip text to the end of the text + text.append(chip.getText()); + // Delete the existing chip + mChipTokenizer.deleteChipAndPadding(chip, text); + // Move the cursor to the end of the text + setSelection(text.length()); + } else { + int chipStart = mChipTokenizer.findChipStart(chip, text); + mChipTokenizer.revertChipToToken(chip, text); + setSelection(mChipTokenizer.findTokenEnd(text, chipStart)); + } + + endUnwatchedTextChange(); + } + + @Override + public boolean onTouchEvent(@NonNull MotionEvent event) { + boolean wasHandled = false; + clearChipStates(); + Chip touchedChip = findTouchedChip(event); + if (touchedChip != null && isFocused() && singleTapDetector.onTouchEvent(event)) { + touchedChip.setState(View.PRESSED_SELECTED_STATE_SET); + if (onChipClicked(touchedChip)) { + wasHandled = true; + } + if (mOnChipClickListener != null) { + mOnChipClickListener.onChipClick(touchedChip, event); + } + } + + // Getting NullPointerException inside Editor.updateFloatingToolbarVisibility (Editor.java:1520) + // primarily seen in Samsung Nougat devices. + boolean superOnTouch = false; + try { + superOnTouch = super.onTouchEvent(event); + } catch (NullPointerException e) { + Log.w("Nacho", String.format("Error during touch event of type [%d]", event.getAction()), e); + // can't handle or reproduce, but will monitor the error + } + + return wasHandled || superOnTouch; + } + + @Nullable + private Chip findTouchedChip(MotionEvent event) { + if (mChipTokenizer == null) { + return null; + } + + Editable text = getText(); + int offset = getOffsetForPosition(event.getX(), event.getY()); + List
+ * If there is no ChipTokenizer set, we call through to the super method.
+ *
+ * @param text the text to be chipified
+ */
+ @Override
+ protected void replaceText(CharSequence text) {
+ // If we have a ChipTokenizer, this will be handled by our OnItemClickListener so we can do nothing here.
+ // If we don't have a ChipTokenizer, we'll use the default behavior
+ if (mChipTokenizer == null) {
+ super.replaceText(text);
+ }
+ }
+
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ if (mIgnoreTextChangedEvents) {
+ return;
+ }
+
+ mTextChangedStart = start;
+ mTextChangedEnd = start + after;
+
+ // Check for backspace
+ if (mChipTokenizer != null) {
+ if (count > 0 && after < count) {
+ int end = start + count;
+ Editable message = getText();
+ Chip[] chips = mChipTokenizer.findAllChips(start, end, message);
+
+ for (Chip chip : chips) {
+ int spanStart = mChipTokenizer.findChipStart(chip, message);
+ int spanEnd = mChipTokenizer.findChipEnd(chip, message);
+ if ((spanStart < end) && (spanEnd > start)) {
+ // Add to remove list
+ mChipsToRemove.add(chip);
+ }
+ }
+ }
+ }
+ }
+
+ @Override
+ public void onTextChanged(@NonNull CharSequence textChanged, int start, int before, int count) {
+ }
+
+ @Override
+ public void afterTextChanged(Editable message) {
+ if (mIgnoreTextChangedEvents) {
+ return;
+ }
+
+ // Avoid triggering text changed events from changes we make in this method
+ beginUnwatchedTextChange();
+
+ // Handle backspace key
+ if (mChipTokenizer != null) {
+ Iterator
+ * In the context of this interface, a token is considered to be plain (non-chipped) text. Once a token is terminated it becomes or contains a chip.
+ *
+ * The CharSequences passed to the ChipTokenizer methods may contain both chipped text
+ * and plain text so the tokenizer must have some method of distinguishing between the two (e.g. using a delimeter character.
+ * The {@link #terminateToken(CharSequence, Object)} method is where a chip can be formed and returned to replace the plain text.
+ * Whatever class the implementation deems to represent a chip, must implement the {@link Chip} interface.
+ *
+ * This will also apply the provided {@link ChipConfiguration} to any existing chips in the provided text.
+ *
+ *
+ * (chip vertical spacing / 2)
+ * ----------------------------------------------------------
+ * | |
+ * (left margin) | (padding edge) text (padding between image) icon | (right margin)
+ * | |
+ * ----------------------------------------------------------
+ * (chip vertical spacing / 2)
+ *
+ *
+ * For chips with the icon on the left (see {@link #setShowIconOnLeft(boolean)}):
+ *
+ *
+ * (chip vertical spacing / 2)
+ * ----------------------------------------------------------
+ * | |
+ * (left margin) | icon (padding between image) text (padding edge) | (right margin)
+ * | |
+ * ----------------------------------------------------------
+ * (chip vertical spacing / 2)
+ *
+ */
+public class ChipSpan extends ImageSpan implements Chip {
+
+ private static final float SCALE_PERCENT_OF_CHIP_HEIGHT = 0.70f;
+ private static final boolean ICON_ON_LEFT_DEFAULT = true;
+
+ private int[] mStateSet = new int[]{};
+
+ private String mEllipsis;
+
+ private ColorStateList mDefaultBackgroundColor;
+ private ColorStateList mBackgroundColor;
+ private int mTextColor;
+ private int mCornerRadius = -1;
+ private int mIconBackgroundColor;
+
+ private int mTextSize = -1;
+ private int mPaddingEdgePx;
+ private int mPaddingBetweenImagePx;
+ private int mLeftMarginPx;
+ private int mRightMarginPx;
+ private int mMaxAvailableWidth = -1;
+
+ private CharSequence mText;
+ private String mTextToDraw;
+
+ private Drawable mIcon;
+ private boolean mShowIconOnLeft = ICON_ON_LEFT_DEFAULT;
+
+ private int mChipVerticalSpacing = 0;
+ private int mChipHeight = -1;
+ private int mChipWidth = -1;
+ private int mIconWidth;
+
+ private int mCachedSize = -1;
+
+ private Object mData;
+
+ /**
+ * Constructs a new ChipSpan.
+ *
+ * @param context a {@link Context} that will be used to retrieve default configurations from resource files
+ * @param text the text for the ChipSpan to display
+ * @param icon an optional icon (can be {@code null}) for the ChipSpan to display
+ */
+ public ChipSpan(@NonNull Context context, @NonNull CharSequence text, @Nullable Drawable icon, Object data) {
+ super(icon);
+ mIcon = icon;
+ mText = text;
+ mTextToDraw = mText.toString();
+
+ mEllipsis = context.getString(R.string.chip_ellipsis);
+
+ mDefaultBackgroundColor = context.getColorStateList(R.color.chip_material_background);
+ mBackgroundColor = mDefaultBackgroundColor;
+
+ mTextColor = context.getColor(R.color.chip_default_text_color);
+ mIconBackgroundColor = context.getColor(R.color.chip_default_icon_background_color);
+
+ Resources resources = context.getResources();
+ mPaddingEdgePx = resources.getDimensionPixelSize(R.dimen.chip_default_padding_edge);
+ mPaddingBetweenImagePx = resources.getDimensionPixelSize(R.dimen.chip_default_padding_between_image);
+ mLeftMarginPx = resources.getDimensionPixelSize(R.dimen.chip_default_left_margin);
+ mRightMarginPx = resources.getDimensionPixelSize(R.dimen.chip_default_right_margin);
+
+ mData = data;
+ }
+
+ /**
+ * Copy constructor to recreate a ChipSpan from an existing one
+ *
+ * @param context a {@link Context} that will be used to retrieve default configurations from resource files
+ * @param chipSpan the ChipSpan to copy
+ */
+ public ChipSpan(@NonNull Context context, @NonNull ChipSpan chipSpan) {
+ this(context, chipSpan.getText(), chipSpan.getDrawable(), chipSpan.getData());
+
+ mDefaultBackgroundColor = chipSpan.mDefaultBackgroundColor;
+ mTextColor = chipSpan.mTextColor;
+ mIconBackgroundColor = chipSpan.mIconBackgroundColor;
+ mCornerRadius = chipSpan.mCornerRadius;
+
+ mTextSize = chipSpan.mTextSize;
+ mPaddingEdgePx = chipSpan.mPaddingEdgePx;
+ mPaddingBetweenImagePx = chipSpan.mPaddingBetweenImagePx;
+ mLeftMarginPx = chipSpan.mLeftMarginPx;
+ mRightMarginPx = chipSpan.mRightMarginPx;
+ mMaxAvailableWidth = chipSpan.mMaxAvailableWidth;
+
+ mShowIconOnLeft = chipSpan.mShowIconOnLeft;
+
+ mChipVerticalSpacing = chipSpan.mChipVerticalSpacing;
+ mChipHeight = chipSpan.mChipHeight;
+
+ mStateSet = chipSpan.mStateSet;
+ }
+
+ @Override
+ public Object getData() {
+ return mData;
+ }
+
+ /**
+ * Sets the height of the chip. This height should not include any extra spacing (for extra vertical spacing call {@link #setChipVerticalSpacing(int)}).
+ * The background of the chip will fill the full height provided here. If this method is never called, the chip will have the height of one full line
+ * of text by default. If {@code -1} is passed here, the chip will revert to this default behavior.
+ *
+ * @param chipHeight the height to set in pixels
+ */
+ public void setChipHeight(int chipHeight) {
+ mChipHeight = chipHeight;
+ }
+
+ /**
+ * Sets the vertical spacing to include in between chips. Half of the value set here will be placed as empty space above the chip and half the value
+ * will be placed as empty space below the chip. Therefore chips on consecutive lines will have the full value as vertical space in between them.
+ * This spacing is achieved by adjusting the font metrics used by the text view containing these chips; however it does not come into effect until
+ * at least one chip is created. Note that vertical spacing is dependent on having a fixed chip height (set in {@link #setChipHeight(int)}). If a
+ * height is not specified in that method, the value set here will be ignored.
+ *
+ * @param chipVerticalSpacing the vertical spacing to set in pixels
+ */
+ public void setChipVerticalSpacing(int chipVerticalSpacing) {
+ mChipVerticalSpacing = chipVerticalSpacing;
+ }
+
+ /**
+ * Sets the font size for the chip's text. If this method is never called, the chip text will have the same font size as the text in the TextView
+ * containing this chip by default. If {@code -1} is passed here, the chip will revert to this default behavior.
+ *
+ * @param size the font size to set in pixels
+ */
+ public void setTextSize(int size) {
+ mTextSize = size;
+ invalidateCachedSize();
+ }
+
+ /**
+ * Sets the color for the chip's text.
+ *
+ * @param color the color to set (as a hexadecimal number in the form 0xAARRGGBB)
+ */
+ public void setTextColor(int color) {
+ mTextColor = color;
+ }
+
+ /**
+ * Sets where the icon (if an icon was provided in the constructor) will appear.
+ *
+ * @param showIconOnLeft if true, the icon will appear on the left, otherwise the icon will appear on the right
+ */
+ public void setShowIconOnLeft(boolean showIconOnLeft) {
+ this.mShowIconOnLeft = showIconOnLeft;
+ invalidateCachedSize();
+ }
+
+ /**
+ * Sets the left margin. This margin will appear as empty space (it will not share the chip's background color) to the left of the chip.
+ *
+ * @param leftMarginPx the left margin to set in pixels
+ */
+ public void setLeftMargin(int leftMarginPx) {
+ mLeftMarginPx = leftMarginPx;
+ invalidateCachedSize();
+ }
+
+ /**
+ * Sets the right margin. This margin will appear as empty space (it will not share the chip's background color) to the right of the chip.
+ *
+ * @param rightMarginPx the right margin to set in pixels
+ */
+ public void setRightMargin(int rightMarginPx) {
+ this.mRightMarginPx = rightMarginPx;
+ invalidateCachedSize();
+ }
+
+ /**
+ * Sets the background color. To configure which color in the {@link ColorStateList} is shown you can call {@link #setState(int[])}.
+ * Passing {@code null} here will cause the chip to revert to it's default background.
+ *
+ * @param backgroundColor a {@link ColorStateList} containing backgrounds for different states.
+ * @see #setState(int[])
+ */
+ public void setBackgroundColor(@Nullable ColorStateList backgroundColor) {
+ mBackgroundColor = backgroundColor != null ? backgroundColor : mDefaultBackgroundColor;
+ }
+
+ /**
+ * Sets the chip background corner radius.
+ *
+ * @param cornerRadius The corner radius value, in pixels.
+ */
+ public void setCornerRadius(@Dimension int cornerRadius) {
+ mCornerRadius = cornerRadius;
+ }
+
+ /**
+ * Sets the icon background color. This is the color of the circle that gets drawn behind the icon passed to the
+ * {@link #ChipSpan(Context, CharSequence, Drawable, Object)} constructor}
+ *
+ * @param iconBackgroundColor the icon background color to set (as a hexadecimal number in the form 0xAARRGGBB)
+ */
+ public void setIconBackgroundColor(int iconBackgroundColor) {
+ mIconBackgroundColor = iconBackgroundColor;
+ }
+
+ public void setMaxAvailableWidth(int maxAvailableWidth) {
+ mMaxAvailableWidth = maxAvailableWidth;
+ invalidateCachedSize();
+ }
+
+ /**
+ * Sets the UI state. This state will be reflected in the background color drawn for the chip.
+ *
+ * @param stateSet one of the state constants in {@link android.view.View}
+ * @see #setBackgroundColor(ColorStateList)
+ */
+ @Override
+ public void setState(int[] stateSet) {
+ this.mStateSet = stateSet != null ? stateSet : new int[]{};
+ }
+
+ @Override
+ public CharSequence getText() {
+ return mText;
+ }
+
+ @Override
+ public int getWidth() {
+ // If we haven't actually calculated a chip width yet just return -1, otherwise return the chip width + margins
+ return mChipWidth != -1 ? (mLeftMarginPx + mChipWidth + mRightMarginPx) : -1;
+ }
+
+ @Override
+ public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
+ boolean usingFontMetrics = (fm != null);
+
+ // Adjust the font metrics regardless of whether or not there is a cached size so that the text view can maintain its height
+ if (usingFontMetrics) {
+ adjustFontMetrics(paint, fm);
+ }
+
+ if (mCachedSize == -1 && usingFontMetrics) {
+ mIconWidth = (mIcon != null) ? calculateChipHeight(fm.top, fm.bottom) : 0;
+
+ int actualWidth = calculateActualWidth(paint);
+ mCachedSize = actualWidth;
+
+ if (mMaxAvailableWidth != -1) {
+ int maxAvailableWidthMinusMargins = mMaxAvailableWidth - mLeftMarginPx - mRightMarginPx;
+ if (actualWidth > maxAvailableWidthMinusMargins) {
+ mTextToDraw = mText + mEllipsis;
+
+ while ((calculateActualWidth(paint) > maxAvailableWidthMinusMargins) && mTextToDraw.length() > 0) {
+ int lastCharacterIndex = mTextToDraw.length() - mEllipsis.length() - 1;
+ if (lastCharacterIndex < 0) {
+ break;
+ }
+ mTextToDraw = mTextToDraw.substring(0, lastCharacterIndex) + mEllipsis;
+ }
+
+ // Avoid a negative width
+ mChipWidth = Math.max(0, maxAvailableWidthMinusMargins);
+ mCachedSize = mMaxAvailableWidth;
+ }
+ }
+ }
+
+ return mCachedSize;
+ }
+
+ private int calculateActualWidth(Paint paint) {
+ // Only change the text size if a text size was set
+ if (mTextSize != -1) {
+ paint.setTextSize(mTextSize);
+ }
+
+ int totalPadding = mPaddingEdgePx;
+
+ // Find text width
+ Rect bounds = new Rect();
+ paint.getTextBounds(mTextToDraw, 0, mTextToDraw.length(), bounds);
+ int textWidth = bounds.width();
+
+ if (mIcon != null) {
+ totalPadding += mPaddingBetweenImagePx;
+ } else {
+ totalPadding += mPaddingEdgePx;
+ }
+
+ mChipWidth = totalPadding + textWidth + mIconWidth;
+ return getWidth();
+ }
+
+ public void invalidateCachedSize() {
+ mCachedSize = -1;
+ }
+
+ /**
+ * Adjusts the provided font metrics to make it seem like the font takes up {@code mChipHeight + mChipVerticalSpacing} pixels in height.
+ * This effectively ensures that the TextView will have a height equal to {@code mChipHeight + mChipVerticalSpacing} + whatever padding it has set.
+ * In {@link #draw(Canvas, CharSequence, int, int, float, int, int, int, Paint)} the chip itself is drawn to that it is vertically centered with
+ * {@code mChipVerticalSpacing / 2} pixels of space above and below it
+ *
+ * @param paint the paint whose font metrics should be adjusted
+ * @param fm the font metrics object to populate through {@link Paint#getFontMetricsInt(Paint.FontMetricsInt)}
+ */
+ private void adjustFontMetrics(Paint paint, Paint.FontMetricsInt fm) {
+ // Only actually adjust font metrics if we have a chip height set
+ if (mChipHeight != -1) {
+ paint.getFontMetricsInt(fm);
+ int textHeight = fm.descent - fm.ascent;
+ // Break up the vertical spacing in half because half will go above the chip, half will go below the chip
+ int halfSpacing = mChipVerticalSpacing / 2;
+
+ // Given that the text is centered vertically within the chip, the amount of space above or below the text (inbetween the text and chip)
+ // is half their difference in height:
+ int spaceBetweenChipAndText = (mChipHeight - textHeight) / 2;
+
+ int textTop = fm.top;
+ int chipTop = fm.top - spaceBetweenChipAndText;
+
+ int textBottom = fm.bottom;
+ int chipBottom = fm.bottom + spaceBetweenChipAndText;
+
+ // The text may have been taller to begin with so we take the most negative coordinate (highest up) to be the top of the content
+ int topOfContent = Math.min(textTop, chipTop);
+ // Same as above but we want the largest positive coordinate (lowest down) to be the bottom of the content
+ int bottomOfContent = Math.max(textBottom, chipBottom);
+
+ // Shift the top up by halfSpacing and the bottom down by halfSpacing
+ int topOfContentWithSpacing = topOfContent - halfSpacing;
+ int bottomOfContentWithSpacing = bottomOfContent + halfSpacing;
+
+ // Change the font metrics so that the TextView thinks the font takes up the vertical space of a chip + spacing
+ fm.ascent = topOfContentWithSpacing;
+ fm.descent = bottomOfContentWithSpacing;
+ fm.top = topOfContentWithSpacing;
+ fm.bottom = bottomOfContentWithSpacing;
+ }
+ }
+
+ private int calculateChipHeight(int top, int bottom) {
+ // If a chip height was set we can return that, otherwise calculate it from top and bottom
+ return mChipHeight != -1 ? mChipHeight : bottom - top;
+ }
+
+ @Override
+ public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
+ // Shift everything mLeftMarginPx to the left to create an empty space on the left (creating the margin)
+ x += mLeftMarginPx;
+ if (mChipHeight != -1) {
+ // If we set a chip height, adjust to vertically center chip in the line
+ // Adding (bottom - top) / 2 shifts the chip down so the top of it will be centered vertically
+ // Subtracting (mChipHeight / 2) shifts the chip back up so that the center of it will be centered vertically (as desired)
+ top += ((bottom - top) / 2) - (mChipHeight / 2);
+ bottom = top + mChipHeight;
+ }
+
+ // Perform actual drawing
+ drawBackground(canvas, x, top, bottom, paint);
+ drawText(canvas, x, top, bottom, paint, mTextToDraw);
+ if (mIcon != null) {
+ drawIcon(canvas, x, top, bottom, paint);
+ }
+ }
+
+ private void drawBackground(Canvas canvas, float x, int top, int bottom, Paint paint) {
+ int backgroundColor = mBackgroundColor.getColorForState(mStateSet, mBackgroundColor.getDefaultColor());
+ paint.setColor(backgroundColor);
+ int height = calculateChipHeight(top, bottom);
+ RectF rect = new RectF(x, top, x + mChipWidth, bottom);
+ int cornerRadius = (mCornerRadius != -1) ? mCornerRadius : height / 2;
+ canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint);
+ paint.setColor(mTextColor);
+ }
+
+ private void drawText(Canvas canvas, float x, int top, int bottom, Paint paint, CharSequence text) {
+ if (mTextSize != -1) {
+ paint.setTextSize(mTextSize);
+ }
+ int height = calculateChipHeight(top, bottom);
+ Paint.FontMetrics fm = paint.getFontMetrics();
+
+ // The top value provided here is the y coordinate for the very top of the chip
+ // The y coordinate we are calculating is where the baseline of the text will be drawn
+ // Our objective is to have the midpoint between the top and baseline of the text be in line with the vertical center of the chip
+ // First we add height / 2 which will put the baseline at the vertical center of the chip
+ // Then we add half the height of the text which will lower baseline so that the midpoint is at the vertical center of the chip as desired
+ float adjustedY = top + ((height / 2) + ((-fm.top - fm.bottom) / 2));
+
+ // The x coordinate provided here is the left-most edge of the chip
+ // If there is no icon or the icon is on the right, then the text will start at the left-most edge, but indented with the edge padding, so we
+ // add mPaddingEdgePx
+ // If there is an icon and it's on the left, the text will start at the left-most edge, but indented by the combined width of the icon and
+ // the padding between the icon and text, so we add (mIconWidth + mPaddingBetweenImagePx)
+ float adjustedX = x + ((mIcon == null || !mShowIconOnLeft) ? mPaddingEdgePx : (mIconWidth + mPaddingBetweenImagePx));
+
+ canvas.drawText(text, 0, text.length(), adjustedX, adjustedY, paint);
+ }
+
+ private void drawIcon(Canvas canvas, float x, int top, int bottom, Paint paint) {
+ drawIconBackground(canvas, x, top, bottom, paint);
+ drawIconBitmap(canvas, x, top, bottom, paint);
+ }
+
+ private void drawIconBackground(Canvas canvas, float x, int top, int bottom, Paint paint) {
+ int height = calculateChipHeight(top, bottom);
+
+ paint.setColor(mIconBackgroundColor);
+
+ // Since it's a circle the diameter is equal to the height, so the radius == diameter / 2 == height / 2
+ int radius = height / 2;
+ // The coordinates that get passed to drawCircle are for the center of the circle
+ // x is the left edge of the chip, (x + mChipWidth) is the right edge of the chip
+ // So the center of the circle is one radius distance from either the left or right edge (depending on which side the icon is being drawn on)
+ float circleX = mShowIconOnLeft ? (x + radius) : (x + mChipWidth - radius);
+ // The y coordinate is always just one radius distance from the top
+ canvas.drawCircle(circleX, top + radius, radius, paint);
+
+ paint.setColor(mTextColor);
+ }
+
+ private void drawIconBitmap(Canvas canvas, float x, int top, int bottom, Paint paint) {
+ int height = calculateChipHeight(top, bottom);
+
+ // Create a scaled down version of the bitmap to fit within the circle (whose diameter == height)
+ Bitmap iconBitmap = Bitmap.createBitmap(mIcon.getIntrinsicWidth(), mIcon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
+ Bitmap scaledIconBitMap = scaleDown(iconBitmap, (float) height * SCALE_PERCENT_OF_CHIP_HEIGHT, true);
+ iconBitmap.recycle();
+ Canvas bitmapCanvas = new Canvas(scaledIconBitMap);
+ mIcon.setBounds(0, 0, bitmapCanvas.getWidth(), bitmapCanvas.getHeight());
+ mIcon.draw(bitmapCanvas);
+
+ // We are drawing a square icon inside of a circle
+ // The coordinates we pass to canvas.drawBitmap have to be for the top-left corner of the bitmap
+ // The bitmap should be inset by half of (circle width - bitmap width)
+ // Since it's a circle, the circle's width is equal to it's height which is equal to the chip height
+ float xInsetWithinCircle = (height - bitmapCanvas.getWidth()) / 2;
+
+ // The icon x coordinate is going to be insetWithinCircle pixels away from the left edge of the circle
+ // If the icon is on the left, the left edge of the circle is just x
+ // If the icon is on the right, the left edge of the circle is x + mChipWidth - height
+ float iconX = mShowIconOnLeft ? (x + xInsetWithinCircle) : (x + mChipWidth - height + xInsetWithinCircle);
+
+ // The y coordinate works the same way (only it's always from the top edge)
+ float yInsetWithinCircle = (height - bitmapCanvas.getHeight()) / 2;
+ float iconY = top + yInsetWithinCircle;
+
+ canvas.drawBitmap(scaledIconBitMap, iconX, iconY, paint);
+ }
+
+ private Bitmap scaleDown(Bitmap realImage, float maxImageSize, boolean filter) {
+ float ratio = Math.min(maxImageSize / realImage.getWidth(), maxImageSize / realImage.getHeight());
+ int width = Math.round(ratio * realImage.getWidth());
+ int height = Math.round(ratio * realImage.getHeight());
+ return Bitmap.createScaledBitmap(realImage, width, height, filter);
+ }
+
+ @Override
+ public String toString() {
+ return mText.toString();
+ }
+}
diff --git a/mastodon/src/main/java/com/hootsuite/nachos/chip/ChipSpanChipCreator.java b/mastodon/src/main/java/com/hootsuite/nachos/chip/ChipSpanChipCreator.java
new file mode 100644
index 000000000..b8055339a
--- /dev/null
+++ b/mastodon/src/main/java/com/hootsuite/nachos/chip/ChipSpanChipCreator.java
@@ -0,0 +1,60 @@
+package com.hootsuite.nachos.chip;
+
+import android.content.Context;
+import android.content.res.ColorStateList;
+import android.graphics.Color;
+
+import com.hootsuite.nachos.ChipConfiguration;
+
+import androidx.annotation.NonNull;
+
+public class ChipSpanChipCreator implements ChipCreator
+ *
+ *
+ * @param character the character to mark as a chip terminator
+ * @param behavior the behavior describing how to respond to the chip terminator
+ */
+ void addChipTerminator(char character, int behavior);
+
+ /**
+ * Customizes the way paste events are handled.
+ * If one of:
+ *
+ *
+ * is passed, all chip terminators will be handled with that behavior when a paste event occurs.
+ * If {@link #PASTE_BEHAVIOR_USE_DEFAULT} is passed, whatever behavior is configured for a particular chip terminator
+ * (through {@link #setChipTerminators(Map)} or {@link #addChipTerminator(char, int)} will be used for that chip terminator
+ *
+ * @param pasteBehavior the behavior to use on a paste event
+ */
+ void setPasteBehavior(int pasteBehavior);
+
+ /**
+ * Parses the provided text looking for characters marked as chip terminators through {@link #addChipTerminator(char, int)} and {@link #setChipTerminators(Map)}.
+ * The provided {@link Editable} will be modified if chip terminators are encountered.
+ *
+ * @param tokenizer the {@link ChipTokenizer} to use to identify and chipify tokens in the text
+ * @param text the text in which to search for chip terminators tokens to be chipped
+ * @param start the index at which to begin looking for chip terminators (inclusive)
+ * @param end the index at which to end looking for chip terminators (exclusive)
+ * @param isPasteEvent true if this handling is for a paste event in which case the behavior set in {@link #setPasteBehavior(int)} will be used,
+ * otherwise false
+ * @return an non-negative integer indicating the index where the cursor (selection) should be placed once the handling is complete,
+ * or a negative integer indicating that the cursor should not be moved.
+ */
+ int findAndHandleChipTerminators(@NonNull ChipTokenizer tokenizer, @NonNull Editable text, int start, int end, boolean isPasteEvent);
+}
diff --git a/mastodon/src/main/java/com/hootsuite/nachos/terminator/DefaultChipTerminatorHandler.java b/mastodon/src/main/java/com/hootsuite/nachos/terminator/DefaultChipTerminatorHandler.java
new file mode 100644
index 000000000..e10c252d1
--- /dev/null
+++ b/mastodon/src/main/java/com/hootsuite/nachos/terminator/DefaultChipTerminatorHandler.java
@@ -0,0 +1,115 @@
+package com.hootsuite.nachos.terminator;
+
+import android.text.Editable;
+
+import com.hootsuite.nachos.tokenizer.ChipTokenizer;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+public class DefaultChipTerminatorHandler implements ChipTerminatorHandler {
+
+ @Nullable
+ private Mapcursor within text.
+ */
+ int findTokenStart(CharSequence text, int cursor);
+
+ /**
+ * Returns the end of the token (minus trailing punctuation)
+ * that begins at offset cursor within text.
+ */
+ int findTokenEnd(CharSequence text, int cursor);
+
+ /**
+ * Searches through {@code text} for any tokens.
+ *
+ * @param text the text in which to search for un-terminated tokens
+ * @return a list of {@link Pair}s of the form (startIndex, endIndex) containing the locations of all
+ * unterminated tokens
+ */
+ @NonNull
+ Listtext, modified, if necessary, to ensure that
+ * it ends with a token terminator (for example a space or comma).
+ */
+ CharSequence terminateToken(CharSequence text, @Nullable Object data);
+
+ /**
+ * Terminates (converts from token into chip) all unterminated tokens in the provided text.
+ * This method CAN alter the provided text.
+ *
+ * @param text the text in which to terminate all tokens
+ */
+ void terminateAllTokens(Editable text);
+
+ /**
+ * Finds the index of the first character in {@code text} that is a part of {@code chip}
+ *
+ * @param chip the chip whose start should be found
+ * @param text the text in which to search for the start of {@code chip}
+ * @return the start index of the chip
+ */
+ int findChipStart(Chip chip, Spanned text);
+
+ /**
+ * Finds the index of the character after the last character in {@code text} that is a part of {@code chip}
+ *
+ * @param chip the chip whose end should be found
+ * @param text the text in which to search for the end of {@code chip}
+ * @return the end index of the chip
+ */
+ int findChipEnd(Chip chip, Spanned text);
+
+ /**
+ * Searches through {@code text} for any chips
+ *
+ * @param start index to start looking for terminated tokens (inclusive)
+ * @param end index to end looking for terminated tokens (exclusive)
+ * @param text the text in which to search for terminated tokens
+ * @return a list of objects implementing the {@link Chip} interface to represent the terminated tokens
+ */
+ @NonNull
+ Chip[] findAllChips(int start, int end, Spanned text);
+
+ /**
+ * Effectively does the opposite of {@link #terminateToken(CharSequence, Object)} by reverting the provided chip back into a token.
+ * This method CAN alter the provided text.
+ *
+ * @param chip the chip to revert into a token
+ * @param text the text in which the chip resides
+ */
+ void revertChipToToken(Chip chip, Editable text);
+
+ /**
+ * Removes a chip and any text it encompasses from {@code text}. This method CAN alter the provided text.
+ *
+ * @param chip the chip to remove
+ * @param text the text to remove the chip from
+ */
+ void deleteChip(Chip chip, Editable text);
+
+ /**
+ * Removes a chip, any text it encompasses AND any padding text (such as spaces) that may have been inserted when the chip was created in
+ * {@link #terminateToken(CharSequence, Object)} or after. This method CAN alter the provided text.
+ *
+ * @param chip the chip to remove
+ * @param text the text to remove the chip and padding from
+ */
+ void deleteChipAndPadding(Chip chip, Editable text);
+}
diff --git a/mastodon/src/main/java/com/hootsuite/nachos/tokenizer/SpanChipTokenizer.java b/mastodon/src/main/java/com/hootsuite/nachos/tokenizer/SpanChipTokenizer.java
new file mode 100644
index 000000000..6acdd6ca6
--- /dev/null
+++ b/mastodon/src/main/java/com/hootsuite/nachos/tokenizer/SpanChipTokenizer.java
@@ -0,0 +1,246 @@
+package com.hootsuite.nachos.tokenizer;
+
+import android.content.Context;
+import android.text.Editable;
+import android.text.SpannableString;
+import android.text.Spanned;
+import android.util.Pair;
+
+import com.hootsuite.nachos.ChipConfiguration;
+import com.hootsuite.nachos.chip.Chip;
+import com.hootsuite.nachos.chip.ChipCreator;
+import com.hootsuite.nachos.chip.ChipSpan;
+
+import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+/**
+ * A default implementation of {@link ChipTokenizer}.
+ * This implementation does the following:
+ *
+ *
+ * Each terminated token will therefore look like the following (this is what will be returned from {@link #terminateToken(CharSequence, Object)}):
+ *
+ *
+ *
+ * -----------------------------------------------------------
+ * | SpannableString |
+ * | ---------------------------------------------------- |
+ * | | ChipSpan | |
+ * | | | |
+ * | | space separator text separator space | |
+ * | | | |
+ * | ---------------------------------------------------- |
+ * -----------------------------------------------------------
+ *
+ *
+ * @see ChipSpan
+ */
+public class SpanChipTokenizer