/
DetailFragment.java
2344 lines (2085 loc) · 84 KB
/
DetailFragment.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
/*
* Copyright (C) 2013-2020 Federico Iosue (federico@iosue.it)
*
* 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.feio.android.omninotes;
import static android.content.Context.CLIPBOARD_SERVICE;
import static android.content.Context.LAYOUT_INFLATER_SERVICE;
import static androidx.core.view.ViewCompat.animate;
import static it.feio.android.omninotes.BaseActivity.TRANSITION_HORIZONTAL;
import static it.feio.android.omninotes.BaseActivity.TRANSITION_VERTICAL;
import static it.feio.android.omninotes.MainActivity.FRAGMENT_DETAIL_TAG;
import static it.feio.android.omninotes.utils.ConstantsBase.ACTION_DISMISS;
import static it.feio.android.omninotes.utils.ConstantsBase.ACTION_FAB_TAKE_PHOTO;
import static it.feio.android.omninotes.utils.ConstantsBase.ACTION_MERGE;
import static it.feio.android.omninotes.utils.ConstantsBase.ACTION_NOTIFICATION_CLICK;
import static it.feio.android.omninotes.utils.ConstantsBase.ACTION_PINNED;
import static it.feio.android.omninotes.utils.ConstantsBase.ACTION_SHORTCUT;
import static it.feio.android.omninotes.utils.ConstantsBase.ACTION_SHORTCUT_WIDGET;
import static it.feio.android.omninotes.utils.ConstantsBase.ACTION_WIDGET;
import static it.feio.android.omninotes.utils.ConstantsBase.ACTION_WIDGET_SHOW_LIST;
import static it.feio.android.omninotes.utils.ConstantsBase.ACTION_WIDGET_TAKE_PHOTO;
import static it.feio.android.omninotes.utils.ConstantsBase.GALLERY_CLICKED_IMAGE;
import static it.feio.android.omninotes.utils.ConstantsBase.GALLERY_IMAGES;
import static it.feio.android.omninotes.utils.ConstantsBase.GALLERY_TITLE;
import static it.feio.android.omninotes.utils.ConstantsBase.INTENT_GOOGLE_NOW;
import static it.feio.android.omninotes.utils.ConstantsBase.INTENT_KEY;
import static it.feio.android.omninotes.utils.ConstantsBase.INTENT_NOTE;
import static it.feio.android.omninotes.utils.ConstantsBase.INTENT_WIDGET;
import static it.feio.android.omninotes.utils.ConstantsBase.MIME_TYPE_AUDIO;
import static it.feio.android.omninotes.utils.ConstantsBase.MIME_TYPE_AUDIO_EXT;
import static it.feio.android.omninotes.utils.ConstantsBase.MIME_TYPE_FILES;
import static it.feio.android.omninotes.utils.ConstantsBase.MIME_TYPE_IMAGE;
import static it.feio.android.omninotes.utils.ConstantsBase.MIME_TYPE_IMAGE_EXT;
import static it.feio.android.omninotes.utils.ConstantsBase.MIME_TYPE_SKETCH;
import static it.feio.android.omninotes.utils.ConstantsBase.MIME_TYPE_SKETCH_EXT;
import static it.feio.android.omninotes.utils.ConstantsBase.MIME_TYPE_VIDEO;
import static it.feio.android.omninotes.utils.ConstantsBase.MIME_TYPE_VIDEO_EXT;
import static it.feio.android.omninotes.utils.ConstantsBase.PREF_ATTACHMENTS_ON_BOTTOM;
import static it.feio.android.omninotes.utils.ConstantsBase.PREF_AUTO_LOCATION;
import static it.feio.android.omninotes.utils.ConstantsBase.PREF_COLORS_APP_DEFAULT;
import static it.feio.android.omninotes.utils.ConstantsBase.PREF_KEEP_CHECKED;
import static it.feio.android.omninotes.utils.ConstantsBase.PREF_KEEP_CHECKMARKS;
import static it.feio.android.omninotes.utils.ConstantsBase.PREF_PASSWORD;
import static it.feio.android.omninotes.utils.ConstantsBase.PREF_PRETTIFIED_DATES;
import static it.feio.android.omninotes.utils.ConstantsBase.PREF_WIDGET_PREFIX;
import static it.feio.android.omninotes.utils.ConstantsBase.SWIPE_MARGIN;
import static it.feio.android.omninotes.utils.ConstantsBase.SWIPE_OFFSET;
import static it.feio.android.omninotes.utils.ConstantsBase.THUMBNAIL_SIZE;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Selection;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentTransaction;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.neopixl.pixlui.components.edittext.EditText;
import com.pixplicity.easyprefs.library.Prefs;
import com.pushbullet.android.extension.MessagingExtension;
import de.greenrobot.event.EventBus;
import de.keyboardsurfer.android.widget.crouton.Style;
import it.feio.android.checklistview.exceptions.ViewNotSupportedException;
import it.feio.android.checklistview.interfaces.CheckListChangedListener;
import it.feio.android.checklistview.models.CheckListView;
import it.feio.android.checklistview.models.CheckListViewItem;
import it.feio.android.checklistview.models.ChecklistManager;
import it.feio.android.omninotes.async.AttachmentTask;
import it.feio.android.omninotes.async.bus.NotesUpdatedEvent;
import it.feio.android.omninotes.async.bus.PushbulletReplyEvent;
import it.feio.android.omninotes.async.bus.SwitchFragmentEvent;
import it.feio.android.omninotes.async.notes.NoteProcessorDelete;
import it.feio.android.omninotes.async.notes.SaveNoteTask;
import it.feio.android.omninotes.databinding.FragmentDetailBinding;
import it.feio.android.omninotes.db.DbHelper;
import it.feio.android.omninotes.exceptions.checked.UnhandledIntentException;
import it.feio.android.omninotes.helpers.AttachmentsHelper;
import it.feio.android.omninotes.helpers.IntentHelper;
import it.feio.android.omninotes.helpers.LogDelegate;
import it.feio.android.omninotes.helpers.PermissionsHelper;
import it.feio.android.omninotes.helpers.TagOpenerHelper;
import it.feio.android.omninotes.helpers.date.DateHelper;
import it.feio.android.omninotes.helpers.date.RecurrenceHelper;
import it.feio.android.omninotes.helpers.notifications.NotificationChannels.NotificationChannelNames;
import it.feio.android.omninotes.helpers.notifications.NotificationsHelper;
import it.feio.android.omninotes.models.Attachment;
import it.feio.android.omninotes.models.Category;
import it.feio.android.omninotes.models.Note;
import it.feio.android.omninotes.models.ONStyle;
import it.feio.android.omninotes.models.Tag;
import it.feio.android.omninotes.models.adapters.AttachmentAdapter;
import it.feio.android.omninotes.models.adapters.CategoryRecyclerViewAdapter;
import it.feio.android.omninotes.models.adapters.PlacesAutoCompleteAdapter;
import it.feio.android.omninotes.models.listeners.OnAttachingFileListener;
import it.feio.android.omninotes.models.listeners.OnGeoUtilResultListener;
import it.feio.android.omninotes.models.listeners.OnNoteSaved;
import it.feio.android.omninotes.models.listeners.OnReminderPickedListener;
import it.feio.android.omninotes.models.listeners.RecyclerViewItemClickSupport;
import it.feio.android.omninotes.models.views.ExpandableHeightGridView;
import it.feio.android.omninotes.utils.AlphaManager;
import it.feio.android.omninotes.utils.BitmapHelper;
import it.feio.android.omninotes.utils.ConnectionManager;
import it.feio.android.omninotes.utils.Display;
import it.feio.android.omninotes.utils.FileHelper;
import it.feio.android.omninotes.utils.FileProviderHelper;
import it.feio.android.omninotes.utils.GeocodeHelper;
import it.feio.android.omninotes.utils.IntentChecker;
import it.feio.android.omninotes.utils.KeyboardUtils;
import it.feio.android.omninotes.utils.PasswordHelper;
import it.feio.android.omninotes.utils.ReminderHelper;
import it.feio.android.omninotes.utils.ShortcutHelper;
import it.feio.android.omninotes.utils.StorageHelper;
import it.feio.android.omninotes.utils.TagsHelper;
import it.feio.android.omninotes.utils.TextHelper;
import it.feio.android.omninotes.utils.date.DateUtils;
import it.feio.android.omninotes.utils.date.ReminderPickers;
import it.feio.android.pixlui.links.TextLinkClickListener;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import rx.Observable;
public class DetailFragment extends BaseFragment implements OnReminderPickedListener,
OnTouchListener,
OnAttachingFileListener, TextWatcher, CheckListChangedListener, OnNoteSaved,
OnGeoUtilResultListener {
private static final int TAKE_PHOTO = 1;
private static final int TAKE_VIDEO = 2;
private static final int SET_PASSWORD = 3;
private static final int SKETCH = 4;
private static final int CATEGORY = 5;
private static final int DETAIL = 6;
private static final int FILES = 7;
private FragmentDetailBinding binding;
boolean goBack = false;
private ExpandableHeightGridView mGridView;
private View toggleChecklistView;
private Uri attachmentUri;
private AttachmentAdapter mAttachmentAdapter;
private MaterialDialog attachmentDialog;
private Note note;
private Note noteTmp;
private Note noteOriginal;
// Audio recording
private String recordName;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
private boolean isRecording = false;
private View isPlayingView = null;
private Bitmap recordingBitmap;
private ChecklistManager mChecklistManager;
// Values to print result
private String exitMessage;
private Style exitCroutonStyle = ONStyle.CONFIRM;
// Flag to check if after editing it will return to ListActivity or not
// and in the last case a Toast will be shown instead than Crouton
private boolean afterSavedReturnsToList = true;
private boolean showKeyboard = false;
private boolean swiping;
private int startSwipeX;
private boolean orientationChanged;
private long audioRecordingTimeStart;
private long audioRecordingTime;
private DetailFragment mFragment;
private Attachment sketchEdited;
private int contentLineCounter = 1;
private int contentCursorPosition;
private ArrayList<String> mergedNotesIds;
private MainActivity mainActivity;
TextLinkClickListener textLinkClickListener = new TextLinkClickListener() {
@Override
public void onTextLinkClick(View view, final String clickedString, final String url) {
new MaterialDialog.Builder(mainActivity)
.content(clickedString)
.negativeColorRes(R.color.colorPrimary)
.positiveText(R.string.open)
.negativeText(R.string.copy)
.onPositive((dialog, which) -> {
try {
Intent intent = TagOpenerHelper.openOrGetIntent(getContext(), url);
if (intent != null) {
mainActivity.initNotesList(intent);
}
} catch (UnhandledIntentException e) {
mainActivity.showMessage(R.string.no_application_can_perform_this_action,
ONStyle.ALERT);
}
})
.onNegative((dialog, which) -> {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager)
mainActivity.getSystemService(CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("text label",
clickedString);
clipboard.setPrimaryClip(clip);
}).build().show();
View clickedView = noteTmp.isChecklist() ? toggleChecklistView : binding.contentWrapper;
clickedView.clearFocus();
KeyboardUtils.hideKeyboard(clickedView);
new Handler().post(() -> {
View clickedView1 = noteTmp.isChecklist() ? toggleChecklistView : binding.contentWrapper;
KeyboardUtils.hideKeyboard(clickedView1);
});
}
};
private boolean activityPausing;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFragment = this;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
EventBus.getDefault().post(new SwitchFragmentEvent(SwitchFragmentEvent.Direction.CHILDREN));
}
@Override
public void onStop() {
super.onStop();
GeocodeHelper.stop();
}
@Override
public void onResume() {
super.onResume();
activityPausing = false;
EventBus.getDefault().register(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentDetailBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mainActivity = (MainActivity) getActivity();
mainActivity.getSupportActionBar().setDisplayShowTitleEnabled(false);
mainActivity.getToolbar().setNavigationOnClickListener(v -> navigateUp());
// Force the navigation drawer to stay opened if tablet mode is on, otherwise has to stay closed
if (NavigationDrawerFragment.isDoublePanelActive()) {
mainActivity.getDrawerLayout().setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
} else {
mainActivity.getDrawerLayout().setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
restoreTempNoteAfterOrientationChange(savedInstanceState);
addSketchedImageIfPresent();
// Ensures that Detail Fragment always have the back Arrow when it's created
EventBus.getDefault().post(new SwitchFragmentEvent(SwitchFragmentEvent.Direction.CHILDREN));
init();
setHasOptionsMenu(true);
setRetainInstance(false);
}
private void addSketchedImageIfPresent() {
if (mainActivity.getSketchUri() != null) {
Attachment mAttachment = new Attachment(mainActivity.getSketchUri(), MIME_TYPE_SKETCH);
addAttachment(mAttachment);
mainActivity.setSketchUri(null);
// Removes previous version of edited image
if (sketchEdited != null) {
noteTmp.getAttachmentsList().remove(sketchEdited);
sketchEdited = null;
}
}
}
private void restoreTempNoteAfterOrientationChange(Bundle savedInstanceState) {
if (savedInstanceState != null) {
noteTmp = savedInstanceState.getParcelable("noteTmp");
note = savedInstanceState.getParcelable("note");
noteOriginal = savedInstanceState.getParcelable("noteOriginal");
attachmentUri = savedInstanceState.getParcelable("attachmentUri");
orientationChanged = savedInstanceState.getBoolean("orientationChanged");
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (noteTmp != null) {
noteTmp.setTitle(getNoteTitle());
noteTmp.setContent(getNoteContent());
outState.putParcelable("noteTmp", noteTmp);
outState.putParcelable("note", note);
outState.putParcelable("noteOriginal", noteOriginal);
outState.putParcelable("attachmentUri", attachmentUri);
outState.putBoolean("orientationChanged", orientationChanged);
}
super.onSaveInstanceState(outState);
}
@Override
public void onPause() {
super.onPause();
//to prevent memory leak fragment keep refernce of event but until deregister
EventBus.getDefault().unregister(this);
activityPausing = true;
// Checks "goBack" value to avoid performing a double saving
if (!goBack) {
saveNote(this);
}
if (toggleChecklistView != null) {
KeyboardUtils.hideKeyboard(toggleChecklistView);
binding.contentWrapper.clearFocus();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (getResources().getConfiguration().orientation != newConfig.orientation) {
orientationChanged = true;
}
}
private void init() {
// Handling of Intent actions
handleIntents();
if (noteOriginal == null) {
noteOriginal = getArguments().getParcelable(INTENT_NOTE);
}
if (note == null) {
note = new Note(noteOriginal);
}
if (noteTmp == null) {
noteTmp = new Note(note);
}
if (noteTmp.isLocked() && !noteTmp.isPasswordChecked()) {
checkNoteLock(noteTmp);
return;
}
initViews();
}
/**
* Checks note lock and password before showing note content
*/
private void checkNoteLock(Note note) {
// If note is locked security password will be requested
if (note.isLocked()
&& Prefs.getString(PREF_PASSWORD, null) != null
&& !Prefs.getBoolean("settings_password_access", false)) {
PasswordHelper.requestPassword(mainActivity, passwordConfirmed -> {
switch (passwordConfirmed) {
case SUCCEED:
noteTmp.setPasswordChecked(true);
init();
break;
case FAIL:
goBack = true;
goHome();
break;
case RESTORE:
goBack = true;
goHome();
PasswordHelper.resetPassword(mainActivity);
break;
}
});
} else {
noteTmp.setPasswordChecked(true);
init();
}
}
private void handleIntents() {
Intent i = mainActivity.getIntent();
if (IntentChecker.checkAction(i, ACTION_MERGE)) {
noteOriginal = new Note();
note = new Note(noteOriginal);
noteTmp = getArguments().getParcelable(INTENT_NOTE);
if (i.getStringArrayListExtra("merged_notes") != null) {
mergedNotesIds = i.getStringArrayListExtra("merged_notes");
}
}
// Action called from home shortcut
if (IntentChecker.checkAction(i, ACTION_SHORTCUT, ACTION_NOTIFICATION_CLICK)) {
afterSavedReturnsToList = false;
noteOriginal = DbHelper.getInstance().getNote(i.getLongExtra(INTENT_KEY, 0));
// Checks if the note pointed from the shortcut has been deleted
try {
note = new Note(noteOriginal);
noteTmp = new Note(noteOriginal);
} catch (NullPointerException e) {
mainActivity.showToast(getText(R.string.shortcut_note_deleted), Toast.LENGTH_LONG);
mainActivity.finish();
}
}
// Check if is launched from a widget
if (IntentChecker.checkAction(i, ACTION_WIDGET, ACTION_WIDGET_TAKE_PHOTO)) {
afterSavedReturnsToList = false;
showKeyboard = true;
// with tags to set tag
if (i.hasExtra(INTENT_WIDGET)) {
String widgetId = i.getExtras().get(INTENT_WIDGET).toString();
String sqlCondition = Prefs.getString(PREF_WIDGET_PREFIX + widgetId, "");
String categoryId = TextHelper.checkIntentCategory(sqlCondition);
if (categoryId != null) {
Category category;
try {
category = DbHelper.getInstance().getCategory(parseLong(categoryId));
noteTmp = new Note();
noteTmp.setCategory(category);
} catch (NumberFormatException e) {
LogDelegate.e("Category with not-numeric value!", e);
}
}
}
// Sub-action is to take a photo
if (IntentChecker.checkAction(i, ACTION_WIDGET_TAKE_PHOTO)) {
takePhoto();
}
}
if (IntentChecker.checkAction(i, ACTION_FAB_TAKE_PHOTO)) {
takePhoto();
}
// Handles third party apps requests of sharing
if (IntentChecker
.checkAction(i, Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE, INTENT_GOOGLE_NOW)
&& i.getType() != null) {
afterSavedReturnsToList = false;
if (noteTmp == null) {
noteTmp = new Note();
}
// Text title
String title = i.getStringExtra(Intent.EXTRA_SUBJECT);
if (title != null) {
noteTmp.setTitle(title);
}
// Text content
String content = i.getStringExtra(Intent.EXTRA_TEXT);
if (content != null) {
noteTmp.setContent(content);
}
importAttachments(i);
}
if (IntentChecker
.checkAction(i, Intent.ACTION_MAIN, ACTION_WIDGET_SHOW_LIST, ACTION_SHORTCUT_WIDGET,
ACTION_WIDGET)) {
showKeyboard = true;
}
i.setAction(null);
}
private void importAttachments(Intent i) {
if (!i.hasExtra(Intent.EXTRA_STREAM)) {
return;
}
if (i.getExtras().get(Intent.EXTRA_STREAM) instanceof Uri) {
Uri uri = i.getParcelableExtra(Intent.EXTRA_STREAM);
// Google Now passes Intent as text but with audio recording attached the case must be handled like this
if (!INTENT_GOOGLE_NOW.equals(i.getAction())) {
String name = FileHelper.getNameFromUri(mainActivity, uri);
new AttachmentTask(this, uri, name, this).execute();
}
} else {
ArrayList<Uri> uris = i.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
for (Uri uriSingle : uris) {
String name = FileHelper.getNameFromUri(mainActivity, uriSingle);
new AttachmentTask(this, uriSingle, name, this).execute();
}
}
}
@SuppressLint("NewApi")
private void initViews() {
// Sets onTouchListener to the whole activity to swipe notes
binding.detailRoot.setOnTouchListener(this);
// Color of tag marker if note is tagged a function is active in preferences
setTagMarkerColor(noteTmp.getCategory());
initViewTitle();
initViewContent();
initViewLocation();
initViewAttachments();
initViewReminder();
initViewFooter();
}
private void initViewFooter() {
String creation = DateHelper
.getFormattedDate(noteTmp.getCreation(), Prefs.getBoolean(PREF_PRETTIFIED_DATES, true));
binding.creation
.append(creation.length() > 0 ? getString(R.string.creation) + " " + creation : "");
if (binding.creation.getText().length() == 0) {
binding.creation.setVisibility(View.GONE);
}
String lastModification = DateHelper
.getFormattedDate(noteTmp.getLastModification(), Prefs.getBoolean(
PREF_PRETTIFIED_DATES, true));
binding.lastModification
.append(lastModification.length() > 0 ? getString(R.string.last_update) + " " +
lastModification : "");
if (binding.lastModification.getText().length() == 0) {
binding.lastModification.setVisibility(View.GONE);
}
}
private void initViewReminder() {
binding.fragmentDetailContent.reminderLayout.setOnClickListener(v -> {
ReminderPickers reminderPicker = new ReminderPickers(mainActivity, mFragment);
reminderPicker.pick(DateUtils.getPresetReminder(noteTmp.getAlarm()), noteTmp
.getRecurrenceRule());
});
binding.fragmentDetailContent.reminderLayout.setOnLongClickListener(v -> {
MaterialDialog dialog = new MaterialDialog.Builder(mainActivity)
.content(R.string.remove_reminder)
.positiveText(R.string.ok)
.onPositive((dialog1, which) -> {
ReminderHelper.removeReminder(OmniNotes.getAppContext(), noteTmp);
noteTmp.setAlarm(null);
binding.fragmentDetailContent.reminderIcon
.setImageResource(R.drawable.ic_alarm_black_18dp);
binding.fragmentDetailContent.datetime.setText("");
}).build();
dialog.show();
return true;
});
// Reminder
String reminderString = initReminder(noteTmp);
if (!TextUtils.isEmpty(reminderString)) {
binding.fragmentDetailContent.reminderIcon
.setImageResource(R.drawable.ic_alarm_add_black_18dp);
binding.fragmentDetailContent.datetime.setText(reminderString);
}
}
private void initViewLocation() {
DetailFragment detailFragment = this;
if (isNoteLocationValid()) {
if (TextUtils.isEmpty(noteTmp.getAddress())) {
//FIXME: What's this "sasd"?
GeocodeHelper.getAddressFromCoordinates(new Location("sasd"), detailFragment);
} else {
binding.fragmentDetailContent.location.setText(noteTmp.getAddress());
binding.fragmentDetailContent.location.setVisibility(View.VISIBLE);
}
}
// Automatic location insertion
if (Prefs.getBoolean(PREF_AUTO_LOCATION, false) && noteTmp.get_id() == null) {
getLocation(detailFragment);
}
binding.fragmentDetailContent.location.setOnClickListener(v -> {
String uriString = "geo:" + noteTmp.getLatitude() + ',' + noteTmp.getLongitude()
+ "?q=" + noteTmp.getLatitude() + ',' + noteTmp.getLongitude();
Intent locationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uriString));
if (!IntentChecker.isAvailable(mainActivity, locationIntent, null)) {
uriString = "http://maps.google.com/maps?q=" + noteTmp.getLatitude() + ',' + noteTmp
.getLongitude();
locationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uriString));
}
startActivity(locationIntent);
});
binding.fragmentDetailContent.location.setOnLongClickListener(v -> {
MaterialDialog.Builder builder = new MaterialDialog.Builder(mainActivity);
builder.content(R.string.remove_location);
builder.positiveText(R.string.ok);
builder.onPositive((dialog, which) -> {
noteTmp.setLatitude("");
noteTmp.setLongitude("");
fade(binding.fragmentDetailContent.location, false);
});
MaterialDialog dialog = builder.build();
dialog.show();
return true;
});
}
private void getLocation(OnGeoUtilResultListener onGeoUtilResultListener) {
PermissionsHelper
.requestPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION, R.string
.permission_coarse_location, binding.snackbarPlaceholder,
() -> GeocodeHelper.getLocation(onGeoUtilResultListener));
}
private void initViewAttachments() {
// Attachments position based on preferences
if (Prefs.getBoolean(PREF_ATTACHMENTS_ON_BOTTOM, false)) {
binding.detailAttachmentsBelow.inflate();
} else {
binding.detailAttachmentsAbove.inflate();
}
mGridView = binding.detailRoot.findViewById(R.id.gridview);
// Some fields can be filled by third party application and are always shown
mAttachmentAdapter = new AttachmentAdapter(mainActivity, noteTmp.getAttachmentsList(),
mGridView);
// Initialzation of gridview for images
mGridView.setAdapter(mAttachmentAdapter);
mGridView.autoresize();
// Click events for images in gridview (zooms image)
mGridView.setOnItemClickListener((parent, v, position, id) -> {
Attachment attachment = (Attachment) parent.getAdapter().getItem(position);
Uri sharableUri = FileProviderHelper.getShareableUri(attachment);
Intent attachmentIntent;
if (MIME_TYPE_FILES.equals(attachment.getMime_type())) {
attachmentIntent = new Intent(Intent.ACTION_VIEW);
attachmentIntent.setDataAndType(sharableUri, StorageHelper.getMimeType(mainActivity,
sharableUri));
attachmentIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent
.FLAG_GRANT_WRITE_URI_PERMISSION);
if (IntentChecker
.isAvailable(mainActivity.getApplicationContext(), attachmentIntent, null)) {
startActivity(attachmentIntent);
} else {
mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.WARN);
}
// Media files will be opened in internal gallery
} else if (MIME_TYPE_IMAGE.equals(attachment.getMime_type())
|| MIME_TYPE_SKETCH.equals(attachment.getMime_type())
|| MIME_TYPE_VIDEO.equals(attachment.getMime_type())) {
// Title
noteTmp.setTitle(getNoteTitle());
noteTmp.setContent(getNoteContent());
String title1 = TextHelper.parseTitleAndContent(mainActivity,
noteTmp)[0].toString();
// Images
int clickedImage = 0;
ArrayList<Attachment> images = new ArrayList<>();
for (Attachment mAttachment : noteTmp.getAttachmentsList()) {
if (MIME_TYPE_IMAGE.equals(mAttachment.getMime_type())
|| MIME_TYPE_SKETCH.equals(mAttachment.getMime_type())
|| MIME_TYPE_VIDEO.equals(mAttachment.getMime_type())) {
images.add(mAttachment);
if (mAttachment.equals(attachment)) {
clickedImage = images.size() - 1;
}
}
}
// Intent
attachmentIntent = new Intent(mainActivity, GalleryActivity.class);
attachmentIntent.putExtra(GALLERY_TITLE, title1);
attachmentIntent.putParcelableArrayListExtra(GALLERY_IMAGES, images);
attachmentIntent.putExtra(GALLERY_CLICKED_IMAGE, clickedImage);
startActivity(attachmentIntent);
} else if (MIME_TYPE_AUDIO.equals(attachment.getMime_type())) {
playback(v, attachment.getUri());
}
});
mGridView.setOnItemLongClickListener((parent, v, position, id) -> {
// To avoid deleting audio attachment during playback
if (mPlayer != null) {
return false;
}
List<String> items = Arrays
.asList(getResources().getStringArray(R.array.attachments_actions));
if (!MIME_TYPE_SKETCH.equals(mAttachmentAdapter.getItem(position).getMime_type())) {
items = items.subList(0, items.size() - 1);
}
Attachment attachment = mAttachmentAdapter.getItem(position);
new MaterialDialog.Builder(mainActivity)
.title(attachment.getName() + " (" + AttachmentsHelper.getSize(attachment) + ")")
.items(items.toArray(new String[items.size()]))
.itemsCallback((materialDialog, view, i, charSequence) ->
performAttachmentAction(position, i))
.build()
.show();
return true;
});
}
/**
* Performs an action when long-click option is selected
*
* @param i item index
*/
private void performAttachmentAction(int attachmentPosition, int i) {
switch (getResources().getStringArray(R.array.attachments_actions_values)[i]) {
case "share":
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Attachment attachment = mAttachmentAdapter.getItem(attachmentPosition);
shareIntent
.setType(StorageHelper.getMimeType(OmniNotes.getAppContext(), attachment.getUri()));
shareIntent.putExtra(Intent.EXTRA_STREAM, FileProviderHelper.getShareableUri(attachment));
if (IntentChecker.isAvailable(OmniNotes.getAppContext(), shareIntent, null)) {
startActivity(shareIntent);
} else {
mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.WARN);
}
break;
case "delete":
removeAttachment(attachmentPosition);
mAttachmentAdapter.notifyDataSetChanged();
mGridView.autoresize();
break;
case "delete all":
new MaterialDialog.Builder(mainActivity)
.title(R.string.delete_all_attachments)
.positiveText(R.string.confirm)
.onPositive((materialDialog, dialogAction) -> removeAllAttachments())
.build()
.show();
break;
case "edit":
takeSketch(mAttachmentAdapter.getItem(attachmentPosition));
break;
default:
LogDelegate.w("No action available");
}
}
private void initViewTitle() {
binding.detailTitle.setText(noteTmp.getTitle());
binding.detailTitle.gatherLinksForText();
binding.detailTitle.setOnTextLinkClickListener(textLinkClickListener);
// To avoid dropping here the dragged checklist items
binding.detailTitle.setOnDragListener((v, event) -> {
// ((View)event.getLocalState()).setVisibility(View.VISIBLE);
return true;
});
//When editor action is pressed focus is moved to last character in content field
binding.detailTitle.setOnEditorActionListener((v, actionId, event) -> {
binding.fragmentDetailContent.detailContent.requestFocus();
binding.fragmentDetailContent.detailContent
.setSelection(binding.fragmentDetailContent.detailContent.getText().length());
return false;
});
requestFocus(binding.detailTitle);
}
private void initViewContent() {
binding.fragmentDetailContent.detailContent.setText(noteTmp.getContent());
binding.fragmentDetailContent.detailContent.gatherLinksForText();
binding.fragmentDetailContent.detailContent.setOnTextLinkClickListener(textLinkClickListener);
// Avoids focused line goes under the keyboard
binding.fragmentDetailContent.detailContent.addTextChangedListener(this);
// Restore checklist
toggleChecklistView = binding.fragmentDetailContent.detailContent;
if (noteTmp.isChecklist()) {
noteTmp.setChecklist(false);
AlphaManager.setAlpha(toggleChecklistView, 0);
toggleChecklist2();
}
}
/**
* Force focus and shows soft keyboard. Only happens if it's a new note, without shared content.
* {@link showKeyboard} is used to check if the note is created from shared content.
*/
@SuppressWarnings("JavadocReference")
private void requestFocus(final EditText view) {
if (note.get_id() == null && !noteTmp.isChanged(note) && showKeyboard) {
KeyboardUtils.showKeyboard(view);
}
}
/**
* Colors tag marker in note's title and content elements
*/
private void setTagMarkerColor(Category tag) {
String colorsPref = Prefs.getString("settings_colors_app", PREF_COLORS_APP_DEFAULT);
// Checking preference
if (!"disabled".equals(colorsPref)) {
// Choosing target view depending on another preference
ArrayList<View> target = new ArrayList<>();
if ("complete".equals(colorsPref)) {
target.add(binding.titleWrapper);
target.add(binding.contentWrapper);
} else {
target.add(binding.tagMarker);
}
// Coloring the target
if (tag != null && tag.getColor() != null) {
for (View view : target) {
view.setBackgroundColor(parseInt(tag.getColor()));
}
} else {
for (View view : target) {
view.setBackgroundColor(Color.parseColor("#00000000"));
}
}
}
}
private void displayLocationDialog() {
getLocation(new OnGeoUtilResultListenerImpl(mainActivity, mFragment, noteTmp));
}
@Override
public void onLocationRetrieved(Location location) {
if (location == null) {
mainActivity.showMessage(R.string.location_not_found, ONStyle.ALERT);
}
if (location != null) {
noteTmp.setLatitude(location.getLatitude());
noteTmp.setLongitude(location.getLongitude());
if (!TextUtils.isEmpty(noteTmp.getAddress())) {
binding.fragmentDetailContent.location.setVisibility(View.VISIBLE);
binding.fragmentDetailContent.location.setText(noteTmp.getAddress());
} else {
GeocodeHelper.getAddressFromCoordinates(location, mFragment);
}
}
}
@Override
public void onLocationUnavailable() {
mainActivity.showMessage(R.string.location_not_found, ONStyle.ALERT);
}
@Override
public void onAddressResolved(String address) {
if (TextUtils.isEmpty(address)) {
if (!isNoteLocationValid()) {
mainActivity.showMessage(R.string.location_not_found, ONStyle.ALERT);
return;
}
address = noteTmp.getLatitude() + ", " + noteTmp.getLongitude();
}
if (!GeocodeHelper.areCoordinates(address)) {
noteTmp.setAddress(address);
}
binding.fragmentDetailContent.location.setVisibility(View.VISIBLE);
binding.fragmentDetailContent.location.setText(address);
fade(binding.fragmentDetailContent.location, true);
}
@Override
public void onCoordinatesResolved(Location location, String address) {
if (location != null) {
noteTmp.setLatitude(location.getLatitude());
noteTmp.setLongitude(location.getLongitude());
noteTmp.setAddress(address);
binding.fragmentDetailContent.location.setVisibility(View.VISIBLE);
binding.fragmentDetailContent.location.setText(address);
fade(binding.fragmentDetailContent.location, true);
} else {
mainActivity.showMessage(R.string.location_not_found, ONStyle.ALERT);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_detail, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
// Closes search view if left open in List fragment
MenuItem searchMenuItem = menu.findItem(R.id.menu_search);
if (searchMenuItem != null) {
searchMenuItem.collapseActionView();
}
boolean newNote = noteTmp.get_id() == null;
menu.findItem(R.id.menu_checklist_on).setVisible(!noteTmp.isChecklist());
menu.findItem(R.id.menu_checklist_off).setVisible(noteTmp.isChecklist());
menu.findItem(R.id.menu_checklist_moveToBottom)
.setVisible(noteTmp.isChecklist() && mChecklistManager.getCheckedCount() > 0);
menu.findItem(R.id.menu_lock).setVisible(!noteTmp.isLocked());
menu.findItem(R.id.menu_unlock).setVisible(noteTmp.isLocked());
// If note is trashed only this options will be available from menu
if (noteTmp.isTrashed()) {
menu.findItem(R.id.menu_untrash).setVisible(true);
menu.findItem(R.id.menu_delete).setVisible(true);
// Otherwise all other actions will be available
} else {
// Temporary removed until fixed on Oreo and following
menu.findItem(R.id.menu_add_shortcut).setVisible(!newNote);
menu.findItem(R.id.menu_pin_note).setVisible(!newNote);
menu.findItem(R.id.menu_archive).setVisible(!newNote && !noteTmp.isArchived());
menu.findItem(R.id.menu_unarchive).setVisible(!newNote && noteTmp.isArchived());
menu.findItem(R.id.menu_trash).setVisible(!newNote);