Yuito-app-android/app/src/main/java/com/keylesspalace/tusky/fragment/ViewThreadFragment.java

684 lines
26 KiB
Java
Raw Normal View History

/* Copyright 2017 Andrew Dawson
*
2017-04-10 02:12:31 +02:00
* This file is a part of Tusky.
*
2017-04-10 02:12:31 +02:00
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Tusky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
2017-04-10 02:12:31 +02:00
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
2017-04-10 02:12:31 +02:00
* You should have received a copy of the GNU General Public License along with Tusky; if not,
* see <http://www.gnu.org/licenses>. */
2017-05-05 00:55:34 +02:00
package com.keylesspalace.tusky.fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.arch.core.util.Function;
import androidx.lifecycle.Lifecycle;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.material.snackbar.Snackbar;
import com.keylesspalace.tusky.AccountListActivity;
import com.keylesspalace.tusky.BaseActivity;
import com.keylesspalace.tusky.BuildConfig;
import com.keylesspalace.tusky.R;
import com.keylesspalace.tusky.ViewThreadActivity;
2017-05-05 00:55:34 +02:00
import com.keylesspalace.tusky.adapter.ThreadAdapter;
import com.keylesspalace.tusky.appstore.BlockEvent;
import com.keylesspalace.tusky.appstore.BookmarkEvent;
import com.keylesspalace.tusky.appstore.EventHub;
import com.keylesspalace.tusky.appstore.FavoriteEvent;
import com.keylesspalace.tusky.appstore.PinEvent;
import com.keylesspalace.tusky.appstore.ReblogEvent;
import com.keylesspalace.tusky.appstore.StatusComposedEvent;
import com.keylesspalace.tusky.appstore.StatusDeletedEvent;
import com.keylesspalace.tusky.di.Injectable;
import com.keylesspalace.tusky.entity.Filter;
import com.keylesspalace.tusky.entity.Poll;
import com.keylesspalace.tusky.entity.Status;
2017-05-05 00:55:34 +02:00
import com.keylesspalace.tusky.interfaces.StatusActionListener;
import com.keylesspalace.tusky.network.FilterModel;
import com.keylesspalace.tusky.network.MastodonApi;
import com.keylesspalace.tusky.settings.PrefKeys;
import com.keylesspalace.tusky.util.CardViewMode;
import com.keylesspalace.tusky.util.LinkHelper;
import com.keylesspalace.tusky.util.ListStatusAccessibilityDelegate;
import com.keylesspalace.tusky.util.PairedList;
import com.keylesspalace.tusky.util.StatusDisplayOptions;
import com.keylesspalace.tusky.util.ViewDataUtils;
2017-05-29 12:14:09 +02:00
import com.keylesspalace.tusky.view.ConversationLineItemDecoration;
import com.keylesspalace.tusky.viewdata.AttachmentViewData;
import com.keylesspalace.tusky.viewdata.StatusViewData;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import kotlin.collections.CollectionsKt;
import static autodispose2.AutoDispose.autoDisposable;
import static autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider.from;
public final class ViewThreadFragment extends SFragment implements
SwipeRefreshLayout.OnRefreshListener, StatusActionListener, Injectable {
private static final String TAG = "ViewThreadFragment";
@Inject
public MastodonApi mastodonApi;
@Inject
public EventHub eventHub;
@Inject
public FilterModel filterModel;
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView recyclerView;
private ThreadAdapter adapter;
private String thisThreadsStatusId;
2017-11-30 20:12:09 +01:00
private boolean alwaysShowSensitiveMedia;
private boolean alwaysOpenSpoiler;
private int statusIndex = 0;
private final PairedList<Status, StatusViewData.Concrete> statuses =
2017-11-30 20:12:09 +01:00
new PairedList<>(new Function<Status, StatusViewData.Concrete>() {
@Override
public StatusViewData.Concrete apply(Status status) {
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
return ViewDataUtils.statusToViewData(
status,
alwaysShowSensitiveMedia || !status.getActionableStatus().getSensitive(),
Timeline paging (#2238) * first setup * network timeline paging / improvements * rename classes / move to correct package * remove unused class TimelineAdapter * some code cleanup * remove TimelineRepository, put mapper functions in TimelineTypeMappers.kt * add db migration * cleanup unused code * bugfix * make default timeline settings work again * fix pinning statuses from timeline * fix network timeline * respect account settings in NetworkTimelineRemoteMediator * respect account settings in NetworkTimelineRemoteMediator * update license headers * show error view when an error occurs * cleanup some todos * fix db migration * fix changing mediaPreviewEnabled setting * fix "load more" button appearing on top of timeline * fix filtering and other bugs * cleanup cache after 14 days * fix TimelineDAOTest * fix code formatting * add NetworkTimeline unit tests * add CachedTimeline unit tests * fix code formatting * move TimelineDaoTest to unit tests * implement removeAllByInstance for CachedTimelineViewModel * fix code formatting * fix bug in TimelineDao.deleteAllFromInstance * improve loading more statuses in NetworkTimelineViewModel * improve loading more statuses in NetworkTimelineViewModel * fix bug where empty state was shown too soon * reload top of cached timeline on app start * improve CachedTimelineRemoteMediator and Tests * improve cached timeline tests * fix some more todos * implement TimelineFragment.removeItem * fix ListStatusAccessibilityDelegate * fix crash in NetworkTimelineViewModel.loadMore * fix default state of collapsible statuses * fix default state of collapsible statuses -tests * fix showing/hiding media in the timeline * get rid of some not-null assertion operators in TimelineTypeMappers * fix tests * error handling in CachedTimelineViewModel.loadMore * keep local status state when refreshing cached statuses * keep local status state when refreshing network timeline statuses * show placeholder loading state in cached timeline * better comments, some code cleanup * add TimelineViewModelTest, improve code, fix bug * fix ktlint * fix voting in boosted polls * code improvement
2022-01-11 19:00:29 +01:00
alwaysOpenSpoiler,
true
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
);
2017-11-30 20:12:09 +01:00
}
});
public static ViewThreadFragment newInstance(String id) {
Bundle arguments = new Bundle(1);
ViewThreadFragment fragment = new ViewThreadFragment();
arguments.putString("id", id);
fragment.setArguments(arguments);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
thisThreadsStatusId = getArguments().getString("id");
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
StatusDisplayOptions statusDisplayOptions = new StatusDisplayOptions(
preferences.getBoolean("animateGifAvatars", false),
accountManager.getActiveAccount().getMediaPreviewEnabled(),
preferences.getBoolean("absoluteTimeView", false),
preferences.getBoolean("showBotOverlay", true),
preferences.getBoolean("useBlurhash", true),
preferences.getBoolean("showCardsInTimelines", false) ?
CardViewMode.INDENTED :
CardViewMode.NONE,
preferences.getBoolean("confirmReblogs", true),
2021-12-29 13:44:00 +01:00
preferences.getBoolean("confirmFavourites", false),
preferences.getBoolean(PrefKeys.WELLBEING_HIDE_STATS_POSTS, false),
preferences.getBoolean(PrefKeys.ANIMATE_CUSTOM_EMOJIS, false)
);
adapter = new ThreadAdapter(statusDisplayOptions, this);
}
@Override
2017-11-30 20:12:09 +01:00
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_view_thread, container, false);
Context context = getContext();
swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.tusky_blue);
recyclerView = rootView.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAccessibilityDelegateCompat(
new ListStatusAccessibilityDelegate(recyclerView, this, statuses::getPairedItemOrNull));
DividerItemDecoration divider = new DividerItemDecoration(
context, layoutManager.getOrientation());
recyclerView.addItemDecoration(divider);
2017-11-30 20:12:09 +01:00
recyclerView.addItemDecoration(new ConversationLineItemDecoration(context));
alwaysShowSensitiveMedia = accountManager.getActiveAccount().getAlwaysShowSensitiveMedia();
alwaysOpenSpoiler = accountManager.getActiveAccount().getAlwaysOpenSpoiler();
reloadFilters();
recyclerView.setAdapter(adapter);
statuses.clear();
((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
return rootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
onRefresh();
2018-07-12 21:21:53 +02:00
eventHub.getEvents()
.observeOn(AndroidSchedulers.mainThread())
.to(autoDisposable(from(this, Lifecycle.Event.ON_DESTROY)))
2018-07-12 21:21:53 +02:00
.subscribe(event -> {
if (event instanceof FavoriteEvent) {
handleFavEvent((FavoriteEvent) event);
} else if (event instanceof ReblogEvent) {
handleReblogEvent((ReblogEvent) event);
} else if (event instanceof BookmarkEvent) {
handleBookmarkEvent((BookmarkEvent) event);
} else if (event instanceof PinEvent) {
handlePinEvent(((PinEvent) event));
2018-07-12 21:21:53 +02:00
} else if (event instanceof BlockEvent) {
removeAllByAccountId(((BlockEvent) event).getAccountId());
} else if (event instanceof StatusComposedEvent) {
handleStatusComposedEvent((StatusComposedEvent) event);
} else if (event instanceof StatusDeletedEvent) {
handleStatusDeletedEvent((StatusDeletedEvent) event);
}
});
}
public void onRevealPressed() {
boolean allExpanded = allExpanded();
for (int i = 0; i < statuses.size(); i++) {
updateViewData(i, statuses.getPairedItem(i).copyWithExpanded(!allExpanded));
}
updateRevealIcon();
}
private boolean allExpanded() {
boolean allExpanded = true;
for (int i = 0; i < statuses.size(); i++) {
if (!statuses.getPairedItem(i).isExpanded()) {
allExpanded = false;
break;
}
}
return allExpanded;
}
@Override
public void onRefresh() {
sendStatusRequest(thisThreadsStatusId);
sendThreadRequest(thisThreadsStatusId);
}
@Override
public void onReply(int position) {
super.reply(statuses.get(position));
}
@Override
public void onReblog(final boolean reblog, final int position) {
final Status status = statuses.get(position);
timelineCases.reblog(statuses.get(position).getId(), reblog)
.observeOn(AndroidSchedulers.mainThread())
.to(autoDisposable(from(this)))
.subscribe(
this::replaceStatus,
(t) -> Log.d(TAG,
"Failed to reblog status: " + status.getId(), t)
);
}
@Override
public void onFavourite(final boolean favourite, final int position) {
final Status status = statuses.get(position);
timelineCases.favourite(statuses.get(position).getId(), favourite)
.observeOn(AndroidSchedulers.mainThread())
.to(autoDisposable(from(this)))
.subscribe(
this::replaceStatus,
(t) -> Log.d(TAG,
"Failed to favourite status: " + status.getId(), t)
);
}
@Override
public void onBookmark(final boolean bookmark, final int position) {
final Status status = statuses.get(position);
timelineCases.bookmark(statuses.get(position).getId(), bookmark)
.observeOn(AndroidSchedulers.mainThread())
.to(autoDisposable(from(this)))
.subscribe(
this::replaceStatus,
(t) -> Log.d(TAG,
"Failed to bookmark status: " + status.getId(), t)
);
}
private void replaceStatus(Status status) {
updateStatus(status.getId(), (__) -> status);
}
private void updateStatus(String statusId, Function<Status, Status> mapper) {
int position = indexOfStatus(statusId);
if (position >= 0 && position < statuses.size()) {
Status oldStatus = statuses.get(position);
Status newStatus = mapper.apply(oldStatus);
StatusViewData.Concrete oldViewData = statuses.getPairedItem(position);
statuses.set(position, newStatus);
updateViewData(position, oldViewData.copyWithStatus(newStatus));
}
}
@Override
public void onMore(@NonNull View view, int position) {
super.more(statuses.get(position), view, position);
}
@Override
public void onViewMedia(int position, int attachmentIndex, @NonNull View view) {
Status status = statuses.get(position);
super.viewMedia(attachmentIndex, AttachmentViewData.list(status), view);
}
@Override
public void onViewThread(int position) {
Status status = statuses.get(position);
if (thisThreadsStatusId.equals(status.getId())) {
// If already viewing this thread, don't reopen it.
return;
}
super.viewThread(status.getActionableId(), status.getActionableStatus().getUrl());
}
@Override
public void onViewUrl(String url) {
Status status = null;
if (!statuses.isEmpty()) {
status = statuses.get(statusIndex);
}
if (status != null && status.getUrl().equals(url)) {
// already viewing the status with this url
// probably just a preview federated and the user is clicking again to view more -> open the browser
// this can happen with some friendica statuses
LinkHelper.openLink(requireContext(), url);
return;
}
super.onViewUrl(url);
}
2017-06-28 10:10:56 +02:00
@Override
public void onOpenReblog(int position) {
// there should be no reblogs in the thread but let's implement it to be sure
super.openReblog(statuses.get(position));
}
@Override
public void onExpandedChange(boolean expanded, int position) {
updateViewData(
position,
statuses.getPairedItem(position).copyWithExpanded(expanded)
);
updateRevealIcon();
}
@Override
public void onContentHiddenChange(boolean isShowing, int position) {
updateViewData(
position,
statuses.getPairedItem(position).copyWithShowingContent(isShowing)
);
}
private void updateViewData(int position, StatusViewData.Concrete newViewData) {
statuses.setPairedItem(position, newViewData);
adapter.setItem(position, newViewData, true);
2017-06-28 10:10:56 +02:00
}
2017-11-03 22:17:31 +01:00
@Override
public void onLoadMore(int position) {
2017-11-03 22:17:31 +01:00
}
@Override
public void onShowReblogs(int position) {
String statusId = statuses.get(position).getId();
Intent intent = AccountListActivity.newIntent(getContext(), AccountListActivity.Type.REBLOGGED, statusId);
((BaseActivity) getActivity()).startActivityWithSlideInAnimation(intent);
}
@Override
public void onShowFavs(int position) {
String statusId = statuses.get(position).getId();
Intent intent = AccountListActivity.newIntent(getContext(), AccountListActivity.Type.FAVOURITED, statusId);
((BaseActivity) getActivity()).startActivityWithSlideInAnimation(intent);
}
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
@Override
public void onContentCollapsedChange(boolean isCollapsed, int position) {
adapter.setItem(
position,
statuses.getPairedItem(position).copyWithCollapsed(isCollapsed),
true
);
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
}
@Override
public void onViewTag(String tag) {
super.viewTag(tag);
}
@Override
public void onViewAccount(String id) {
super.viewAccount(id);
}
@Override
public void removeItem(int position) {
if (position == statusIndex) {
//the status got removed, close the activity
getActivity().finish();
}
statuses.remove(position);
adapter.setStatuses(statuses.getPairedCopy());
}
public void onVoteInPoll(int position, @NonNull List<Integer> choices) {
final Status status = statuses.get(position).getActionableStatus();
setVoteForPoll(status.getId(), status.getPoll().votedCopy(choices));
timelineCases.voteInPoll(status.getId(), status.getPoll().getId(), choices)
.observeOn(AndroidSchedulers.mainThread())
.to(autoDisposable(from(this)))
.subscribe(
(newPoll) -> setVoteForPoll(status.getId(), newPoll),
(t) -> Log.d(TAG,
"Failed to vote in poll: " + status.getId(), t)
);
}
private void setVoteForPoll(String statusId, Poll newPoll) {
updateStatus(statusId, s -> s.copyWithPoll(newPoll));
}
private void removeAllByAccountId(String accountId) {
Status status = null;
if (!statuses.isEmpty()) {
status = statuses.get(statusIndex);
}
// using iterator to safely remove items while iterating
Iterator<Status> iterator = statuses.iterator();
while (iterator.hasNext()) {
Status s = iterator.next();
if (s.getAccount().getId().equals(accountId) || s.getActionableStatus().getAccount().getId().equals(accountId)) {
iterator.remove();
}
}
statusIndex = statuses.indexOf(status);
if (statusIndex == -1) {
//the status got removed, close the activity
getActivity().finish();
return;
}
adapter.setDetailedStatusPosition(statusIndex);
adapter.setStatuses(statuses.getPairedCopy());
}
private void sendStatusRequest(final String id) {
mastodonApi.status(id)
.observeOn(AndroidSchedulers.mainThread())
.to(autoDisposable(from(this, Lifecycle.Event.ON_DESTROY)))
.subscribe(
status -> {
int position = setStatus(status);
recyclerView.scrollToPosition(position);
},
throwable -> onThreadRequestFailure(id, throwable)
);
}
2017-02-27 01:14:50 +01:00
private void sendThreadRequest(final String id) {
mastodonApi.statusContext(id)
.observeOn(AndroidSchedulers.mainThread())
.to(autoDisposable(from(this, Lifecycle.Event.ON_DESTROY)))
.subscribe(
context -> {
swipeRefreshLayout.setRefreshing(false);
setContext(context.getAncestors(), context.getDescendants());
},
throwable -> onThreadRequestFailure(id, throwable)
);
}
private void onThreadRequestFailure(final String id, final Throwable throwable) {
View view = getView();
swipeRefreshLayout.setRefreshing(false);
if (view != null) {
Snackbar.make(view, R.string.error_generic, Snackbar.LENGTH_LONG)
.setAction(R.string.action_retry, v -> {
sendThreadRequest(id);
sendStatusRequest(id);
})
.show();
} else {
Log.e(TAG, "Network request failed", throwable);
}
}
private int setStatus(Status status) {
if (statuses.size() > 0
&& statusIndex < statuses.size()
2022-02-20 10:58:12 +01:00
&& statuses.get(statusIndex).getId().equals(status.getId())) {
// Do not add this status on refresh, it's already in there.
statuses.set(statusIndex, status);
return statusIndex;
}
int i = statusIndex;
statuses.add(i, status);
adapter.setDetailedStatusPosition(i);
adapter.addItem(i, statuses.getPairedItem(i));
updateRevealIcon();
return i;
}
private void setContext(List<Status> unfilteredAncestors, List<Status> unfilteredDescendants) {
Status mainStatus = null;
// In case of refresh, remove old ancestors and descendants first. We'll remove all blindly,
// as we have no guarantee on their order to be the same as before
int oldSize = statuses.size();
if (oldSize > 1) {
mainStatus = statuses.get(statusIndex);
statuses.clear();
adapter.clearItems();
}
ArrayList<Status> ancestors = new ArrayList<>();
for (Status status : unfilteredAncestors)
if (!filterModel.shouldFilterStatus(status))
ancestors.add(status);
// Insert newly fetched ancestors
statusIndex = ancestors.size();
adapter.setDetailedStatusPosition(statusIndex);
statuses.addAll(0, ancestors);
List<StatusViewData.Concrete> ancestorsViewDatas = statuses.getPairedCopy().subList(0, statusIndex);
if (BuildConfig.DEBUG && ancestors.size() != ancestorsViewDatas.size()) {
String error = String.format(Locale.getDefault(),
"Incorrectly got statusViewData sublist." +
" ancestors.size == %d ancestorsViewDatas.size == %d," +
" statuses.size == %d",
ancestors.size(), ancestorsViewDatas.size(), statuses.size());
throw new AssertionError(error);
}
adapter.addAll(0, ancestorsViewDatas);
if (mainStatus != null) {
// In case we needed to delete everything (which is way easier than deleting
// everything except one), re-insert the remaining status here.
// Not filtering the main status, since the user explicitly chose to be here
statuses.add(statusIndex, mainStatus);
StatusViewData.Concrete viewData = statuses.getPairedItem(statusIndex);
2017-11-30 20:12:09 +01:00
adapter.addItem(statusIndex, viewData);
}
ArrayList<Status> descendants = new ArrayList<>();
for (Status status : unfilteredDescendants)
if (!filterModel.shouldFilterStatus(status))
descendants.add(status);
// Insert newly fetched descendants
statuses.addAll(descendants);
List<StatusViewData.Concrete> descendantsViewData;
descendantsViewData = statuses.getPairedCopy()
.subList(statuses.size() - descendants.size(), statuses.size());
if (BuildConfig.DEBUG && descendants.size() != descendantsViewData.size()) {
String error = String.format(Locale.getDefault(),
"Incorrectly got statusViewData sublist." +
" descendants.size == %d descendantsViewData.size == %d," +
" statuses.size == %d",
descendants.size(), descendantsViewData.size(), statuses.size());
throw new AssertionError(error);
}
adapter.addAll(descendantsViewData);
updateRevealIcon();
}
private void handleFavEvent(FavoriteEvent event) {
updateStatus(event.getStatusId(), (s) -> {
s.setFavourited(event.getFavourite());
return s;
});
}
private void handleReblogEvent(ReblogEvent event) {
updateStatus(event.getStatusId(), (s) -> {
s.setReblogged(event.getReblog());
return s;
});
}
private void handleBookmarkEvent(BookmarkEvent event) {
updateStatus(event.getStatusId(), (s) -> {
s.setBookmarked(event.getBookmark());
return s;
});
}
private void handlePinEvent(PinEvent event) {
updateStatus(event.getStatusId(), (s) -> s.copyWithPinned(event.getPinned()));
}
private void handleStatusComposedEvent(StatusComposedEvent event) {
Status eventStatus = event.getStatus();
if (eventStatus.getInReplyToId() == null) return;
if (eventStatus.getInReplyToId().equals(thisThreadsStatusId)) {
insertStatus(eventStatus, statuses.size());
} else {
// If new status is a reply to some status in the thread, insert new status after it
// We only check statuses below main status, ones on top don't belong to this thread
for (int i = statusIndex; i < statuses.size(); i++) {
Status status = statuses.get(i);
if (eventStatus.getInReplyToId().equals(status.getId())) {
insertStatus(eventStatus, i + 1);
break;
}
}
}
}
private void insertStatus(Status status, int at) {
statuses.add(at, status);
adapter.addItem(at, statuses.getPairedItem(at));
}
private void handleStatusDeletedEvent(StatusDeletedEvent event) {
int index = this.indexOfStatus(event.getStatusId());
if (index != -1) {
statuses.remove(index);
adapter.removeItem(index);
}
}
private int indexOfStatus(String statusId) {
return CollectionsKt.indexOfFirst(this.statuses, (s) -> s.getId().equals(statusId));
}
private void updateRevealIcon() {
ViewThreadActivity activity = ((ViewThreadActivity) getActivity());
if (activity == null) return;
boolean hasAnyWarnings = false;
// Statuses are updated from the main thread so nothing should change while iterating
for (int i = 0; i < statuses.size(); i++) {
if (!TextUtils.isEmpty(statuses.get(i).getSpoilerText())) {
hasAnyWarnings = true;
break;
}
}
if (!hasAnyWarnings) {
activity.setRevealButtonState(ViewThreadActivity.REVEAL_BUTTON_HIDDEN);
return;
}
activity.setRevealButtonState(allExpanded() ? ViewThreadActivity.REVEAL_BUTTON_HIDE :
ViewThreadActivity.REVEAL_BUTTON_REVEAL);
}
private void reloadFilters() {
mastodonApi.getFilters()
.to(autoDisposable(AndroidLifecycleScopeProvider.from(this)))
.subscribe(
(filters) -> {
List<Filter> relevantFilters = CollectionsKt.filter(
filters,
(f) -> f.getContext().contains(Filter.THREAD)
);
filterModel.initWithFilters(relevantFilters);
recyclerView.post(this::applyFilters);
},
(t) -> Log.e(TAG, "Failed to load filters", t)
);
}
private void applyFilters() {
CollectionsKt.removeAll(this.statuses, filterModel::shouldFilterStatus);
adapter.setStatuses(this.statuses.getPairedCopy());
}
}