-
Notifications
You must be signed in to change notification settings - Fork 257
/
Copy pathReadArticleActivity.java
1368 lines (1086 loc) · 47.6 KB
/
ReadArticleActivity.java
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package fr.gaulupeau.apps.Poche.ui;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.HttpAuthHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.di72nn.stuff.wallabag.apiwrapper.WallabagService;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.greenrobot.greendao.query.QueryBuilder;
import fr.gaulupeau.apps.InThePoche.BuildConfig;
import fr.gaulupeau.apps.Poche.events.ArticlesChangedEvent;
import fr.gaulupeau.apps.Poche.events.FeedsChangedEvent;
import fr.gaulupeau.apps.Poche.network.ImageCacheUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import fr.gaulupeau.apps.InThePoche.R;
import fr.gaulupeau.apps.Poche.App;
import fr.gaulupeau.apps.Poche.data.DbConnection;
import fr.gaulupeau.apps.Poche.data.OperationsHelper;
import fr.gaulupeau.apps.Poche.data.Settings;
import fr.gaulupeau.apps.Poche.data.dao.ArticleDao;
import fr.gaulupeau.apps.Poche.data.dao.DaoSession;
import fr.gaulupeau.apps.Poche.data.dao.entities.Article;
import fr.gaulupeau.apps.Poche.service.ServiceHelper;
import fr.gaulupeau.apps.Poche.tts.TtsFragment;
public class ReadArticleActivity extends BaseActionBarActivity {
public static final String EXTRA_ID = "ReadArticleActivity.id";
public static final String EXTRA_LIST_ARCHIVED = "ReadArticleActivity.archived";
public static final String EXTRA_LIST_FAVORITES = "ReadArticleActivity.favorites";
private static final String TAG = ReadArticleActivity.class.getSimpleName();
private static final String TAG_TTS_FRAGMENT = "ttsFragment";
private static final EnumSet<ArticlesChangedEvent.ChangeType> CHANGE_SET_ACTIONS = EnumSet.of(
ArticlesChangedEvent.ChangeType.FAVORITED,
ArticlesChangedEvent.ChangeType.UNFAVORITED,
ArticlesChangedEvent.ChangeType.ARCHIVED,
ArticlesChangedEvent.ChangeType.UNARCHIVED);
private static final EnumSet<ArticlesChangedEvent.ChangeType> CHANGE_SET_CONTENT = EnumSet.of(
ArticlesChangedEvent.ChangeType.CONTENT_CHANGED,
ArticlesChangedEvent.ChangeType.TITLE_CHANGED,
ArticlesChangedEvent.ChangeType.DOMAIN_CHANGED,
ArticlesChangedEvent.ChangeType.PUBLISHED_AT_CHANGED,
ArticlesChangedEvent.ChangeType.AUTHORS_CHANGED,
ArticlesChangedEvent.ChangeType.URL_CHANGED,
ArticlesChangedEvent.ChangeType.ESTIMATED_READING_TIME_CHANGED,
ArticlesChangedEvent.ChangeType.FETCHED_IMAGES_CHANGED);
private static final EnumSet<ArticlesChangedEvent.ChangeType> CHANGE_SET_PREV_NEXT = EnumSet.of(
ArticlesChangedEvent.ChangeType.UNSPECIFIED,
ArticlesChangedEvent.ChangeType.ADDED,
ArticlesChangedEvent.ChangeType.DELETED,
ArticlesChangedEvent.ChangeType.ARCHIVED,
ArticlesChangedEvent.ChangeType.UNARCHIVED,
ArticlesChangedEvent.ChangeType.FAVORITED,
ArticlesChangedEvent.ChangeType.UNFAVORITED,
ArticlesChangedEvent.ChangeType.CREATED_DATE_CHANGED);
private Boolean contextFavorites;
private Boolean contextArchived;
private Settings settings;
private ArticleDao articleDao;
private int fontSize;
private boolean volumeButtonsScrolling;
private boolean tapToScroll;
private boolean disableTouchOptionEnabled;
private boolean disableTouch;
private int disableTouchKeyCode;
private float screenScrollingPercent;
private boolean smoothScrolling;
private int scrolledOverBottom;
private boolean swipeArticles;
private ScrollView scrollView;
private View scrollViewLastChild;
private WebView webViewContent;
private TextView loadingPlaceholder;
private LinearLayout bottomTools;
private View hrBar;
private TtsFragment ttsFragment;
private Article article;
private String articleTitle;
private String articleDomain;
private String articleUrl;
private String articleLanguage;
private Double articleProgress;
private Long previousArticleID;
private Long nextArticleID;
private int webViewHeightBeforeUpdate;
private Runnable positionRestorationRunnable;
private boolean isResumed;
private boolean onPageFinishedCallPostponedUntilResume;
private boolean loadingFinished;
public void onCreate(Bundle savedInstanceState) {
settings = App.getInstance().getSettings();
if(settings.isFullscreenArticleView()) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
);
ActionBar actionBar = super.getSupportActionBar();
if(actionBar != null) actionBar.hide();
}
if(settings.isKeepScreenOn()) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
Intent intent = getIntent();
long articleID = intent.getLongExtra(EXTRA_ID, -1);
Log.d(TAG, "onCreate() articleId: " + articleID);
if(intent.hasExtra(EXTRA_LIST_FAVORITES)) {
contextFavorites = intent.getBooleanExtra(EXTRA_LIST_FAVORITES, false);
}
if(intent.hasExtra(EXTRA_LIST_ARCHIVED)) {
contextArchived = intent.getBooleanExtra(EXTRA_LIST_ARCHIVED, false);
}
DaoSession session = DbConnection.getSession();
articleDao = session.getArticleDao();
if(!loadArticle(articleID)) {
Log.e(TAG, "onCreate: Did not find article with ID: " + articleID);
finish();
return;
}
fontSize = settings.getArticleFontSize();
volumeButtonsScrolling = settings.isVolumeButtonsScrollingEnabled();
tapToScroll = settings.isTapToScrollEnabled();
disableTouchOptionEnabled = settings.isDisableTouchEnabled();
disableTouch = settings.isDisableTouchLastState();
disableTouchKeyCode = settings.getDisableTouchKeyCode();
screenScrollingPercent = settings.getScreenScrollingPercent();
smoothScrolling = settings.isScreenScrollingSmooth();
scrolledOverBottom = settings.getScrolledOverBottom();
swipeArticles = settings.getSwipeArticles();
setTitle(articleTitle);
// article is loaded - update menu
invalidateOptionsMenu();
scrollView = (ScrollView)findViewById(R.id.scroll);
scrollViewLastChild = scrollView.getChildAt(scrollView.getChildCount() - 1);
webViewContent = (WebView)findViewById(R.id.webViewContent);
loadingPlaceholder = (TextView)findViewById(R.id.tv_loading_article);
bottomTools = (LinearLayout)findViewById(R.id.bottomTools);
hrBar = findViewById(R.id.view1);
initWebView();
if(ttsFragment != null) {
// is it ever executed?
ttsFragment.onDocumentLoadStart(articleDomain, articleTitle, articleLanguage);
}
loadArticleToWebView();
initButtons();
if(settings.isTtsVisible() && ttsFragment == null) {
ttsFragment = (TtsFragment)getSupportFragmentManager()
.findFragmentByTag(TAG_TTS_FRAGMENT);
if(ttsFragment == null) {
toggleTTS(false);
}
}
if(disableTouch) {
showDisableTouchToast();
}
EventBus.getDefault().register(this);
}
@Override
public void onResume() {
super.onResume();
isResumed = true;
if(onPageFinishedCallPostponedUntilResume) {
onPageFinishedCallPostponedUntilResume = false;
onPageFinished();
}
}
@Override
public void onPause() {
super.onPause();
isResumed = false;
}
@Override
public void onStop() {
if(loadingFinished && article != null) {
cancelPositionRestoration();
OperationsHelper.setArticleProgress(this, article.getArticleId(), getReadingPosition());
}
super.onStop();
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
Log.d(TAG, "onCreateOptionsMenu() started");
getMenuInflater().inflate(R.menu.option_article, menu);
if(article != null) {
boolean unread = article.getArchive() != null && !article.getArchive();
menu.findItem(R.id.menuArticleMarkAsRead).setVisible(unread);
menu.findItem(R.id.menuArticleMarkAsUnread).setVisible(!unread);
boolean favorite = article.getFavorite() != null && article.getFavorite();
menu.findItem(R.id.menuArticleFavorite).setVisible(!favorite);
menu.findItem(R.id.menuArticleUnfavorite).setVisible(favorite);
}
menu.findItem(R.id.menuTTS).setChecked(ttsFragment != null);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menuArticleMarkAsRead:
case R.id.menuArticleMarkAsUnread:
markAsReadAndClose();
break;
case R.id.menuArticleFavorite:
case R.id.menuArticleUnfavorite:
toggleFavorite();
break;
case R.id.menuShare:
shareArticle();
break;
case R.id.menuChangeTitle:
showChangeTitleDialog();
break;
case R.id.menuManageTags:
manageTags();
break;
case R.id.menuDelete:
deleteArticle();
break;
case R.id.menuOpenOriginal:
openOriginal();
break;
case R.id.menuCopyOriginalURL:
copyURLToClipboard();
break;
case R.id.menuDownloadAsFile:
showDownloadFileDialog();
break;
case R.id.menuIncreaseFontSize:
changeFontSize(true);
break;
case R.id.menuDecreaseFontSize:
changeFontSize(false);
break;
case R.id.menuTTS:
toggleTTS(true);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int code = event.getKeyCode();
boolean triggerAction;
if (code == KeyEvent.KEYCODE_PAGE_UP || code == KeyEvent.KEYCODE_PAGE_DOWN) {
triggerAction = (event.getAction() == KeyEvent.ACTION_UP);
} else {
triggerAction = (event.getAction() == KeyEvent.ACTION_DOWN);
}
if (triggerAction) {
if(code == disableTouchKeyCode && (disableTouch || disableTouchOptionEnabled)) {
disableTouch = !disableTouch;
settings.setDisableTouchLastState(disableTouch);
Log.d(TAG, "toggling touch screen, now disableTouch is " + disableTouch);
showDisableTouchToast();
return true;
}
boolean scroll = false;
boolean up = false;
switch (code) {
case KeyEvent.KEYCODE_PAGE_UP:
case KeyEvent.KEYCODE_PAGE_DOWN:
scroll = true;
up = code == KeyEvent.KEYCODE_PAGE_UP;
break;
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
scroll = true;
up = code == KeyEvent.KEYCODE_DPAD_UP || code == KeyEvent.KEYCODE_DPAD_LEFT;
break;
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (volumeButtonsScrolling) {
scroll = true;
up = code == KeyEvent.KEYCODE_VOLUME_UP;
}
break;
}
if (scroll) {
scroll(up, screenScrollingPercent, smoothScrolling, true);
return true;
}
}
return super.dispatchKeyEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return disableTouch || super.dispatchTouchEvent(ev);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onArticlesChangedEvent(ArticlesChangedEvent event) {
Log.d(TAG, "onArticlesChangedEvent() started");
boolean updatePrevNext = false;
if(!Collections.disjoint(event.getInvalidateAllChanges(), CHANGE_SET_PREV_NEXT)) {
updatePrevNext = true;
} else {
EnumSet<ArticlesChangedEvent.ChangeType> changes;
if(contextArchived != null) {
changes = contextArchived ? event.getArchiveFeedChanges() : event.getMainFeedChanges();
} else if(contextFavorites != null && contextFavorites) {
changes = event.getFavoriteFeedChanges();
} else {
changes = EnumSet.copyOf(event.getMainFeedChanges());
changes.addAll(event.getArchiveFeedChanges());
changes.addAll(event.getFavoriteFeedChanges());
}
if(!Collections.disjoint(changes, CHANGE_SET_PREV_NEXT)) {
updatePrevNext = true;
}
}
if(updatePrevNext) {
Log.d(TAG, "onArticleChangedEvent() prev/next buttons changed");
updatePrevNextButtons();
}
EnumSet<ArticlesChangedEvent.ChangeType> changes = event.getArticleChanges(article);
if(changes == null) return;
Log.d(TAG, "onArticlesChangedEvent() changes: " + changes);
boolean updateActions;
boolean updateContent;
boolean updateTitle;
boolean updateURL;
if(changes.contains(FeedsChangedEvent.ChangeType.UNSPECIFIED)) {
updateActions = true;
updateContent = true;
updateTitle = true;
updateURL = true;
} else {
updateActions = !Collections.disjoint(changes, CHANGE_SET_ACTIONS);
updateContent = !Collections.disjoint(changes, CHANGE_SET_CONTENT);
updateTitle = changes.contains(FeedsChangedEvent.ChangeType.TITLE_CHANGED);
updateURL = changes.contains(FeedsChangedEvent.ChangeType.URL_CHANGED);
}
if(updateActions) {
Log.d(TAG, "onArticleChangedEvent() actions changed");
updateMarkAsReadButtonView();
invalidateOptionsMenu();
}
if(updateTitle) {
Log.d(TAG, "onArticleChangedEvent() title changed");
articleTitle = article.getTitle();
setTitle(articleTitle);
}
if(updateURL) {
Log.d(TAG, "onArticleChangedEvent() URL changed");
articleUrl = article.getUrl();
}
if(updateContent) {
Log.d(TAG, "onArticleChangedEvent() content changed");
// prepareToRestorePosition(true);
loadArticleToWebView();
// restorePositionAfterUpdate();
}
}
private void showDisableTouchToast() {
Toast.makeText(this, disableTouch
? R.string.message_disableTouch_inputDisabled
: R.string.message_disableTouch_inputEnabled,
Toast.LENGTH_SHORT).show();
}
@SuppressLint("SetJavaScriptEnabled")
private void initWebView() {
webViewContent.getSettings().setJavaScriptEnabled(true);
webViewContent.setWebChromeClient(new WebChromeClient() {
private View customView;
@Override
public boolean onConsoleMessage(ConsoleMessage cm) {
boolean result = false;
if(ttsFragment != null) {
result = ttsFragment.onWebViewConsoleMessage(cm);
}
if(!result) {
Log.d("WebView.onCM", String.format("%s @ %d: %s", cm.message(),
cm.lineNumber(), cm.sourceId()));
}
return true;
}
//Necessary for enabling watching youtube videos in fullscreen
public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback) {
customView = paramView;
//Hide action bar and bottom buttons while in fullscreen
ReadArticleActivity.this.getSupportActionBar().hide();
LinearLayout bottom = findViewById(R.id.bottomTools);
bottom.setVisibility(View.GONE);
FrameLayout.LayoutParams fullscreen = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
((FrameLayout) ReadArticleActivity.this.getWindow().getDecorView())
.addView(customView, fullscreen);
}
//Necessary for enabling watching youtube videos in fullscreen
public void onHideCustomView() {
//Show action bar and bottom buttons when leaving fullscreen
ReadArticleActivity.this.getSupportActionBar().show();
LinearLayout bottom = findViewById(R.id.bottomTools);
bottom.setVisibility(View.VISIBLE);
((FrameLayout) ReadArticleActivity.this.getWindow().getDecorView())
.removeView(customView);
}
});
webViewContent.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
ReadArticleActivity.this.onPageFinished();
super.onPageFinished(view, url);
}
@SuppressWarnings("deprecation") // can't use newer method until API 21
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
// If we try to open current URL, do not propose to save it, directly open browser
if(url.equals(articleUrl)) {
openURL(url);
} else {
handleUrlClicked(url);
}
return true; // always override URL loading
}
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler,
String host, String realm) {
Log.d(TAG, "onReceivedHttpAuthRequest() host: " + host + ", realm: " + realm);
if(!TextUtils.isEmpty(host)) {
String httpAuthHost = settings.getUrl();
try {
httpAuthHost = new URL(httpAuthHost).getHost();
} catch(Exception ignored) {}
if(host.contains(httpAuthHost)) {
Log.d(TAG, "onReceivedHttpAuthRequest() host match");
handler.proceed(settings.getHttpAuthUsername(), settings.getHttpAuthPassword());
return;
}
}
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
});
if(fontSize != 100) setFontSize(webViewContent, fontSize);
GestureDetector.SimpleOnGestureListener gestureListener
= new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// note: e1 - previous event, e2 - current event
// velocity* - velocity in pixels per second
if(!swipeArticles) return false;
if(e1 == null || e2 == null) return false;
if(e1.getPointerCount() > 1 || e2.getPointerCount() > 1) return false;
// if(Math.abs(e1.getY() - e2.getY()) > 150) {
// Log.d("FLING", "not a horizontal fling (distance)");
// return false; // not a horizontal move (distance)
// }
if(Math.abs(velocityX) < 80) {
Log.v("FLING", "too slow");
return false; // too slow
}
if(Math.abs(velocityX / velocityY) < 3) {
Log.v("FLING", "not a horizontal fling");
return false; // not a horizontal fling
}
float diff = e1.getX() - e2.getX();
if(Math.abs(diff) < 80) { // configurable
Log.v("FLING", "too small distance");
return false; // too small distance
}
if(diff > 0) { // right-to-left: next
Log.v("FLING", "right-to-left: next");
openNextArticle();
} else { // left-to-right: prev
Log.v("FLING", "left-to-right: prev");
openPreviousArticle();
}
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if(!tapToScroll) return false;
if(e.getPointerCount() > 1) return false;
int viewHeight = scrollView.getHeight();
float y = e.getY() - scrollView.getScrollY();
if(y > viewHeight * 0.25 && y < viewHeight * 0.75) {
int viewWidth = scrollView.getWidth();
float x = e.getX();
if(x < viewWidth * 0.3) { // left part
scroll(true, screenScrollingPercent, smoothScrolling, false);
} else if(x > viewWidth * 0.7) { // right part
scroll(false, screenScrollingPercent, smoothScrolling, false);
}
}
return false;
}
};
final GestureDetector gestureDetector = new GestureDetector(this, gestureListener);
webViewContent.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
}
private void loadArticleToWebView() {
webViewContent.loadDataWithBaseURL("file:///android_asset/", getHtmlPage(),
"text/html", "utf-8", null);
}
private String getHtmlPage() {
String cssName;
boolean highContrast = false;
boolean weightedFont = false;
switch(Themes.getCurrentTheme()) {
case E_INK:
weightedFont = true;
case LIGHT_CONTRAST:
highContrast = true;
case LIGHT:
default:
cssName = "main";
break;
case DARK_CONTRAST:
highContrast = true;
case DARK:
cssName = "dark";
break;
case SOLARIZED:
cssName = "solarized";
highContrast = false;
break;
}
List<String> additionalClasses = new ArrayList<>(1);
if(highContrast) additionalClasses.add("high-contrast");
if(weightedFont) additionalClasses.add("weighted-font");
if(settings.isArticleFontSerif()) additionalClasses.add("serif-font");
if(settings.isArticleTextAlignmentJustify()) additionalClasses.add("text-align-justify");
additionalClasses.add(settings.getHandlePreformattedTextOption());
String classAttr;
if(!additionalClasses.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append(" class=\"");
for(String cl: additionalClasses) {
sb.append(cl).append(' ');
}
sb.append('"');
classAttr = sb.toString();
} else {
classAttr = "";
}
String htmlBase;
try {
htmlBase = readRawString(R.raw.webview_htmlbase);
} catch(Exception e) {
// should not happen
throw new RuntimeException("Couldn't load raw resource", e);
}
String htmlContent = getHtmlContent();
List<String> imgURLs = ImageCacheUtils.findImageUrlsInHtml(htmlContent);
if(imgURLs != null && imgURLs.size() > 0) {
String wbgURL = ImageCacheUtils.getWallabagUrl();
for(String imageURL: imgURLs) {
if(imageURL.startsWith(ImageCacheUtils.WALLABAG_RELATIVE_URL_PATH)) {
htmlContent = htmlContent.replace(imageURL, wbgURL + imageURL);
Log.d(TAG, "getHtmlPage() prefixing wallabag server URL " + wbgURL + " to the image path " + imageURL);
}
}
}
String dateAndAuthor = "";
Date publishedAt = article.getPublishedAt();
if (publishedAt != null) {
dateAndAuthor += android.text.format.DateFormat.getDateFormat(this).format(publishedAt)
+ " " + android.text.format.DateFormat.getTimeFormat(this).format(publishedAt);
}
if (!TextUtils.isEmpty(article.getAuthors())) {
dateAndAuthor += " " + article.getAuthors();
}
return String.format(htmlBase, cssName, classAttr, TextUtils.htmlEncode(articleTitle),
articleUrl, articleDomain, dateAndAuthor, htmlContent);
}
private String getHtmlContent() {
String htmlContent = article.getContent();
int estimatedReadingTime = article.getEstimatedReadingTime(settings.getReadingSpeed());
String estimatedReadingTimeString = getString(R.string.content_estimatedReadingTime,
estimatedReadingTime > 0 ? estimatedReadingTime : "< 1");
String previewPicture = "";
if(settings.isPreviewImageEnabled() && !TextUtils.isEmpty(article.getPreviewPictureURL())) {
previewPicture = "<br><img src=\"" + article.getPreviewPictureURL() + "\"/>";
}
htmlContent = estimatedReadingTimeString + previewPicture + htmlContent;
if(BuildConfig.DEBUG) Log.d(TAG, "getHtmlContent() htmlContent: " + htmlContent);
if(settings.isImageCacheEnabled()) {
Log.d(TAG, "getHtmlContent() replacing image links to cached versions in htmlContent");
htmlContent = ImageCacheUtils.replaceImagesInHtmlContent(
htmlContent, article.getArticleId().longValue());
}
return htmlContent;
}
private void initButtons() {
updateMarkAsReadButtonView();
updatePrevNextButtons();
}
private void updateMarkAsReadButtonView() {
Button buttonMarkRead = (Button)findViewById(R.id.btnMarkRead);
Button buttonMarkUnread = (Button)findViewById(R.id.btnMarkUnread);
boolean archived = article.getArchive();
buttonMarkRead.setVisibility(!archived ? View.VISIBLE: View.GONE);
buttonMarkUnread.setVisibility(archived ? View.VISIBLE: View.GONE);
OnClickListener onClickListener =
new OnClickListener() {
@Override
public void onClick(View v) {
markAsReadAndClose();
}
};
buttonMarkRead.setOnClickListener(onClickListener);
buttonMarkUnread.setOnClickListener(onClickListener);
}
private void updatePrevNextButtons() {
previousArticleID = getAdjacentArticle(true);
nextArticleID = getAdjacentArticle(false);
updatePrevNextButtonViews();
}
private void updatePrevNextButtonViews() {
ImageButton buttonGoPrevious = (ImageButton)findViewById(R.id.btnGoPrevious);
ImageButton buttonGoNext = (ImageButton)findViewById(R.id.btnGoNext);
buttonGoPrevious.setVisibility(previousArticleID == null ? View.GONE : View.VISIBLE);
buttonGoNext.setVisibility(nextArticleID == null ? View.GONE : View.VISIBLE);
buttonGoPrevious.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
openPreviousArticle();
}
});
buttonGoNext.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
openNextArticle();
}
});
}
private void loadingFinished() {
loadingFinished = true;
loadingPlaceholder.setVisibility(View.GONE);
bottomTools.setVisibility(View.VISIBLE);
hrBar.setVisibility(View.VISIBLE);
// should there be a pause between visibility change and position restoration?
restoreReadingPosition();
if(ttsFragment != null) {
ttsFragment.onDocumentLoadFinished(webViewContent, scrollView);
}
}
private void handleUrlClicked(final String url) {
Log.d(TAG, "handleUrlClicked() url: " + url);
if(TextUtils.isEmpty(url)) return;
// TODO: fancy dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
@SuppressLint("InflateParams") // it's ok to inflate with null for AlertDialog
View v = getLayoutInflater().inflate(R.layout.dialog_title_url, null);
TextView tv = (TextView)v.findViewById(R.id.tv_dialog_title_url);
tv.setText(url);
builder.setCustomTitle(v);
builder.setItems(
new CharSequence[]{
getString(R.string.d_urlAction_openInBrowser),
getString(R.string.d_urlAction_addToWallabag),
getString(R.string.d_urlAction_copyToClipboard),
getString(R.string.menuShare)
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
openURL(url);
break;
case 1:
ServiceHelper.addLink(ReadArticleActivity.this, url);
break;
case 2:
copyURLToClipboard(url);
break;
case 3:
shareArticle(null, url);
break;
}
}
});
builder.show();
}
private void openURL(String url) {
Log.d(TAG, "openURL() url: " + url);
if(TextUtils.isEmpty(url)) return;
Uri uri = Uri.parse(url);
if(uri.getScheme() == null) {
Log.i(TAG, "openURL() scheme is null, appending default scheme");
uri = Uri.parse("http://" + url);
}
Log.d(TAG, "openURL() uri: " + uri);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(intent);
} catch(ActivityNotFoundException e) {
Log.w(TAG, "openURL() failed to open URL", e);
Toast.makeText(this, R.string.message_couldNotOpenUrl, Toast.LENGTH_SHORT).show();
}
}
private void markAsReadAndClose() {
OperationsHelper.archiveArticle(this, article.getArticleId(), !article.getArchive());
finish();
}
private void toggleFavorite() {
OperationsHelper.favoriteArticle(this, article.getArticleId(), !article.getFavorite());
}
private void shareArticle() {
shareArticle(articleTitle, articleUrl);
}
private void shareArticle(String articleTitle , String articleUrl) {
String shareText = articleUrl;
if(!TextUtils.isEmpty(articleTitle)) shareText = articleTitle + " " + shareText;
if(settings.isAppendWallabagMentionEnabled()) {
shareText += getString(R.string.share_text_extra);
}
Intent send = new Intent(Intent.ACTION_SEND);
send.setType("text/plain");
if(!TextUtils.isEmpty(articleTitle)) send.putExtra(Intent.EXTRA_SUBJECT, articleTitle);
send.putExtra(Intent.EXTRA_TEXT, shareText);
startActivity(Intent.createChooser(send, getString(R.string.share_article_title)));
}
private void deleteArticle() {
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle(R.string.d_deleteArticle_title);
b.setMessage(R.string.d_deleteArticle_message);
b.setPositiveButton(R.string.positive_answer, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
OperationsHelper.deleteArticle(ReadArticleActivity.this, article.getArticleId());
finish();
}
});
b.setNegativeButton(R.string.negative_answer, null);
b.show();
}
private void showChangeTitleDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
@SuppressLint("InflateParams") // ok for dialogs
final View view = getLayoutInflater().inflate(R.layout.dialog_change_title, null);
((TextView)view.findViewById(R.id.editText_title)).setText(articleTitle);
builder.setView(view);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
TextView textView = (TextView)view.findViewById(R.id.editText_title);
changeTitle(textView.getText().toString());
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.show();
}