Yuito-app-android/app/src/main/java/com/keylesspalace/tusky/util/SmartLengthInputFilter.java

155 lines
6.3 KiB
Java
Raw Normal View History

Add support for collapsible statuses when they exceed 500 characters (#825) * Update Gradle plugin to work with Android Studio 3.3 Canary Android Studio 3.1.4 Stable doesn't render layout previews in this project for whatever reason. Switching to the latest 3.3 Canary release fixes the issue without affecting Gradle scripts but requires the new Android Gradle plugin to match the new Android Studio release. This commit will be reverted once development on the feature is done. * Update gradle build script to allow installing debug builds alongside store version This will allow developers, testers, etc to work on Tusky will not having to worry about overwriting, uninstalling, fiddling with a preinstalled application which would mean having to login again every time the development cycle starts/finishes and manually reinstalling the app. * Add UI changes to support collapsing statuses The button uses subtle styling to not be distracting like the CW button on the timeline The button is toggleable, full width to match the status textbox hitbox width and also is shorter to not be too intrusive between the status text and images, or the post below * Update status data model to store whether the message has been collapsed * Update status action listener to notify of collapsed state changing Provide stubs in all implementing classes and mark as TODO the stubs that require a proper implementation for the feature to work. * Add implementation code to handle status collapse/expand in timeline Code has not been added elsewhere to simplify testing. Once the code will be considered stable it will be also included in other status action listener implementers. * Add preferences so that users can toggle the collapsing of long posts This is currently limited to a simple toggle, it would be nice to implement a more advanced UI to offer the user more control over the feature. * Update Gradle plugin to work with latest Android Studio 3.3 Canary 8 Just like the other commit, this will be reverted once the feature is working. I simply don't want to deal with what changes in my installation of Android Studio 3.1.4 Stable which breaks the layout preview rendering. * Update data models and utils for statuses to better handle collapsing I forgot that data isn't available from the API and can't really be built from scratch using existing data due to preferences. A new, extra boolean should fix the issue. * Fix search breaking due to newly introduced variables in utils classes * Fix timeline breaking due to newly introduced variables in utils classes * Fix item status text for collapsed toggle being shown in the wrong state * Update timeline fragment to refresh the list when collapsed settings change * Add support for status content collapse in timeline viewholder * Fix view holder truncating posts using temporary debug settings at 50 chars * Add toggle support to notification layout as well * Add support for collapsed statuses to search results * Add support for expandable content to notifications too * Update codebase with some suggested changes by @charlang * Update more code with more suggestions and move null-safety into view data * Update even more code with even more suggested code changes * Revert a0a41ca and 0ee004d (Android Studio 3.1 to Android Studio 3.3 updates) * Add an input filter utility class to reuse code for trimming statuses * Update UI of statuses to show a taller collapsible button * Update notification fragment logging to simplify null checks * Add smartness to SmartLengthInputFilter such as word trimming and runway * Fix posts with show more button even if bad ratio didn't collapse * Fix thread view showing button but not collapsing by implementing the feature * Fix spannable losing spans when collapsed and restore length to 500 characters * Remove debug build suffix as per request * Fix all the merging happened in f66d689, 623cad2 and 7056ba5 * Fix notification button spanning full width rather than content width * Add a way to access a singleton to smart filter and use clearer code * Update view holders using smart input filters to use more singletons * Fix code style lacking spaces before boolean checks in ifs and others * Remove all code related to collapsibility preferences, strings included * Update style to match content warning toggle button * Update strings to give cleaner differentiation between CW and collapse * Update smart filter code to use fully qualified names to avoid confusion
2018-09-19 19:51:20 +02:00
/*
* Copyright 2018 Diego Rossi (@_HellPie)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.keylesspalace.tusky.util;
import android.text.InputFilter;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
/**
* A customized version of {@link android.text.InputFilter.LengthFilter} which allows smarter
* constraints and adds better visuals such as:
* <ul>
* <li>Ellipsis at the end of the constrained text to show continuation.</li>
* <li>Trimming of invisible characters (new lines, spaces, etc.) from the constrained text.</li>
* <li>Constraints end at the end of the last "word", before a whitespace.</li>
* <li>Expansion of the limit by up to 10 characters to facilitate the previous constraint.</li>
* <li>Constraints are not applied if the percentage of hidden content is too small.</li>
* </ul>
*
* Some of these features are configurable through at instancing time.
*/
public class SmartLengthInputFilter implements InputFilter {
/**
* Defines how many characters to extend beyond the limit to cut at the end of the word on the
* boundary of it rather than cutting at the word preceding that one.
*/
private static final int RUNWAY = 10;
/**
* Default for maximum status length on Mastodon and default collapsing length on Pleroma.
*/
public static final int LENGTH_DEFAULT = 500;
/**
* Stores a reusable singleton instance of a {@link SmartLengthInputFilter} already configured
* to the default maximum length of {@value #LENGTH_DEFAULT}.
*/
public static final SmartLengthInputFilter INSTANCE = new SmartLengthInputFilter(LENGTH_DEFAULT);
private final int max;
private final boolean allowRunway;
private final boolean skipIfBadRatio;
/**
* Creates a new {@link SmartLengthInputFilter} instance with a predefined maximum length and
* all the smart constraint features this class supports.
*
* @param max The maximum length before trimming. May change based on other constraints.
*/
public SmartLengthInputFilter(int max) {
this(max, true, true);
}
/**
* Fully configures a new {@link SmartLengthInputFilter} to fine tune the state of the supported
* smart constraints this class supports.
*
* @param max The maximum length before trimming.
* @param allowRunway Whether to extend {@param max} by an extra 10 characters
* and trim precisely at the end of the closest word.
* @param skipIfBadRatio Whether to skip trimming entirely if the trimmed content
* will be less than 25% of the shown content.
*/
public SmartLengthInputFilter(int max, boolean allowRunway, boolean skipIfBadRatio) {
this.max = max;
this.allowRunway = allowRunway;
this.skipIfBadRatio = skipIfBadRatio;
}
/**
* Calculates if it's worth trimming the message at a specific limit or if the content that will
* be hidden will not be enough to justify the operation.
*
* @param message The message to trim.
* @param limit The maximum length after trimming.
* @return Whether the message should be trimmed or not.
*/
public static boolean hasBadRatio(Spanned message, int limit) {
return (double) limit / message.length() > 0.75;
}
/** {@inheritDoc} */
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// Code originally imported from InputFilter.LengthFilter but heavily customized.
// https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/text/InputFilter.java#175
int sourceLength = source.length();
int keep = max - (dest.length() - (dend - dstart));
if (keep <= 0) return "";
if (keep >= end - start) return null; // keep original
keep += start;
// Enable skipping trimming if the ratio is not good enough
if (skipIfBadRatio && (double)keep / sourceLength > 0.75)
return null;
// Enable trimming at the end of the closest word if possible
if (allowRunway && Character.isLetterOrDigit(source.charAt(keep))) {
int boundary;
// Android N+ offer a clone of the ICU APIs in Java for better internationalization and
// unicode support. Using the ICU version of BreakIterator grants better support for
// those without having to add the ICU4J library at a minimum Api trade-off.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
android.icu.text.BreakIterator iterator = android.icu.text.BreakIterator.getWordInstance();
iterator.setText(source.toString());
boundary = iterator.following(keep);
if (keep - boundary > RUNWAY) boundary = iterator.preceding(keep);
} else {
java.text.BreakIterator iterator = java.text.BreakIterator.getWordInstance();
iterator.setText(source.toString());
boundary = iterator.following(keep);
if (keep - boundary > RUNWAY) boundary = iterator.preceding(keep);
}
keep = boundary;
} else {
// If no runway is allowed simply remove whitespaces if present
while (Character.isWhitespace(source.charAt(keep - 1))) {
--keep;
if (keep == start) return "";
}
}
if (Character.isHighSurrogate(source.charAt(keep - 1))) {
--keep;
if (keep == start) return "";
}
if (source instanceof Spanned) {
return new SpannableStringBuilder(source, start, keep).append("");
} else {
return source.subSequence(start, keep) + "";
}
}
}