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

1562 lines
61 KiB
Java
Raw Normal View History

2017-01-20 09:09:10 +01:00
/* Copyright 2017 Andrew Dawson
*
2017-04-10 02:12:31 +02:00
* This file is a part of Tusky.
2017-01-20 09:09:10 +01:00
*
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.
2017-01-20 09:09:10 +01:00
*
* 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-01-20 09:09:10 +01:00
*
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-01-20 09:09:10 +01:00
2017-05-05 00:55:34 +02:00
package com.keylesspalace.tusky.fragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.arch.core.util.Function;
import androidx.core.util.Pair;
import androidx.core.widget.ContentLoadingProgressBar;
import androidx.lifecycle.Lifecycle;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.AsyncDifferConfig;
import androidx.recyclerview.widget.AsyncListDiffer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListUpdateCallback;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.keylesspalace.tusky.AccountListActivity;
import com.keylesspalace.tusky.BaseActivity;
2017-05-05 00:55:34 +02:00
import com.keylesspalace.tusky.R;
import com.keylesspalace.tusky.adapter.StatusBaseViewHolder;
2017-05-05 00:55:34 +02:00
import com.keylesspalace.tusky.adapter.TimelineAdapter;
import com.keylesspalace.tusky.appstore.BlockEvent;
import com.keylesspalace.tusky.appstore.DomainMuteEvent;
import com.keylesspalace.tusky.appstore.EventHub;
import com.keylesspalace.tusky.appstore.FavoriteEvent;
import com.keylesspalace.tusky.appstore.MuteEvent;
import com.keylesspalace.tusky.appstore.PreferenceChangedEvent;
2018-08-13 02:14:57 +02:00
import com.keylesspalace.tusky.appstore.QuickReplyEvent;
import com.keylesspalace.tusky.appstore.ReblogEvent;
import com.keylesspalace.tusky.appstore.StatusComposedEvent;
import com.keylesspalace.tusky.appstore.StatusDeletedEvent;
2018-12-19 08:05:51 +01:00
import com.keylesspalace.tusky.appstore.StreamUpdateEvent;
import com.keylesspalace.tusky.appstore.UnfollowEvent;
2018-12-19 08:05:51 +01:00
import com.keylesspalace.tusky.db.AccountEntity;
import com.keylesspalace.tusky.db.AccountManager;
import com.keylesspalace.tusky.di.Injectable;
import com.keylesspalace.tusky.entity.Filter;
import com.keylesspalace.tusky.entity.Poll;
import com.keylesspalace.tusky.entity.Status;
import com.keylesspalace.tusky.interfaces.ActionButtonActivity;
import com.keylesspalace.tusky.interfaces.RefreshableFragment;
import com.keylesspalace.tusky.interfaces.ReselectableFragment;
2017-05-05 00:55:34 +02:00
import com.keylesspalace.tusky.interfaces.StatusActionListener;
import com.keylesspalace.tusky.network.MastodonApi;
import com.keylesspalace.tusky.repository.Placeholder;
import com.keylesspalace.tusky.repository.TimelineRepository;
import com.keylesspalace.tusky.repository.TimelineRequestMode;
import com.keylesspalace.tusky.util.Either;
import com.keylesspalace.tusky.util.LinkHelper;
import com.keylesspalace.tusky.util.ListStatusAccessibilityDelegate;
import com.keylesspalace.tusky.util.ListUtils;
import com.keylesspalace.tusky.util.PairedList;
import com.keylesspalace.tusky.util.StringUtils;
2017-05-05 00:55:34 +02:00
import com.keylesspalace.tusky.util.ThemeUtils;
import com.keylesspalace.tusky.util.ViewDataUtils;
import com.keylesspalace.tusky.view.BackgroundMessageView;
2017-05-29 12:14:09 +02:00
import com.keylesspalace.tusky.view.EndlessOnScrollListener;
import com.keylesspalace.tusky.viewdata.StatusViewData;
2018-12-19 08:05:51 +01:00
import net.accelf.yuito.TimelineStreamingListener;
import java.io.IOException;
2018-12-19 08:05:51 +01:00
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import at.connyduck.sparkbutton.helpers.Utils;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import kotlin.Unit;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
2018-12-19 08:05:51 +01:00
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import retrofit2.Call;
import retrofit2.Callback;
2017-05-10 04:36:05 +02:00
import retrofit2.Response;
import static android.content.Context.CONNECTIVITY_SERVICE;
import static com.uber.autodispose.AutoDispose.autoDisposable;
import static com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider.from;
public class TimelineFragment extends SFragment implements
SwipeRefreshLayout.OnRefreshListener,
StatusActionListener,
Injectable, ReselectableFragment, RefreshableFragment {
2017-11-03 22:17:31 +01:00
private static final String TAG = "TimelineF"; // logging tag
private static final String KIND_ARG = "kind";
private static final String HASHTAG_OR_ID_ARG = "hashtag_or_id";
private static final String ARG_ENABLE_SWIPE_TO_REFRESH = "arg.enable.swipe.to.refresh";
2017-11-03 22:17:31 +01:00
private static final int LOAD_AT_ONCE = 30;
private boolean isSwipeToRefreshEnabled = true;
private boolean isNeedRefresh;
2017-11-03 22:17:31 +01:00
2017-05-05 00:55:34 +02:00
public enum Kind {
HOME,
2017-03-31 04:31:17 +02:00
PUBLIC_LOCAL,
PUBLIC_FEDERATED,
TAG,
USER,
USER_PINNED,
Account activity redesign (#662) * Refactor-all-the-things version of the fix for issue #573 * Migrate SpanUtils to kotlin because why not * Minimal fix for issue #573 * Add tests for compose spanning * Clean up code suggestions * Make FakeSpannable.getSpans implementation less awkward * Add secondary validation pass for urls * Address code review feedback * Fixup type filtering in FakeSpannable again * Make all mentions in compose activity use the default link color * new layout for AccountActivity * fix the light theme * convert AccountActivity to Kotlin * introduce AccountViewModel * Merge branch 'master' into account-activity-redesign # Conflicts: # app/src/main/java/com/keylesspalace/tusky/AccountActivity.java * add Bot badge to profile * parse custom emojis in usernames * add possibility to cancel follow request * add third tab on profiles * add account fields to profile * add support for moved accounts * set click listener on account moved view * fix tests * use 24dp as statusbar size * add ability to hide reblogs from followed accounts * add button to edit own account to AccountActivity * set toolbar top margin programmatically * fix crash * add shadow behind statusbar * introduce ViewExtensions to clean up code * move code out of offsetChangedListener for perf reasons * clean up stuff * add error handling * improve type safety * fix ConstraintLayout warning * remove unneeded ressources * fix event dispatching * fix crash in event handling * set correct emoji on title * improve some things * wrap follower/foillowing/status views
2018-06-18 13:26:18 +02:00
USER_WITH_REPLIES,
2018-01-06 19:01:37 +01:00
FAVOURITES,
LIST
}
private enum FetchEnd {
TOP,
BOTTOM,
2017-11-03 22:17:31 +01:00
MIDDLE
}
@Inject
public EventHub eventHub;
@Inject
TimelineRepository timelineRepo;
@Inject
public AccountManager accountManager;
private boolean eventRegistered = false;
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView recyclerView;
private ProgressBar progressBar;
private ContentLoadingProgressBar topProgressBar;
private BackgroundMessageView statusView;
private TimelineAdapter adapter;
private Kind kind;
private String hashtagOrId;
private LinearLayoutManager layoutManager;
private EndlessOnScrollListener scrollListener;
private boolean filterRemoveReplies;
private boolean filterRemoveReblogs;
private boolean hideFab;
private boolean bottomLoading;
private boolean didLoadEverythingBottom;
2017-11-30 20:12:09 +01:00
private boolean alwaysShowSensitiveMedia;
private boolean alwaysOpenSpoiler;
private boolean initialUpdateFailed = false;
2017-11-30 20:12:09 +01:00
private SharedPreferences preferences;
private boolean reduceTimelineRoading;
private boolean checkMobileNetwork;
2018-12-19 08:05:51 +01:00
private WebSocket webSocket;
private PairedList<Either<Placeholder, Status>, StatusViewData> statuses =
new PairedList<>(new Function<Either<Placeholder, Status>, StatusViewData>() {
@Override
public StatusViewData apply(Either<Placeholder, Status> input) {
Status status = input.asRightOrNull();
if (status != null) {
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,
alwaysOpenSpoiler
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
);
} else {
Placeholder placeholder = input.asLeft();
return new StatusViewData.Placeholder(placeholder.getId(), false);
}
}
});
public static TimelineFragment newInstance(Kind kind) {
return newInstance(kind, null);
}
public static TimelineFragment newInstance(Kind kind, @Nullable String hashtagOrId) {
return newInstance(kind, hashtagOrId, true);
}
public static TimelineFragment newInstance(Kind kind, @Nullable String hashtagOrId, boolean enableSwipeToRefresh) {
TimelineFragment fragment = new TimelineFragment();
Bundle arguments = new Bundle();
arguments.putString(KIND_ARG, kind.name());
arguments.putString(HASHTAG_OR_ID_ARG, hashtagOrId);
arguments.putBoolean(ARG_ENABLE_SWIPE_TO_REFRESH, enableSwipeToRefresh);
fragment.setArguments(arguments);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle arguments = Objects.requireNonNull(getArguments());
kind = Kind.valueOf(arguments.getString(KIND_ARG));
if (kind == Kind.TAG
|| kind == Kind.USER
|| kind == Kind.USER_PINNED
|| kind == Kind.USER_WITH_REPLIES
|| kind == Kind.LIST) {
hashtagOrId = arguments.getString(HASHTAG_OR_ID_ARG);
}
2018-07-08 10:16:19 +02:00
adapter = new TimelineAdapter(dataSource, this);
isSwipeToRefreshEnabled = arguments.getBoolean(ARG_ENABLE_SWIPE_TO_REFRESH, true);
preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_timeline, container, false);
recyclerView = rootView.findViewById(R.id.recyclerView);
swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
progressBar = rootView.findViewById(R.id.progressBar);
statusView = rootView.findViewById(R.id.statusView);
topProgressBar = rootView.findViewById(R.id.topProgressBar);
setupSwipeRefreshLayout();
setupRecyclerView();
updateAdapter();
setupTimelinePreferences();
if (statuses.isEmpty()) {
progressBar.setVisibility(View.VISIBLE);
bottomLoading = true;
this.sendInitialRequest();
} else {
progressBar.setVisibility(View.GONE);
if (isNeedRefresh)
onRefresh();
}
return rootView;
}
2018-12-19 08:05:51 +01:00
@Override
public void onStart() {
super.onStart();
startStreaming();
}
@Override
public void onStop() {
super.onStop();
stopStreaming();
}
private void startStreaming() {
if (preferences.getBoolean("useHTLStream", false) && kind == Kind.HOME) {
connectWebsocket(buildStreamingUrl());
}
}
private String buildStreamingUrl() {
AccountEntity activeAccount = accountManager.getActiveAccount();
if (activeAccount != null) {
return "wss://" + activeAccount.getDomain() + "/api/v1/streaming/?" + "stream=user" + "&" + "access_token" + "=" + activeAccount.getAccessToken();
} else {
return null;
}
}
private void connectWebsocket(String endpoint) {
if (webSocket != null) {
stopStreaming();
}
Request request = new Request.Builder()
.url(endpoint)
.build();
OkHttpClient client = new OkHttpClient.Builder()
.build();
webSocket = client.newWebSocket(request, new TimelineStreamingListener(eventHub));
}
private void stopStreaming() {
if (webSocket == null) {
return;
}
webSocket.close(1000, null);
webSocket = null;
}
private void sendInitialRequest() {
if (this.kind == Kind.HOME) {
this.tryCache();
} else {
sendFetchTimelineRequest(null, null, null, FetchEnd.BOTTOM, -1);
}
}
private void tryCache() {
// Request timeline from disk to make it quick, then replace it with timeline from
// the server to update it
this.timelineRepo.getStatuses(null, null, null, LOAD_AT_ONCE,
TimelineRequestMode.DISK)
.observeOn(AndroidSchedulers.mainThread())
.as(autoDisposable(from(this, Lifecycle.Event.ON_DESTROY)))
.subscribe(statuses -> {
filterStatuses(statuses);
if (statuses.size() > 1) {
this.clearPlaceholdersForResponse(statuses);
this.statuses.clear();
this.statuses.addAll(statuses);
this.updateAdapter();
this.progressBar.setVisibility(View.GONE);
// Request statuses including current top to refresh all of them
}
this.updateCurrent();
this.loadAbove();
});
}
private void updateCurrent() {
if (this.statuses.isEmpty()) {
return;
}
String topId = CollectionsKt.first(this.statuses, Either::isRight).asRight().getId();
this.timelineRepo.getStatuses(topId, null, null, LOAD_AT_ONCE,
TimelineRequestMode.NETWORK)
.observeOn(AndroidSchedulers.mainThread())
.as(autoDisposable(from(this, Lifecycle.Event.ON_DESTROY)))
.subscribe(
(statuses) -> {
this.initialUpdateFailed = false;
// When cached timeline is too old, we would replace it with nothing
if (!statuses.isEmpty()) {
filterStatuses(statuses);
if (!this.statuses.isEmpty()) {
// clear old cached statuses
Iterator<Either<Placeholder, Status>> iterator = this.statuses.iterator();
while (iterator.hasNext()) {
Either<Placeholder, Status> item = iterator.next();
if (item.isRight()) {
Status status = item.asRight();
if (status.getId().length() < topId.length() || status.getId().compareTo(topId) < 0) {
iterator.remove();
}
} else {
Placeholder placeholder = item.asLeft();
if (placeholder.getId().length() < topId.length() || placeholder.getId().compareTo(topId) < 0) {
iterator.remove();
}
}
}
}
this.statuses.addAll(statuses);
this.updateAdapter();
}
this.bottomLoading = false;
},
(e) -> {
this.initialUpdateFailed = true;
// Indicate that we are not loading anymore
this.progressBar.setVisibility(View.GONE);
this.swipeRefreshLayout.setRefreshing(false);
});
}
private void setupTimelinePreferences() {
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
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
alwaysShowSensitiveMedia = accountManager.getActiveAccount().getAlwaysShowSensitiveMedia();
alwaysOpenSpoiler = accountManager.getActiveAccount().getAlwaysOpenSpoiler();
boolean mediaPreviewEnabled = accountManager.getActiveAccount().getMediaPreviewEnabled();
adapter.setMediaPreviewEnabled(mediaPreviewEnabled);
boolean useAbsoluteTime = preferences.getBoolean("absoluteTimeView", false);
adapter.setUseAbsoluteTime(useAbsoluteTime);
boolean showBotOverlay = preferences.getBoolean("showBotOverlay", true);
adapter.setShowBotOverlay(showBotOverlay);
boolean animateAvatar = preferences.getBoolean("animateGifAvatars", false);
adapter.setAnimateAvatar(animateAvatar);
boolean filter = preferences.getBoolean("tabFilterHomeReplies", true);
filterRemoveReplies = kind == Kind.HOME && !filter;
filter = preferences.getBoolean("tabFilterHomeBoosts", true);
filterRemoveReblogs = kind == Kind.HOME && !filter;
reloadFilters(false);
updateLimitedBandwidthStatus();
}
private static boolean filterContextMatchesKind(Kind kind, List<String> filterContext) {
// home, notifications, public, thread
switch (kind) {
case HOME:
return filterContext.contains(Filter.HOME);
case PUBLIC_FEDERATED:
case PUBLIC_LOCAL:
case TAG:
return filterContext.contains(Filter.PUBLIC);
case FAVOURITES:
return (filterContext.contains(Filter.PUBLIC) || filterContext.contains(Filter.NOTIFICATIONS));
default:
return false;
}
}
@Override
2019-09-24 20:33:29 +02:00
protected boolean filterIsRelevant(@NonNull Filter filter) {
return filterContextMatchesKind(kind, filter.getContext());
}
@Override
protected void refreshAfterApplyingFilters() {
fullyRefresh();
}
private void setupSwipeRefreshLayout() {
swipeRefreshLayout.setEnabled(isSwipeToRefreshEnabled);
if (isSwipeToRefreshEnabled) {
Context context = swipeRefreshLayout.getContext();
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.tusky_blue);
swipeRefreshLayout.setProgressBackgroundColorSchemeColor(ThemeUtils.getColor(context,
android.R.attr.colorBackground));
}
}
private void setupRecyclerView() {
recyclerView.setAccessibilityDelegateCompat(
new ListStatusAccessibilityDelegate(recyclerView, this, statuses::getPairedItemOrNull));
2018-07-05 21:32:49 +02:00
Context context = recyclerView.getContext();
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
DividerItemDecoration divider = new DividerItemDecoration(
context, layoutManager.getOrientation());
recyclerView.addItemDecoration(divider);
2017-05-10 04:36:05 +02:00
// CWs are expanded without animation, buttons animate itself, we don't need it basically
((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
recyclerView.setAdapter(adapter);
}
private void deleteStatusById(String id) {
for (int i = 0; i < statuses.size(); i++) {
Either<Placeholder, Status> either = statuses.get(i);
if (either.isRight()
&& id.equals(either.asRight().getId())) {
statuses.remove(either);
updateAdapter();
break;
}
}
if (statuses.size() == 0) {
showNothing();
}
2017-05-10 04:36:05 +02:00
}
private void showNothing() {
statusView.setVisibility(View.VISIBLE);
statusView.setup(R.drawable.elephant_friend_empty, R.string.message_empty, null);
}
2017-05-10 04:36:05 +02:00
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/* This is delayed until onActivityCreated solely because MainActivity.composeButton isn't
* guaranteed to be set until then. */
if (actionButtonPresent()) {
/* Use a modified scroll listener that both loads more statuses as it goes, and hides
* the follow button on down-scroll. */
2017-08-05 11:34:50 +02:00
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
hideFab = preferences.getBoolean("fabHide", false);
scrollListener = new EndlessOnScrollListener(layoutManager) {
@Override
public void onScrolled(RecyclerView view, int dx, int dy) {
super.onScrolled(view, dx, dy);
2017-08-05 11:34:50 +02:00
ActionButtonActivity activity = (ActionButtonActivity) getActivity();
FloatingActionButton composeButton = activity.getActionButton();
if (composeButton != null) {
if (hideFab) {
if (dy > 0 && composeButton.isShown()) {
composeButton.hide(); // hides the button if we're scrolling down
} else if (dy < 0 && !composeButton.isShown()) {
composeButton.show(); // shows it if we are scrolling up
}
} else if (!composeButton.isShown()) {
composeButton.show();
}
2017-11-03 22:17:31 +01:00
}
}
@Override
public void onLoadMore(int totalItemsCount, RecyclerView view) {
TimelineFragment.this.onLoadMore();
}
};
} else {
// Just use the basic scroll listener to load more statuses.
scrollListener = new EndlessOnScrollListener(layoutManager) {
@Override
public void onLoadMore(int totalItemsCount, RecyclerView view) {
TimelineFragment.this.onLoadMore();
}
};
}
recyclerView.addOnScrollListener(scrollListener);
2018-07-12 21:21:53 +02:00
if (!eventRegistered) {
eventHub.getEvents()
.observeOn(AndroidSchedulers.mainThread())
.as(autoDisposable(from(this, Lifecycle.Event.ON_DESTROY)))
.subscribe(event -> {
if (event instanceof FavoriteEvent) {
FavoriteEvent favEvent = ((FavoriteEvent) event);
handleFavEvent(favEvent);
} else if (event instanceof ReblogEvent) {
ReblogEvent reblogEvent = (ReblogEvent) event;
handleReblogEvent(reblogEvent);
} else if (event instanceof UnfollowEvent) {
if (kind == Kind.HOME) {
String id = ((UnfollowEvent) event).getAccountId();
removeAllByAccountId(id);
}
} else if (event instanceof BlockEvent) {
2019-02-27 20:03:28 +01:00
if (kind != Kind.USER && kind != Kind.USER_WITH_REPLIES && kind != Kind.USER_PINNED) {
String id = ((BlockEvent) event).getAccountId();
removeAllByAccountId(id);
}
} else if (event instanceof MuteEvent) {
2019-02-27 20:03:28 +01:00
if (kind != Kind.USER && kind != Kind.USER_WITH_REPLIES && kind != Kind.USER_PINNED) {
String id = ((MuteEvent) event).getAccountId();
removeAllByAccountId(id);
}
} else if (event instanceof DomainMuteEvent) {
if (kind != Kind.USER && kind != Kind.USER_WITH_REPLIES && kind != Kind.USER_PINNED) {
String instance = ((DomainMuteEvent) event).getInstance();
removeAllByInstance(instance);
}
} else if (event instanceof StatusDeletedEvent) {
2019-02-27 20:03:28 +01:00
if (kind != Kind.USER && kind != Kind.USER_WITH_REPLIES && kind != Kind.USER_PINNED) {
String id = ((StatusDeletedEvent) event).getStatusId();
deleteStatusById(id);
}
} else if (event instanceof StatusComposedEvent) {
Status status = ((StatusComposedEvent) event).getStatus();
handleStatusComposeEvent(status);
} else if (event instanceof PreferenceChangedEvent) {
onPreferenceChanged(((PreferenceChangedEvent) event).getPreferenceKey());
2018-12-19 08:05:51 +01:00
} else if (event instanceof StreamUpdateEvent) {
if (kind == Kind.HOME) {
handleStreamUpdateEvent((StreamUpdateEvent) event);
}
2018-07-12 21:21:53 +02:00
}
});
eventRegistered = true;
}
}
@Override
public void onRefresh() {
if (isSwipeToRefreshEnabled)
swipeRefreshLayout.setEnabled(true);
this.statusView.setVisibility(View.GONE);
isNeedRefresh = false;
if (this.initialUpdateFailed) {
updateCurrent();
}
this.loadAbove();
}
private void loadAbove() {
String firstOrNull = null;
String secondOrNull = null;
for (int i = 0; i < this.statuses.size(); i++) {
Either<Placeholder, Status> status = this.statuses.get(i);
if (status.isRight()) {
firstOrNull = status.asRight().getId();
if (i + 1 < statuses.size() && statuses.get(i + 1).isRight()) {
secondOrNull = statuses.get(i + 1).asRight().getId();
}
break;
}
}
if (firstOrNull != null) {
this.sendFetchTimelineRequest(null, firstOrNull, secondOrNull, FetchEnd.TOP, -1);
} else {
this.sendFetchTimelineRequest(null, null, null, FetchEnd.BOTTOM, -1);
}
}
@Override
public void onReply(int position) {
2018-08-13 02:14:57 +02:00
switch (kind) {
case HOME:
case PUBLIC_LOCAL:
case PUBLIC_FEDERATED:
case TAG:
case FAVOURITES:
case LIST: {
eventHub.dispatch(new QuickReplyEvent(statuses.get(position).asRight().getActionableStatus()));
break;
}
case USER:
case USER_PINNED:
case USER_WITH_REPLIES: {
super.reply(statuses.get(position).asRight());
break;
}
}
}
@Override
public void onReblog(final boolean reblog, final int position) {
final Status status = statuses.get(position).asRight();
timelineCases.reblog(status, reblog)
.observeOn(AndroidSchedulers.mainThread())
.as(autoDisposable(from(this, Lifecycle.Event.ON_DESTROY)))
.subscribe(
(newStatus) -> setRebloggedForStatus(position, status, reblog),
(err) -> Log.d(TAG, "Failed to reblog status " + status.getId(), err)
);
}
private void setRebloggedForStatus(int position, Status status, boolean reblog) {
status.setReblogged(reblog);
if (status.getReblog() != null) {
status.getReblog().setReblogged(reblog);
}
Pair<StatusViewData.Concrete, Integer> actual =
findStatusAndPosition(position, status);
if (actual == null) return;
StatusViewData newViewData =
new StatusViewData.Builder(actual.first)
.setReblogged(reblog)
.createStatusViewData();
statuses.setPairedItem(actual.second, newViewData);
updateAdapter();
}
@Override
public void onFavourite(final boolean favourite, final int position) {
final Status status = statuses.get(position).asRight();
timelineCases.favourite(status, favourite)
.observeOn(AndroidSchedulers.mainThread())
.as(autoDisposable(from(this, Lifecycle.Event.ON_DESTROY)))
.subscribe(
(newStatus) -> setFavouriteForStatus(position, newStatus, favourite),
(err) -> Log.d(TAG, "Failed to favourite status " + status.getId(), err)
);
}
private void setFavouriteForStatus(int position, Status status, boolean favourite) {
status.setFavourited(favourite);
if (status.getReblog() != null) {
status.getReblog().setFavourited(favourite);
}
Pair<StatusViewData.Concrete, Integer> actual =
findStatusAndPosition(position, status);
if (actual == null) return;
StatusViewData newViewData = new StatusViewData
.Builder(actual.first)
.setFavourited(favourite)
.createStatusViewData();
statuses.setPairedItem(actual.second, newViewData);
updateAdapter();
}
2019-09-03 16:08:13 +02:00
@Override
public void onQuote(int position) {
super.quote(statuses.get(position).asRight());
}
public void onVoteInPoll(int position, @NonNull List<Integer> choices) {
final Status status = statuses.get(position).asRight();
Poll votedPoll = status.getActionableStatus().getPoll().votedCopy(choices);
setVoteForPoll(position, status, votedPoll);
timelineCases.voteInPoll(status, choices)
.observeOn(AndroidSchedulers.mainThread())
.as(autoDisposable(from(this)))
.subscribe(
(newPoll) -> setVoteForPoll(position, status, newPoll),
(t) -> Log.d(TAG,
"Failed to vote in poll: " + status.getId(), t)
);
}
private void setVoteForPoll(int position, Status status, Poll newPoll) {
Pair<StatusViewData.Concrete, Integer> actual =
findStatusAndPosition(position, status);
if (actual == null) return;
StatusViewData newViewData = new StatusViewData
.Builder(actual.first)
.setPoll(newPoll)
.createStatusViewData();
statuses.setPairedItem(actual.second, newViewData);
updateAdapter();
}
@Override
public void onMore(@NonNull View view, final int position) {
super.more(statuses.get(position).asRight(), view, position);
}
2017-06-28 10:10:56 +02:00
@Override
public void onOpenReblog(int position) {
super.openReblog(statuses.get(position).asRight());
}
@Override
public void onExpandedChange(boolean expanded, int position) {
StatusViewData newViewData = new StatusViewData.Builder(
((StatusViewData.Concrete) statuses.getPairedItem(position)))
.setIsExpanded(expanded).createStatusViewData();
statuses.setPairedItem(position, newViewData);
updateAdapter();
}
@Override
public void onContentHiddenChange(boolean isShowing, int position) {
StatusViewData newViewData = new StatusViewData.Builder(
((StatusViewData.Concrete) statuses.getPairedItem(position)))
.setIsShowingSensitiveContent(isShowing).createStatusViewData();
statuses.setPairedItem(position, newViewData);
updateAdapter();
2017-06-28 10:10:56 +02:00
}
@Override
public void onShowReblogs(int position) {
String statusId = statuses.get(position).asRight().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).asRight().getId();
Intent intent = AccountListActivity.newIntent(getContext(), AccountListActivity.Type.FAVOURITED, statusId);
((BaseActivity) getActivity()).startActivityWithSlideInAnimation(intent);
}
2017-11-03 22:17:31 +01:00
@Override
public void onLoadMore(int position) {
//check bounds before accessing list,
if (statuses.size() >= position && position > 0) {
Status fromStatus = statuses.get(position - 1).asRightOrNull();
Status toStatus = statuses.get(position + 1).asRightOrNull();
String maxMinusOne =
statuses.size() > position + 1 && statuses.get(position + 2).isRight()
? statuses.get(position + 1).asRight().getId()
: null;
if (fromStatus == null || toStatus == null) {
Log.e(TAG, "Failed to load more at " + position + ", wrong placeholder position");
return;
}
sendFetchTimelineRequest(fromStatus.getId(), toStatus.getId(), maxMinusOne,
FetchEnd.MIDDLE, position);
2017-11-03 22:17:31 +01:00
Placeholder placeholder = statuses.get(position).asLeft();
StatusViewData newViewData = new StatusViewData.Placeholder(placeholder.getId(), true);
2017-11-03 22:17:31 +01:00
statuses.setPairedItem(position, newViewData);
updateAdapter();
2017-11-03 22:17:31 +01:00
} else {
Log.e(TAG, "error loading more");
2017-11-03 22:17:31 +01:00
}
}
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) {
if (position < 0 || position >= statuses.size()) {
Log.e(TAG, String.format("Tried to access out of bounds status position: %d of %d", position, statuses.size() - 1));
return;
}
StatusViewData status = statuses.getPairedItem(position);
if (!(status instanceof StatusViewData.Concrete)) {
// Statuses PairedList contains a base type of StatusViewData.Concrete and also doesn't
// check for null values when adding values to it although this doesn't seem to be an issue.
Log.e(TAG, String.format(
"Expected StatusViewData.Concrete, got %s instead at position: %d of %d",
status == null ? "<null>" : status.getClass().getSimpleName(),
position,
statuses.size() - 1
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;
}
StatusViewData updatedStatus = new StatusViewData.Builder((StatusViewData.Concrete) status)
.setCollapsed(isCollapsed)
.createStatusViewData();
statuses.setPairedItem(position, updatedStatus);
updateAdapter();
}
@Override
public void onViewMedia(int position, int attachmentIndex, @Nullable View view) {
Status status = statuses.get(position).asRightOrNull();
if (status == null) return;
super.viewMedia(attachmentIndex, status, view);
}
@Override
public void onViewThread(int position) {
super.viewThread(statuses.get(position).asRight());
}
@Override
public void onViewTag(String tag) {
if (kind == Kind.TAG && hashtagOrId.equals(tag)) {
// If already viewing a tag page, then ignore any request to view that tag again.
return;
}
super.viewTag(tag);
}
@Override
public void onViewAccount(String id) {
Account activity redesign (#662) * Refactor-all-the-things version of the fix for issue #573 * Migrate SpanUtils to kotlin because why not * Minimal fix for issue #573 * Add tests for compose spanning * Clean up code suggestions * Make FakeSpannable.getSpans implementation less awkward * Add secondary validation pass for urls * Address code review feedback * Fixup type filtering in FakeSpannable again * Make all mentions in compose activity use the default link color * new layout for AccountActivity * fix the light theme * convert AccountActivity to Kotlin * introduce AccountViewModel * Merge branch 'master' into account-activity-redesign # Conflicts: # app/src/main/java/com/keylesspalace/tusky/AccountActivity.java * add Bot badge to profile * parse custom emojis in usernames * add possibility to cancel follow request * add third tab on profiles * add account fields to profile * add support for moved accounts * set click listener on account moved view * fix tests * use 24dp as statusbar size * add ability to hide reblogs from followed accounts * add button to edit own account to AccountActivity * set toolbar top margin programmatically * fix crash * add shadow behind statusbar * introduce ViewExtensions to clean up code * move code out of offsetChangedListener for perf reasons * clean up stuff * add error handling * improve type safety * fix ConstraintLayout warning * remove unneeded ressources * fix event dispatching * fix crash in event handling * set correct emoji on title * improve some things * wrap follower/foillowing/status views
2018-06-18 13:26:18 +02:00
if ((kind == Kind.USER || kind == Kind.USER_WITH_REPLIES) && hashtagOrId.equals(id)) {
/* If already viewing an account page, then any requests to view that account page
* should be ignored. */
return;
}
super.viewAccount(id);
}
private void onPreferenceChanged(String key) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
switch (key) {
case "fabHide": {
hideFab = sharedPreferences.getBoolean("fabHide", false);
break;
}
case "mediaPreviewEnabled": {
boolean enabled = accountManager.getActiveAccount().getMediaPreviewEnabled();
boolean oldMediaPreviewEnabled = adapter.getMediaPreviewEnabled();
if (enabled != oldMediaPreviewEnabled) {
adapter.setMediaPreviewEnabled(enabled);
fullyRefresh();
}
break;
}
case "tabFilterHomeReplies": {
boolean filter = sharedPreferences.getBoolean("tabFilterHomeReplies", true);
boolean oldRemoveReplies = filterRemoveReplies;
filterRemoveReplies = kind == Kind.HOME && !filter;
if (adapter.getItemCount() > 1 && oldRemoveReplies != filterRemoveReplies) {
fullyRefresh();
}
break;
}
case "tabFilterHomeBoosts": {
boolean filter = sharedPreferences.getBoolean("tabFilterHomeBoosts", true);
boolean oldRemoveReblogs = filterRemoveReblogs;
filterRemoveReblogs = kind == Kind.HOME && !filter;
if (adapter.getItemCount() > 1 && oldRemoveReblogs != filterRemoveReblogs) {
fullyRefresh();
}
break;
}
case Filter.HOME:
case Filter.NOTIFICATIONS:
case Filter.THREAD:
case Filter.PUBLIC: {
if (filterContextMatchesKind(kind, Collections.singletonList(key))) {
reloadFilters(true);
}
break;
}
2017-11-30 20:12:09 +01:00
case "alwaysShowSensitiveMedia": {
//it is ok if only newly loaded statuses are affected, no need to fully refresh
alwaysShowSensitiveMedia = accountManager.getActiveAccount().getAlwaysShowSensitiveMedia();
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
break;
2017-11-30 20:12:09 +01:00
}
case "limitedBandwidthActive":
case "limitedBandwidthOnlyMobileNetwork":
case "limitedBandwidthTimelineRoading": {
updateLimitedBandwidthStatus();
break;
}
}
}
private void updateLimitedBandwidthStatus() {
reduceTimelineRoading = preferences.getBoolean("limitedBandwidthActive", false) && preferences.getBoolean("limitedBandwidthTimelineRoading", true);
checkMobileNetwork = preferences.getBoolean("limitedBandwidthOnlyMobileNetwork", true);
}
@Override
public void removeItem(int position) {
statuses.remove(position);
updateAdapter();
}
2018-06-25 14:44:29 +02:00
private void removeAllByAccountId(String accountId) {
// using iterator to safely remove items while iterating
Iterator<Either<Placeholder, Status>> iterator = statuses.iterator();
while (iterator.hasNext()) {
Status status = iterator.next().asRightOrNull();
if (status != null &&
(status.getAccount().getId().equals(accountId) || status.getActionableStatus().getAccount().getId().equals(accountId))) {
iterator.remove();
}
}
updateAdapter();
}
private void removeAllByInstance(String instance) {
// using iterator to safely remove items while iterating
Iterator<Either<Placeholder, Status>> iterator = statuses.iterator();
while (iterator.hasNext()) {
Status status = iterator.next().asRightOrNull();
if (status != null && LinkHelper.getDomain(status.getAccount().getUrl()).equals(instance)) {
iterator.remove();
}
}
updateAdapter();
}
private void onLoadMore() {
if (didLoadEverythingBottom || bottomLoading) {
return;
}
2019-03-28 21:10:38 +01:00
if (statuses.size() == 0) {
2019-03-28 21:10:38 +01:00
sendInitialRequest();
return;
}
bottomLoading = true;
Either<Placeholder, Status> last = statuses.get(statuses.size() - 1);
Placeholder placeholder;
if (last.isRight()) {
final String placeholderId = StringUtils.dec(last.asRight().getId());
placeholder = new Placeholder(placeholderId);
statuses.add(new Either.Left<>(placeholder));
} else {
placeholder = last.asLeft();
}
statuses.setPairedItem(statuses.size() - 1,
new StatusViewData.Placeholder(placeholder.getId(), true));
updateAdapter();
String bottomId = null;
final ListIterator<Either<Placeholder, Status>> iterator =
this.statuses.listIterator(this.statuses.size());
while (iterator.hasPrevious()) {
Either<Placeholder, Status> previous = iterator.previous();
if (previous.isRight()) {
bottomId = previous.asRight().getId();
break;
}
}
sendFetchTimelineRequest(bottomId, null, null, FetchEnd.BOTTOM, -1);
}
private void fullyRefresh() {
statuses.clear();
updateAdapter();
2018-06-25 18:20:45 +02:00
bottomLoading = true;
sendFetchTimelineRequest(null, null, null, FetchEnd.BOTTOM, -1);
}
private boolean actionButtonPresent() {
return kind != Kind.TAG && kind != Kind.FAVOURITES &&
getActivity() instanceof ActionButtonActivity;
}
private void jumpToTop() {
if (isAdded()) {
layoutManager.scrollToPosition(0);
recyclerView.stopScroll();
scrollListener.reset();
}
}
private Call<List<Status>> getFetchCallByTimelineType(Kind kind, String tagOrId, String fromId,
String uptoId) {
MastodonApi api = mastodonApi;
switch (kind) {
default:
case HOME:
return api.homeTimeline(fromId, uptoId, LOAD_AT_ONCE);
case PUBLIC_FEDERATED:
2017-11-03 22:17:31 +01:00
return api.publicTimeline(null, fromId, uptoId, LOAD_AT_ONCE);
case PUBLIC_LOCAL:
2017-11-03 22:17:31 +01:00
return api.publicTimeline(true, fromId, uptoId, LOAD_AT_ONCE);
case TAG:
2017-11-03 22:17:31 +01:00
return api.hashtagTimeline(tagOrId, null, fromId, uptoId, LOAD_AT_ONCE);
case USER:
return api.accountStatuses(tagOrId, fromId, uptoId, LOAD_AT_ONCE, true, null, null);
case USER_PINNED:
return api.accountStatuses(tagOrId, fromId, uptoId, LOAD_AT_ONCE, null, null, true);
Account activity redesign (#662) * Refactor-all-the-things version of the fix for issue #573 * Migrate SpanUtils to kotlin because why not * Minimal fix for issue #573 * Add tests for compose spanning * Clean up code suggestions * Make FakeSpannable.getSpans implementation less awkward * Add secondary validation pass for urls * Address code review feedback * Fixup type filtering in FakeSpannable again * Make all mentions in compose activity use the default link color * new layout for AccountActivity * fix the light theme * convert AccountActivity to Kotlin * introduce AccountViewModel * Merge branch 'master' into account-activity-redesign # Conflicts: # app/src/main/java/com/keylesspalace/tusky/AccountActivity.java * add Bot badge to profile * parse custom emojis in usernames * add possibility to cancel follow request * add third tab on profiles * add account fields to profile * add support for moved accounts * set click listener on account moved view * fix tests * use 24dp as statusbar size * add ability to hide reblogs from followed accounts * add button to edit own account to AccountActivity * set toolbar top margin programmatically * fix crash * add shadow behind statusbar * introduce ViewExtensions to clean up code * move code out of offsetChangedListener for perf reasons * clean up stuff * add error handling * improve type safety * fix ConstraintLayout warning * remove unneeded ressources * fix event dispatching * fix crash in event handling * set correct emoji on title * improve some things * wrap follower/foillowing/status views
2018-06-18 13:26:18 +02:00
case USER_WITH_REPLIES:
return api.accountStatuses(tagOrId, fromId, uptoId, LOAD_AT_ONCE, null, null, null);
case FAVOURITES:
2017-11-03 22:17:31 +01:00
return api.favourites(fromId, uptoId, LOAD_AT_ONCE);
2018-01-06 19:01:37 +01:00
case LIST:
return api.listTimeline(tagOrId, fromId, uptoId, LOAD_AT_ONCE);
}
}
private void sendFetchTimelineRequest(@Nullable String maxId, @Nullable String sinceId,
@Nullable String sinceIdMinusOne,
2017-11-03 22:17:31 +01:00
final FetchEnd fetchEnd, final int pos) {
if (isAdded() && (fetchEnd == FetchEnd.TOP || fetchEnd == FetchEnd.BOTTOM && maxId == null && progressBar.getVisibility() != View.VISIBLE) && !isSwipeToRefreshEnabled)
topProgressBar.show();
if (kind == Kind.HOME) {
TimelineRequestMode mode;
// allow getting old statuses/fallbacks for network only for for bottom loading
if (fetchEnd == FetchEnd.BOTTOM) {
mode = TimelineRequestMode.ANY;
} else {
mode = TimelineRequestMode.NETWORK;
}
timelineRepo.getStatuses(maxId, sinceId, sinceIdMinusOne, LOAD_AT_ONCE, mode)
.observeOn(AndroidSchedulers.mainThread())
.as(autoDisposable(from(this, Lifecycle.Event.ON_DESTROY)))
.subscribe(
(result) -> onFetchTimelineSuccess(result, fetchEnd, pos),
(err) -> onFetchTimelineFailure(new Exception(err), fetchEnd, pos)
);
} else {
Callback<List<Status>> callback = new Callback<List<Status>>() {
@Override
public void onResponse(@NonNull Call<List<Status>> call, @NonNull Response<List<Status>> response) {
if (response.isSuccessful()) {
onFetchTimelineSuccess(liftStatusList(response.body()), fetchEnd, pos);
} else {
onFetchTimelineFailure(new Exception(response.message()), fetchEnd, pos);
}
}
@Override
public void onFailure(@NonNull Call<List<Status>> call, @NonNull Throwable t) {
onFetchTimelineFailure((Exception) t, fetchEnd, pos);
}
};
Call<List<Status>> listCall = getFetchCallByTimelineType(kind, hashtagOrId, maxId, sinceId);
callList.add(listCall);
listCall.enqueue(callback);
}
}
private void onFetchTimelineSuccess(List<Either<Placeholder, Status>> statuses,
2017-11-03 22:17:31 +01:00
FetchEnd fetchEnd, int pos) {
// We filled the hole (or reached the end) if the server returned less statuses than we
// we asked for.
2017-11-03 22:17:31 +01:00
boolean fullFetch = statuses.size() >= LOAD_AT_ONCE;
filterStatuses(statuses);
switch (fetchEnd) {
case TOP: {
updateStatuses(statuses, fullFetch);
2017-11-03 22:17:31 +01:00
break;
}
case MIDDLE: {
replacePlaceholderWithStatuses(statuses, fullFetch, pos);
break;
}
case BOTTOM: {
if (!this.statuses.isEmpty()
&& !this.statuses.get(this.statuses.size() - 1).isRight()) {
this.statuses.remove(this.statuses.size() - 1);
updateAdapter();
}
if (!statuses.isEmpty() && !statuses.get(statuses.size() - 1).isRight()) {
// Removing placeholder if it's the last one from the cache
statuses.remove(statuses.size() - 1);
}
int oldSize = this.statuses.size();
if (this.statuses.size() > 1) {
addItems(statuses);
} else {
updateStatuses(statuses, fullFetch);
}
if (this.statuses.size() == oldSize) {
// This may be a brittle check but seems like it works
// Can we check it using headers somehow? Do all server support them?
didLoadEverythingBottom = true;
}
break;
}
}
if (isAdded()) {
topProgressBar.hide();
updateBottomLoadingState(fetchEnd);
progressBar.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
swipeRefreshLayout.setEnabled(true);
if (this.statuses.size() == 0) {
this.showNothing();
} else {
this.statusView.setVisibility(View.GONE);
}
}
}
2017-11-03 22:17:31 +01:00
private void onFetchTimelineFailure(Exception exception, FetchEnd fetchEnd, int position) {
if (isAdded()) {
2018-07-08 10:16:19 +02:00
swipeRefreshLayout.setRefreshing(false);
topProgressBar.hide();
2018-07-08 10:16:19 +02:00
if (fetchEnd == FetchEnd.MIDDLE && !statuses.get(position).isRight()) {
Placeholder placeholder = statuses.get(position).asLeftOrNull();
2018-07-08 10:16:19 +02:00
StatusViewData newViewData;
if (placeholder == null) {
Status above = statuses.get(position - 1).asRight();
String newId = StringUtils.dec(above.getId());
placeholder = new Placeholder(newId);
2018-07-08 10:16:19 +02:00
}
newViewData = new StatusViewData.Placeholder(placeholder.getId(), false);
2018-07-08 10:16:19 +02:00
statuses.setPairedItem(position, newViewData);
updateAdapter();
} else if (this.statuses.isEmpty()) {
swipeRefreshLayout.setEnabled(false);
this.statusView.setVisibility(View.VISIBLE);
if (exception instanceof IOException) {
this.statusView.setup(R.drawable.elephant_offline, R.string.error_network, __ -> {
this.progressBar.setVisibility(View.VISIBLE);
this.onRefresh();
return Unit.INSTANCE;
});
} else {
this.statusView.setup(R.drawable.elephant_error, R.string.error_generic, __ -> {
this.progressBar.setVisibility(View.VISIBLE);
this.onRefresh();
return Unit.INSTANCE;
});
}
}
2017-11-03 22:17:31 +01:00
2018-07-08 10:16:19 +02:00
Log.e(TAG, "Fetch Failure: " + exception.getMessage());
updateBottomLoadingState(fetchEnd);
2018-07-08 10:16:19 +02:00
progressBar.setVisibility(View.GONE);
}
}
private void updateBottomLoadingState(FetchEnd fetchEnd) {
switch (fetchEnd) {
case BOTTOM: {
bottomLoading = false;
break;
}
}
}
private void filterStatuses(List<Either<Placeholder, Status>> statuses) {
Iterator<Either<Placeholder, Status>> it = statuses.iterator();
while (it.hasNext()) {
Status status = it.next().asRightOrNull();
if (status != null
&& ((status.getInReplyToId() != null && filterRemoveReplies)
|| (status.getReblog() != null && filterRemoveReblogs)
|| shouldFilterStatus(status))) {
it.remove();
}
}
}
private void updateStatuses(List<Either<Placeholder, Status>> newStatuses, boolean fullFetch) {
if (ListUtils.isEmpty(newStatuses)) {
updateAdapter();
return;
}
if (statuses.isEmpty()) {
statuses.addAll(newStatuses);
} else {
Either<Placeholder, Status> lastOfNew = newStatuses.get(newStatuses.size() - 1);
int index = statuses.indexOf(lastOfNew);
2017-11-03 22:17:31 +01:00
if (index >= 0) {
statuses.subList(0, index).clear();
}
int newIndex = newStatuses.indexOf(statuses.get(0));
if (newIndex == -1) {
if (index == -1 && fullFetch) {
String placeholderId = StringUtils.inc(
CollectionsKt.last(newStatuses, Either::isRight).asRight().getId());
newStatuses.add(new Either.Left<>(new Placeholder(placeholderId)));
2017-11-03 22:17:31 +01:00
}
statuses.addAll(0, newStatuses);
} else {
statuses.addAll(0, newStatuses.subList(0, newIndex));
}
}
// Remove all consecutive placeholders
removeConsecutivePlaceholders();
updateAdapter();
}
private void removeConsecutivePlaceholders() {
for (int i = 0; i < statuses.size() - 1; i++) {
if (statuses.get(i).isLeft() && statuses.get(i + 1).isLeft()) {
statuses.remove(i);
}
}
}
private void addItems(List<Either<Placeholder, Status>> newStatuses) {
if (ListUtils.isEmpty(newStatuses)) {
return;
}
Either<Placeholder, Status> last = null;
for (int i = statuses.size() - 1; i >= 0; i--) {
if (statuses.get(i).isRight()) {
last = statuses.get(i);
break;
}
}
// I was about to replace findStatus with indexOf but it is incorrect to compare value
// types by ID anyway and we should change equals() for Status, I think, so this makes sense
if (last != null && !newStatuses.contains(last)) {
statuses.addAll(newStatuses);
removeConsecutivePlaceholders();
updateAdapter();
}
}
2018-12-19 08:05:51 +01:00
private void addStatus(Either<Placeholder, Status> item) {
if (item.isRight()) {
Status status = item.asRight();
if (!((status.getInReplyToId() != null && filterRemoveReplies)
|| (status.getReblog() != null && filterRemoveReblogs)
|| shouldFilterStatus(status))) {
if (findStatusOrReblogPositionById(status.getId()) < 0) {
statuses.add(0, item);
updateAdapter();
timelineRepo.addSingleStatusToDb(status);
}
}
} else {
statuses.add(0, item);
updateAdapter();
}
}
/**
* For certain requests we don't want to see placeholders, they will be removed some other way
*/
private void clearPlaceholdersForResponse(List<Either<Placeholder, Status>> statuses) {
CollectionsKt.removeAll(statuses, Either::isLeft);
}
private void replacePlaceholderWithStatuses(List<Either<Placeholder, Status>> newStatuses,
boolean fullFetch, int pos) {
Either<Placeholder, Status> placeholder = statuses.get(pos);
if (placeholder.isLeft()) {
2017-11-03 22:17:31 +01:00
statuses.remove(pos);
}
if (ListUtils.isEmpty(newStatuses)) {
updateAdapter();
2017-11-03 22:17:31 +01:00
return;
}
if (fullFetch) {
newStatuses.add(placeholder);
2017-11-03 22:17:31 +01:00
}
statuses.addAll(pos, newStatuses);
removeConsecutivePlaceholders();
2017-11-03 22:17:31 +01:00
updateAdapter();
2017-11-03 22:17:31 +01:00
}
private int findStatusOrReblogPositionById(@NonNull String statusId) {
for (int i = 0; i < statuses.size(); i++) {
Status status = statuses.get(i).asRightOrNull();
if (status != null
&& (statusId.equals(status.getId())
|| (status.getReblog() != null
&& statusId.equals(status.getReblog().getId())))) {
return i;
}
}
return -1;
}
private final Function1<Status, Either<Placeholder, Status>> statusLifter =
Either.Right::new;
private @Nullable
Pair<StatusViewData.Concrete, Integer>
findStatusAndPosition(int position, Status status) {
StatusViewData.Concrete statusToUpdate;
int positionToUpdate;
StatusViewData someOldViewData = statuses.getPairedItem(position);
// Unlikely, but data could change between the request and response
if ((someOldViewData instanceof StatusViewData.Placeholder) ||
!((StatusViewData.Concrete) someOldViewData).getId().equals(status.getId())) {
// try to find the status we need to update
int foundPos = statuses.indexOf(new Either.Right<>(status));
if (foundPos < 0) return null; // okay, it's hopeless, give up
statusToUpdate = ((StatusViewData.Concrete)
statuses.getPairedItem(foundPos));
positionToUpdate = position;
} else {
statusToUpdate = (StatusViewData.Concrete) someOldViewData;
positionToUpdate = position;
}
return new Pair<>(statusToUpdate, positionToUpdate);
}
private void handleReblogEvent(@NonNull ReblogEvent reblogEvent) {
int pos = findStatusOrReblogPositionById(reblogEvent.getStatusId());
if (pos < 0) return;
Status status = statuses.get(pos).asRight();
setRebloggedForStatus(pos, status, reblogEvent.getReblog());
}
private void handleFavEvent(@NonNull FavoriteEvent favEvent) {
int pos = findStatusOrReblogPositionById(favEvent.getStatusId());
if (pos < 0) return;
Status status = statuses.get(pos).asRight();
setFavouriteForStatus(pos, status, favEvent.getFavourite());
}
private void handleStatusComposeEvent(@NonNull Status status) {
switch (kind) {
case HOME:
2018-12-19 08:05:51 +01:00
if (preferences.getBoolean("useHTLStream", false)){
return;
}
case PUBLIC_FEDERATED:
case PUBLIC_LOCAL:
break;
case USER:
Account activity redesign (#662) * Refactor-all-the-things version of the fix for issue #573 * Migrate SpanUtils to kotlin because why not * Minimal fix for issue #573 * Add tests for compose spanning * Clean up code suggestions * Make FakeSpannable.getSpans implementation less awkward * Add secondary validation pass for urls * Address code review feedback * Fixup type filtering in FakeSpannable again * Make all mentions in compose activity use the default link color * new layout for AccountActivity * fix the light theme * convert AccountActivity to Kotlin * introduce AccountViewModel * Merge branch 'master' into account-activity-redesign # Conflicts: # app/src/main/java/com/keylesspalace/tusky/AccountActivity.java * add Bot badge to profile * parse custom emojis in usernames * add possibility to cancel follow request * add third tab on profiles * add account fields to profile * add support for moved accounts * set click listener on account moved view * fix tests * use 24dp as statusbar size * add ability to hide reblogs from followed accounts * add button to edit own account to AccountActivity * set toolbar top margin programmatically * fix crash * add shadow behind statusbar * introduce ViewExtensions to clean up code * move code out of offsetChangedListener for perf reasons * clean up stuff * add error handling * improve type safety * fix ConstraintLayout warning * remove unneeded ressources * fix event dispatching * fix crash in event handling * set correct emoji on title * improve some things * wrap follower/foillowing/status views
2018-06-18 13:26:18 +02:00
case USER_WITH_REPLIES:
if (status.getAccount().getId().equals(hashtagOrId)) {
break;
} else {
return;
}
case TAG:
case FAVOURITES:
case LIST:
return;
}
boolean reloadTimeline = true;
if (reduceTimelineRoading) {
reloadTimeline = false;
Activity activity = getActivity();
if (checkMobileNetwork && activity != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info != null && info.getType() == ConnectivityManager.TYPE_WIFI) {
reloadTimeline = true;
}
}
}
if (reloadTimeline) {
onRefresh();
}
}
2018-12-19 08:05:51 +01:00
private void handleStreamUpdateEvent(StreamUpdateEvent event) {
Status status = event.getStatus();
if (event.getFirst() && statuses.get(0).isRight()) {
Placeholder placeholder = new Placeholder(statuses.get(0).asRight().getId() + 1);
updateStatuses(Arrays.asList(new Either.Right<>(status), new Either.Left<>(placeholder)), false);
} else {
addStatus(new Either.Right<>(status));
}
}
private List<Either<Placeholder, Status>> liftStatusList(List<Status> list) {
return CollectionsKt.map(list, statusLifter);
}
private void updateAdapter() {
differ.submitList(statuses.getPairedCopy());
}
private final ListUpdateCallback listUpdateCallback = new ListUpdateCallback() {
@Override
public void onInserted(int position, int count) {
if (isAdded()) {
2018-07-08 10:16:19 +02:00
adapter.notifyItemRangeInserted(position, count);
Context context = getContext();
2018-12-19 08:05:51 +01:00
if (position == 0 && context != null && layoutManager.findFirstVisibleItemPosition() == 0) {
if (count == 1) {
jumpToTop();
} else if (isSwipeToRefreshEnabled) {
recyclerView.scrollBy(0, Utils.dpToPx(context, -30));
2018-12-19 08:05:51 +01:00
} else {
recyclerView.scrollToPosition(0);
2018-12-19 08:05:51 +01:00
}
2018-07-08 10:16:19 +02:00
}
}
}
@Override
public void onRemoved(int position, int count) {
adapter.notifyItemRangeRemoved(position, count);
}
@Override
public void onMoved(int fromPosition, int toPosition) {
adapter.notifyItemMoved(fromPosition, toPosition);
}
@Override
public void onChanged(int position, int count, Object payload) {
adapter.notifyItemRangeChanged(position, count, payload);
}
};
private final AsyncListDiffer<StatusViewData>
differ = new AsyncListDiffer<>(listUpdateCallback,
new AsyncDifferConfig.Builder<>(diffCallback).build());
private final TimelineAdapter.AdapterDataSource<StatusViewData> dataSource =
new TimelineAdapter.AdapterDataSource<StatusViewData>() {
@Override
public int getItemCount() {
return differ.getCurrentList().size();
}
@Override
public StatusViewData getItemAt(int pos) {
return differ.getCurrentList().get(pos);
}
};
private static final DiffUtil.ItemCallback<StatusViewData> diffCallback
= new DiffUtil.ItemCallback<StatusViewData>() {
@Override
public boolean areItemsTheSame(StatusViewData oldItem, StatusViewData newItem) {
return oldItem.getViewDataId() == newItem.getViewDataId();
}
@Override
public boolean areContentsTheSame(StatusViewData oldItem, @NonNull StatusViewData newItem) {
return false; //Items are different always. It allows to refresh timestamp on every view holder update
}
@Nullable
@Override
public Object getChangePayload(@NonNull StatusViewData oldItem, @NonNull StatusViewData newItem) {
if (oldItem.deepEquals(newItem)) {
//If items are equal - update timestamp only
return Collections.singletonList(StatusBaseViewHolder.Key.KEY_CREATED);
} else
// If items are different - update a whole view holder
return null;
}
};
@Override
public void onResume() {
super.onResume();
startUpdateTimestamp();
}
/**
* Start to update adapter every minute to refresh timestamp
* If setting absoluteTimeView is false
* Auto dispose observable on pause
*/
private void startUpdateTimestamp() {
boolean useAbsoluteTime = preferences.getBoolean("absoluteTimeView", false);
if (!useAbsoluteTime) {
Observable.interval(1, TimeUnit.MINUTES)
.observeOn(AndroidSchedulers.mainThread())
.as(autoDisposable(from(this, Lifecycle.Event.ON_PAUSE)))
.subscribe(
interval -> updateAdapter()
);
}
}
@Override
public void onReselect() {
jumpToTop();
}
@Override
public void refreshContent() {
if (isAdded())
onRefresh();
else
isNeedRefresh = true;
}
}