summaryrefslogtreecommitdiff
path: root/org.fox.ttrss/src/main/java/org/fox/ttrss/ArticlePager.java
blob: 86feeaed71ca7579457f27f3e61fe941c2e81b11 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package org.fox.ttrss;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.BadParcelableException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.snackbar.Snackbar;
import com.google.gson.JsonElement;

import org.fox.ttrss.types.Article;
import org.fox.ttrss.types.ArticleList;
import org.fox.ttrss.types.Feed;
import org.fox.ttrss.util.HeadlinesRequest;

import java.util.HashMap;

import icepick.State;

public class ArticlePager extends StateSavedFragment {

	private final String TAG = "ArticlePager";
	private PagerAdapter m_adapter;
	private HeadlinesEventListener m_listener;
	@State protected Article m_article;
	@State protected ArticleList m_articles = new ArticleList(); //m_articles = Application.getInstance().m_loadedArticles;
	private OnlineActivity m_activity;
	private String m_searchQuery = "";
	@State protected Feed m_feed;
	private SharedPreferences m_prefs;
	@State protected int m_firstId = 0;
	private boolean m_refreshInProgress;
	private boolean m_lazyLoadDisabled;

	private class PagerAdapter extends FragmentStatePagerAdapter {
		
		public PagerAdapter(FragmentManager fm) {
			super(fm);
		}

		private ArticleFragment m_currentFragment;

		// workaround for possible TransactionTooLarge exception on 8.0+
		// we don't need to save member state anyway, bridge takes care of it
		@Override
		public Parcelable saveState() {
			Bundle bundle = (Bundle) super.saveState();

			if (bundle != null)
				bundle.putParcelableArray("states", null); // Never maintain any states from the base class, just null it out

			return bundle;
		}

		@Override
		public Fragment getItem(int position) {
			try {
				Article article = m_articles.get(position);

				if (article != null) {
					ArticleFragment af = new ArticleFragment();
					af.initialize(article);

					return af;
				}
			} catch (IndexOutOfBoundsException e) {
				e.printStackTrace();
			}

			return null;
		}

		@Override
		public int getCount() {
			return m_articles.size();
		}

        public ArticleFragment getCurrentFragment() {
            return m_currentFragment;
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
			m_currentFragment = ((ArticleFragment) object);

            super.setPrimaryItem(container, position, object);
        }

	}
		
	public void initialize(Article article, Feed feed, ArticleList articles) {
		m_article = article;
		m_feed = feed;
        m_articles = articles;
	}

	public void setSearchQuery(String searchQuery) {
		m_searchQuery = searchQuery;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setRetainInstance(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {    	
		View view = inflater.inflate(R.layout.article_pager, container, false);
	
		if (savedInstanceState != null) {
			if (m_activity instanceof DetailActivity) {
				m_articles = ((DetailActivity)m_activity).m_articles;
			}
		}
		
		m_adapter = new PagerAdapter(getActivity().getSupportFragmentManager());
		
		ViewPager pager = view.findViewById(R.id.article_pager);
				
		int position = m_articles.indexOf(m_article);
		
		m_listener.onArticleSelected(m_article, false);

		pager.setAdapter(m_adapter);

		pager.setCurrentItem(position);
		pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

			}

			@Override
			public void onPageSelected(int position) {
				Log.d(TAG, "onPageSelected: " + position);

				final Article article = m_articles.get(position);

				if (article != null) {
					m_article = article;

					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							m_listener.onArticleSelected(article, false);
						}
					}, 250);

					//Log.d(TAG, "Page #" + position + "/" + m_adapter.getCount());

					if (!m_refreshInProgress && !m_lazyLoadDisabled && (m_activity.isSmallScreen() || m_activity.isPortrait()) && position >= m_adapter.getCount() - 5) {
						Log.d(TAG, "loading more articles...");

						new Handler().postDelayed(new Runnable() {
							@Override
							public void run() {
								refresh(true);
							}
						}, 100);
					}
				}
			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}
		});

		return view;
	}
	
	@SuppressWarnings({ "serial" }) 
	protected void refresh(final boolean append) {

		if (!append) {
			m_lazyLoadDisabled = false;
		}

		m_refreshInProgress = true;

		@SuppressLint("StaticFieldLeak") HeadlinesRequest req = new HeadlinesRequest(getActivity().getApplicationContext(), m_activity, m_feed, m_articles) {
			@Override
			protected void onProgressUpdate(Integer... progress) {
				m_activity.setProgress(progress[0] / progress[1] * 10000);
			}

			@Override
			protected void onPostExecute(JsonElement result) {
				if (isDetached() || !isAdded()) return;

				if (!append) {
					ViewPager pager = getView().findViewById(R.id.article_pager);
					pager.setCurrentItem(0);

					m_articles.clear();
				}

				super.onPostExecute(result);

				m_refreshInProgress = false;

				if (result != null) {

					if (m_firstIdChanged) {
						m_lazyLoadDisabled = true;
					}

					if (m_firstIdChanged && !(m_activity instanceof DetailActivity && !m_activity.isPortrait())) {
						//m_activity.toast(R.string.headlines_row_top_changed);

						Snackbar.make(getView(), R.string.headlines_row_top_changed, Snackbar.LENGTH_LONG)
								.setAction(R.string.reload, new View.OnClickListener() {
									@Override
									public void onClick(View v) {
										refresh(false);
									}
								}).show();
					}

					if (m_amountLoaded < Integer.valueOf(m_prefs.getString("headlines_request_size", "15"))) {
						m_lazyLoadDisabled = true;
					}

					ArticlePager.this.m_firstId = m_firstId;

					try {
						m_adapter.notifyDataSetChanged();
					} catch (BadParcelableException e) {
						if (getActivity() != null) {							
							getActivity().finish();
							return;
						}
					}
					
					if (m_article != null) {
						if (m_article.id == 0 || !m_articles.containsId(m_article.id)) {
							if (m_articles.size() > 0) {
								m_article = m_articles.get(0);
								m_listener.onArticleSelected(m_article, false);
							}
						}
					}

				} else {
					m_lazyLoadDisabled = true;

					if (m_lastError == ApiCommon.ApiError.LOGIN_FAILED) {
						m_activity.login(true);
					} else {
						m_activity.toast(getErrorMessage());
						//setLoadingStatus(getErrorMessage(), false);
					}	
				}
			}
		};
		
		final Feed feed = m_feed;
		
		final String sessionId = m_activity.getSessionId();
		int skip = 0;
		
		if (append) {
			// adaptive, all_articles, marked, published, unread
			String viewMode = m_activity.getViewMode();
			int numUnread = 0;
			int numAll = m_articles.size();
			
			for (Article a : m_articles) {
				if (a.unread) ++numUnread;
			}
			
			if ("marked".equals(viewMode)) {
				skip = numAll;
			} else if ("published".equals(viewMode)) {
				skip = numAll;
			} else if ("unread".equals(viewMode)) {
				skip = numUnread;					
			} else if (m_searchQuery != null && m_searchQuery.length() > 0) {
				skip = numAll;
			} else if ("adaptive".equals(viewMode)) {
				skip = numUnread > 0 ? numUnread : numAll;
			} else {
				skip = numAll;
			}
		}
		
		final int fskip = skip;
		
		req.setOffset(skip);

		HashMap<String,String> map = new HashMap<String, String>();
		map.put("op", "getHeadlines");
		map.put("sid", sessionId);
		map.put("feed_id", String.valueOf(feed.id));
		map.put("show_excerpt", "true");
		map.put("excerpt_length", String.valueOf(CommonActivity.EXCERPT_MAX_LENGTH));
		map.put("show_content", "true");
		map.put("include_attachments", "true");
		map.put("limit", m_prefs.getString("headlines_request_size", "15"));
		map.put("offset", String.valueOf(0));
		map.put("view_mode", m_activity.getViewMode());
		map.put("skip", String.valueOf(fskip));
		map.put("include_nested", "true");
		map.put("has_sandbox", "true");
		map.put("order_by", m_activity.getSortMode());

		if (feed.is_cat) map.put("is_cat", "true");

		if (m_searchQuery != null && m_searchQuery.length() != 0) {
			map.put("search", m_searchQuery);
			map.put("search_mode", "");
			map.put("match_on", "both");
		}

		if (m_firstId > 0) map.put("check_first_id", String.valueOf(m_firstId));

		if (m_activity.getApiLevel() >= 12) {
			map.put("include_header", "true");
		}

		if (m_prefs.getBoolean("enable_image_downsampling", false)) {
			if (m_prefs.getBoolean("always_downsample_images", false) || !m_activity.isWifiConnected()) {
				map.put("resize_width", String.valueOf(m_activity.getResizeWidth()));
			}
		}

        Log.d(TAG, "[AP] request more headlines, firstId=" + m_firstId);

		req.execute(map);
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);		
		
		m_listener = (HeadlinesEventListener)activity;
		m_activity = (OnlineActivity)activity;
		
		m_prefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
	}
	
	@SuppressLint("NewApi")
	@Override
	public void onResume() {
		super.onResume();

		//if (m_adapter != null) m_adapter.notifyDataSetChanged();

		m_activity.invalidateOptionsMenu();
	}

	public Article getSelectedArticle() {
		return m_article;
	}

	public void setActiveArticle(Article article) {
		if (m_article != article) {
			m_article = article;

			int position = m_articles.indexOf(m_article);

			ViewPager pager = getView().findViewById(R.id.article_pager);
		
			pager.setCurrentItem(position);
		}
	}

	public void selectArticle(boolean next) {
		if (m_article != null) {
			int position = m_articles.indexOf(m_article);
			
			if (next) 
				position++;
			else
				position--;
			
			try {
				Article tmp = m_articles.get(position);
				
				if (tmp != null) {
					setActiveArticle(tmp);
				}
				
			} catch (IndexOutOfBoundsException e) {
				// do nothing
			}
		}		
	}

	public void notifyUpdated() {
		m_adapter.notifyDataSetChanged();
	}
}