-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathMainActivity.kt
More file actions
1590 lines (1415 loc) · 56.7 KB
/
MainActivity.kt
File metadata and controls
1590 lines (1415 loc) · 56.7 KB
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 org.fossify.notes.activities
import android.accounts.NetworkErrorException
import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.content.Intent.FLAG_ACTIVITY_NO_HISTORY
import android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
import android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.drawable.Icon
import android.graphics.drawable.LayerDrawable
import android.net.Uri
import android.os.Bundle
import android.print.PrintAttributes
import android.print.PrintManager
import android.text.method.ArrowKeyMovementMethod
import android.text.method.LinkMovementMethod
import android.util.TypedValue
import android.view.ActionMode
import android.view.Gravity
import android.view.MenuItem
import android.view.inputmethod.EditorInfo
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.net.toUri
import androidx.viewpager.widget.ViewPager
import org.fossify.commons.dialogs.ConfirmationAdvancedDialog
import org.fossify.commons.dialogs.ConfirmationDialog
import org.fossify.commons.dialogs.FilePickerDialog
import org.fossify.commons.dialogs.RadioGroupDialog
import org.fossify.commons.dialogs.SecurityDialog
import org.fossify.commons.extensions.appLaunched
import org.fossify.commons.extensions.appLockManager
import org.fossify.commons.extensions.applyColorFilter
import org.fossify.commons.extensions.baseConfig
import org.fossify.commons.extensions.beVisibleIf
import org.fossify.commons.extensions.checkWhatsNew
import org.fossify.commons.extensions.clearBackgroundSpans
import org.fossify.commons.extensions.convertToBitmap
import org.fossify.commons.extensions.deleteFile
import org.fossify.commons.extensions.fadeIn
import org.fossify.commons.extensions.fadeOut
import org.fossify.commons.extensions.getContrastColor
import org.fossify.commons.extensions.getCurrentFormattedDateTime
import org.fossify.commons.extensions.getDocumentFile
import org.fossify.commons.extensions.getFilenameFromContentUri
import org.fossify.commons.extensions.getFilenameFromPath
import org.fossify.commons.extensions.getProperBackgroundColor
import org.fossify.commons.extensions.getProperPrimaryColor
import org.fossify.commons.extensions.getProperStatusBarColor
import org.fossify.commons.extensions.getRealPathFromURI
import org.fossify.commons.extensions.handleDeletePasswordProtection
import org.fossify.commons.extensions.hasPermission
import org.fossify.commons.extensions.hideKeyboard
import org.fossify.commons.extensions.highlightText
import org.fossify.commons.extensions.isMediaFile
import org.fossify.commons.extensions.launchMoreAppsFromUsIntent
import org.fossify.commons.extensions.needsStupidWritePermissions
import org.fossify.commons.extensions.onGlobalLayout
import org.fossify.commons.extensions.onPageChangeListener
import org.fossify.commons.extensions.onTextChangeListener
import org.fossify.commons.extensions.performSecurityCheck
import org.fossify.commons.extensions.searchMatches
import org.fossify.commons.extensions.shortcutManager
import org.fossify.commons.extensions.showErrorToast
import org.fossify.commons.extensions.showKeyboard
import org.fossify.commons.extensions.toast
import org.fossify.commons.extensions.updateTextColors
import org.fossify.commons.extensions.value
import org.fossify.commons.extensions.viewBinding
import org.fossify.commons.helpers.LICENSE_RTL
import org.fossify.commons.helpers.PERMISSION_READ_STORAGE
import org.fossify.commons.helpers.PERMISSION_WRITE_STORAGE
import org.fossify.commons.helpers.PROTECTION_NONE
import org.fossify.commons.helpers.REAL_FILE_PATH
import org.fossify.commons.helpers.SHOW_ALL_TABS
import org.fossify.commons.helpers.ensureBackgroundThread
import org.fossify.commons.helpers.isQPlus
import org.fossify.commons.models.FAQItem
import org.fossify.commons.models.FileDirItem
import org.fossify.commons.models.RadioItem
import org.fossify.commons.models.Release
import org.fossify.commons.views.MyEditText
import org.fossify.notes.BuildConfig
import org.fossify.notes.R
import org.fossify.notes.adapters.NotesPagerAdapter
import org.fossify.notes.databases.NotesDatabase
import org.fossify.notes.databinding.ActivityMainBinding
import org.fossify.notes.dialogs.DeleteNoteDialog
import org.fossify.notes.dialogs.ExportFileDialog
import org.fossify.notes.dialogs.ImportFolderDialog
import org.fossify.notes.dialogs.NewNoteDialog
import org.fossify.notes.dialogs.OpenFileDialog
import org.fossify.notes.dialogs.OpenNoteDialog
import org.fossify.notes.dialogs.RenameNoteDialog
import org.fossify.notes.dialogs.SortChecklistDialog
import org.fossify.notes.extensions.config
import org.fossify.notes.extensions.getPercentageFontSize
import org.fossify.notes.extensions.notesDB
import org.fossify.notes.extensions.parseChecklistItems
import org.fossify.notes.extensions.updateWidgets
import org.fossify.notes.extensions.widgetsDB
import org.fossify.notes.fragments.TextFragment
import org.fossify.notes.helpers.MIME_TEXT_PLAIN
import org.fossify.notes.helpers.MyMovementMethod
import org.fossify.notes.helpers.NEW_CHECKLIST
import org.fossify.notes.helpers.NEW_TEXT_NOTE
import org.fossify.notes.helpers.NotesHelper
import org.fossify.notes.helpers.OPEN_NOTE_ID
import org.fossify.notes.helpers.SHORTCUT_NEW_CHECKLIST
import org.fossify.notes.helpers.SHORTCUT_NEW_TEXT_NOTE
import org.fossify.notes.models.Note
import org.fossify.notes.models.NoteType
import java.io.File
import java.nio.charset.Charset
class MainActivity : SimpleActivity() {
private val EXPORT_FILE_SYNC = 1
private val EXPORT_FILE_NO_SYNC = 2
private val IMPORT_FILE_SYNC = 1
private val IMPORT_FILE_NO_SYNC = 2
private val PICK_OPEN_FILE_INTENT = 1
private val PICK_EXPORT_FILE_INTENT = 2
private lateinit var mCurrentNote: Note
private var mNotes = listOf<Note>()
private var mAdapter: NotesPagerAdapter? = null
private var noteViewWithTextSelected: MyEditText? = null
private var saveNoteButton: MenuItem? = null
private var wasInit = false
private var storedEnableLineWrap = true
private var showSaveButton = false
private var showUndoButton = false
private var showRedoButton = false
private var searchIndex = 0
private var searchMatches = emptyList<Int>()
private var isSearchActive = false
private lateinit var searchQueryET: MyEditText
private lateinit var searchPrevBtn: ImageView
private lateinit var searchNextBtn: ImageView
private lateinit var searchClearBtn: ImageView
private val binding by viewBinding(ActivityMainBinding::inflate)
override fun onCreate(savedInstanceState: Bundle?) {
isMaterialActivity = true
super.onCreate(savedInstanceState)
setContentView(binding.root)
appLaunched(BuildConfig.APPLICATION_ID)
setupOptionsMenu()
refreshMenuItems()
updateMaterialActivityViews(
mainCoordinatorLayout = binding.mainCoordinator,
nestedView = null,
useTransparentNavigation = false,
useTopSearchMenu = false
)
searchQueryET = findViewById(org.fossify.commons.R.id.search_query)
searchPrevBtn = findViewById(org.fossify.commons.R.id.search_previous)
searchNextBtn = findViewById(org.fossify.commons.R.id.search_next)
searchClearBtn = findViewById(org.fossify.commons.R.id.search_clear)
val noteToOpen = intent.getLongExtra(OPEN_NOTE_ID, -1L)
initViewPager(noteToOpen)
binding.pagerTabStrip.drawFullUnderline = false
val textSize = getPercentageFontSize()
binding.pagerTabStrip.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
binding.pagerTabStrip.layoutParams.height =
(textSize + resources.getDimension(org.fossify.commons.R.dimen.medium_margin) * 2).toInt()
(binding.pagerTabStrip.layoutParams as ViewPager.LayoutParams).isDecor = true
val hasNoIntent = intent.action.isNullOrEmpty() && noteToOpen == -1L
checkWhatsNewDialog()
checkIntents(intent)
storeStateVariables()
if (config.showNotePicker && savedInstanceState == null && hasNoIntent) {
displayOpenNoteDialog()
}
wasInit = true
checkAppOnSDCard()
setupSearchButtons()
}
override fun onResume() {
super.onResume()
setupToolbar(binding.mainToolbar)
if (storedEnableLineWrap != config.enableLineWrap) {
initViewPager()
}
NotesHelper(this).getNotes { latestNotes ->
if (mNotes.size != latestNotes.size) {
initViewPager()
}
}
applyReadOnlyStateToCurrentNote()
refreshMenuItems()
binding.pagerTabStrip.apply {
val textSize = getPercentageFontSize()
setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
layoutParams.height =
(textSize + resources.getDimension(org.fossify.commons.R.dimen.medium_margin) * 2).toInt()
setGravity(Gravity.CENTER_VERTICAL)
setNonPrimaryAlpha(0.4f)
setTextColor(getProperPrimaryColor())
tabIndicatorColor = getProperPrimaryColor()
}
updateTextColors(binding.viewPager)
checkShortcuts()
binding.searchWrapper.setBackgroundColor(getProperStatusBarColor())
val contrastColor = getProperPrimaryColor().getContrastColor()
arrayListOf(searchPrevBtn, searchNextBtn, searchClearBtn).forEach {
it.applyColorFilter(contrastColor)
}
updateTopBarColors(binding.mainToolbar, getProperBackgroundColor())
}
override fun onPause() {
super.onPause()
storeStateVariables()
}
override fun onDestroy() {
super.onDestroy()
if (!isChangingConfigurations) {
NotesDatabase.destroyInstance()
}
}
private fun refreshMenuItems() {
val multipleNotesExist = mNotes.size > 1
val isCurrentItemChecklist = isCurrentItemChecklist()
binding.mainToolbar.menu.apply {
findItem(R.id.undo).apply {
isVisible = showUndoButton && !mCurrentNote.isReadOnly && mCurrentNote.type == NoteType.TYPE_TEXT
icon?.alpha = if (isEnabled) 255 else 127
}
findItem(R.id.redo).apply {
isVisible = showRedoButton && !mCurrentNote.isReadOnly && mCurrentNote.type == NoteType.TYPE_TEXT
icon?.alpha = if (isEnabled) 255 else 127
}
findItem(R.id.rename_note).isVisible = multipleNotesExist
findItem(R.id.open_note).isVisible = multipleNotesExist
findItem(R.id.delete_note).isVisible = multipleNotesExist
findItem(R.id.open_search).isVisible = !isCurrentItemChecklist
findItem(R.id.remove_done_items).isVisible = isCurrentItemChecklist
findItem(R.id.sort_checklist).isVisible = isCurrentItemChecklist
findItem(R.id.import_folder).isVisible = !isQPlus()
findItem(R.id.lock_note).isVisible =
mNotes.isNotEmpty() && (::mCurrentNote.isInitialized && !mCurrentNote.isLocked())
findItem(R.id.unlock_note).isVisible =
mNotes.isNotEmpty() && (::mCurrentNote.isInitialized && mCurrentNote.isLocked())
findItem(R.id.more_apps_from_us).isVisible =
!resources.getBoolean(org.fossify.commons.R.bool.hide_google_relations)
saveNoteButton = findItem(R.id.save_note)
saveNoteButton!!.isVisible =
!config.autosaveNotes && showSaveButton && (::mCurrentNote.isInitialized && mCurrentNote.type == NoteType.TYPE_TEXT)
findItem(R.id.preview_mode).isVisible = (::mCurrentNote.isInitialized && !mCurrentNote.isReadOnly && mCurrentNote.type != NoteType.TYPE_CHECKLIST)
findItem(R.id.edit_mode).isVisible = (::mCurrentNote.isInitialized && mCurrentNote.isReadOnly && mCurrentNote.type != NoteType.TYPE_CHECKLIST)
}
binding.pagerTabStrip.beVisibleIf(multipleNotesExist)
}
private fun setupOptionsMenu() {
binding.mainToolbar.setOnMenuItemClickListener { menuItem ->
if (config.autosaveNotes && menuItem.itemId != R.id.undo && menuItem.itemId != R.id.redo) {
saveCurrentNote(false) {
mCurrentNote = it
}
}
val fragment = getCurrentFragment()
when (menuItem.itemId) {
R.id.open_search -> fragment?.handleUnlocking { openSearch() }
R.id.open_note -> displayOpenNoteDialog()
R.id.save_note -> fragment?.handleUnlocking { saveNote() }
R.id.undo -> undo()
R.id.redo -> redo()
R.id.new_note -> displayNewNoteDialog()
R.id.rename_note -> fragment?.handleUnlocking { displayRenameDialog() }
R.id.share -> fragment?.handleUnlocking { shareText() }
R.id.cab_create_shortcut -> createShortcut()
R.id.lock_note -> lockNote()
R.id.unlock_note -> unlockNote()
R.id.preview_mode -> toggleReadOnly()
R.id.edit_mode -> toggleReadOnly()
R.id.open_file -> tryOpenFile()
R.id.import_folder -> openFolder()
R.id.export_as_file -> fragment?.handleUnlocking { tryExportAsFile() }
R.id.print -> fragment?.handleUnlocking { printText() }
R.id.delete_note -> fragment?.handleUnlocking { displayDeleteNotePrompt() }
R.id.more_apps_from_us -> launchMoreAppsFromUsIntent()
R.id.settings -> launchSettings()
R.id.about -> launchAbout()
R.id.remove_done_items -> fragment?.handleUnlocking { removeDoneItems() }
R.id.sort_checklist -> fragment?.handleUnlocking { displaySortChecklistDialog() }
else -> return@setOnMenuItemClickListener false
}
return@setOnMenuItemClickListener true
}
}
// https://code.google.com/p/android/issues/detail?id=191430 quickfix
override fun onActionModeStarted(mode: ActionMode?) {
super.onActionModeStarted(mode)
if (wasInit) {
currentNotesView()?.apply {
if (config.clickableLinks || movementMethod is LinkMovementMethod || movementMethod is MyMovementMethod) {
movementMethod = ArrowKeyMovementMethod.getInstance()
noteViewWithTextSelected = this
}
}
}
}
override fun onActionModeFinished(mode: ActionMode?) {
super.onActionModeFinished(mode)
if (config.clickableLinks) {
noteViewWithTextSelected?.movementMethod = MyMovementMethod.getInstance()
}
}
override fun onBackPressed() {
if (!config.autosaveNotes && mAdapter?.anyHasUnsavedChanges() == true) {
ConfirmationAdvancedDialog(
activity = this,
message = "",
messageId = R.string.unsaved_changes_warning,
positive = org.fossify.commons.R.string.save,
negative = org.fossify.commons.R.string.discard
) {
if (it) {
mAdapter?.saveAllFragmentTexts()
}
appLockManager.lock()
super.onBackPressed()
}
} else if (isSearchActive) {
closeSearch()
} else {
appLockManager.lock()
super.onBackPressed()
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
val wantedNoteId = intent.getLongExtra(OPEN_NOTE_ID, -1L)
binding.viewPager.currentItem = getWantedNoteIndex(wantedNoteId)
checkIntents(intent)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
super.onActivityResult(requestCode, resultCode, resultData)
if (resultCode != RESULT_OK || resultData?.data == null) return
val dataUri = resultData.data!!
when (requestCode) {
PICK_OPEN_FILE_INTENT -> importUri(dataUri)
PICK_EXPORT_FILE_INTENT -> if (mNotes.isNotEmpty()) {
applicationContext.contentResolver.takePersistableUriPermission(
dataUri, FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION
)
showExportFilePickUpdateDialog(resultData.dataString!!, getCurrentNoteValue())
}
}
}
private fun isCurrentItemChecklist(): Boolean {
return if (::mCurrentNote.isInitialized) {
mCurrentNote.type == NoteType.TYPE_CHECKLIST
} else {
false
}
}
@SuppressLint("NewApi")
private fun checkShortcuts() {
val appIconColor = config.appIconColor
if (config.lastHandledShortcutColor != appIconColor) {
val newTextNote = getNewTextNoteShortcut(appIconColor)
val newChecklist = getNewChecklistShortcut(appIconColor)
try {
shortcutManager.dynamicShortcuts = listOf(newTextNote, newChecklist)
config.lastHandledShortcutColor = appIconColor
} catch (_: Exception) {
}
}
}
@SuppressLint("NewApi")
private fun getNewTextNoteShortcut(appIconColor: Int): ShortcutInfo {
val shortLabel = getString(R.string.text_note)
val longLabel = getString(R.string.new_text_note)
val drawable = AppCompatResources.getDrawable(
this, org.fossify.commons.R.drawable.shortcut_plus
)
(drawable as LayerDrawable).findDrawableByLayerId(R.id.shortcut_plus_background)
.applyColorFilter(appIconColor)
val bmp = drawable.convertToBitmap()
val intent = Intent(this, MainActivity::class.java)
intent.action = Intent.ACTION_VIEW
intent.putExtra(NEW_TEXT_NOTE, true)
return ShortcutInfo.Builder(this, SHORTCUT_NEW_TEXT_NOTE)
.setShortLabel(shortLabel)
.setLongLabel(longLabel)
.setIcon(Icon.createWithBitmap(bmp))
.setIntent(intent)
.build()
}
@SuppressLint("NewApi")
private fun getNewChecklistShortcut(appIconColor: Int): ShortcutInfo {
val shortLabel = getString(R.string.checklist)
val longLabel = getString(R.string.new_checklist)
val drawable = AppCompatResources.getDrawable(this, R.drawable.shortcut_check)
(drawable as LayerDrawable).findDrawableByLayerId(R.id.shortcut_plus_background)
.applyColorFilter(appIconColor)
val bmp = drawable.convertToBitmap()
val intent = Intent(this, MainActivity::class.java)
intent.action = Intent.ACTION_VIEW
intent.putExtra(NEW_CHECKLIST, true)
return ShortcutInfo.Builder(this, SHORTCUT_NEW_CHECKLIST)
.setShortLabel(shortLabel)
.setLongLabel(longLabel)
.setIcon(Icon.createWithBitmap(bmp))
.setIntent(intent)
.build()
}
private fun checkIntents(intent: Intent) {
intent.apply {
if (action == Intent.ACTION_SEND && type == MIME_TEXT_PLAIN) {
getStringExtra(Intent.EXTRA_TEXT)?.let {
handleTextIntent(it)
intent.removeExtra(Intent.EXTRA_TEXT)
}
}
if (action == Intent.ACTION_VIEW) {
val realPath = intent.getStringExtra(REAL_FILE_PATH)
val isFromHistory = intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0
if (!isFromHistory) {
if (realPath != null && hasPermission(PERMISSION_READ_STORAGE)) {
val file = File(realPath)
handleUri(Uri.fromFile(file))
} else if (intent.getBooleanExtra(NEW_TEXT_NOTE, false)) {
addNewNote(
Note(
id = null,
title = getCurrentFormattedDateTime(),
value = "",
type = NoteType.TYPE_TEXT,
path = "",
protectionType = PROTECTION_NONE,
protectionHash = ""
)
)
} else if (intent.getBooleanExtra(NEW_CHECKLIST, false)) {
addNewNote(
Note(
id = null,
title = getCurrentFormattedDateTime(),
value = "",
type = NoteType.TYPE_CHECKLIST,
path = "",
protectionType = PROTECTION_NONE,
protectionHash = ""
)
)
} else {
handleUri(data!!)
}
}
intent.removeCategory(Intent.CATEGORY_DEFAULT)
intent.action = null
intent.removeExtra(NEW_CHECKLIST)
intent.removeExtra(NEW_TEXT_NOTE)
}
}
}
private fun storeStateVariables() {
config.apply {
storedEnableLineWrap = enableLineWrap
}
}
private fun handleTextIntent(text: String) {
NotesHelper(this).getNotes {
val notes = it
val list = arrayListOf<RadioItem>().apply {
add(RadioItem(0, getString(R.string.create_new_note)))
notes.forEachIndexed { index, note ->
add(RadioItem(index + 1, note.title))
}
}
RadioGroupDialog(this, list, -1, R.string.add_to_note) {
if (it as Int == 0) {
displayNewNoteDialog(text)
} else {
updateSelectedNote(notes[it - 1].id!!)
addTextToCurrentNote(if (mCurrentNote.value.isEmpty()) text else "\n$text")
}
}
}
}
private fun handleUri(uri: Uri) {
NotesHelper(this).getNoteIdWithPath(uri.path!!) {
if (it != null && it > 0L) {
updateSelectedNote(it)
return@getNoteIdWithPath
}
NotesHelper(this).getNotes {
mNotes = it
importUri(uri)
}
}
}
private fun initViewPager(wantedNoteId: Long? = null) {
NotesHelper(this).getNotes { notes ->
notes.filter { it.shouldBeUnlocked(this) }
.forEach(::removeProtection)
mNotes = notes
mCurrentNote = mNotes[0]
mAdapter = NotesPagerAdapter(supportFragmentManager, mNotes, this)
binding.viewPager.apply {
adapter = mAdapter
currentItem = getWantedNoteIndex(wantedNoteId)
config.currentNoteId = mCurrentNote.id!!
onPageChangeListener {
mCurrentNote = mNotes[it]
config.currentNoteId = mCurrentNote.id!!
applyReadOnlyStateToCurrentNote()
refreshMenuItems()
}
}
if (!config.showKeyboard || mCurrentNote.type == NoteType.TYPE_CHECKLIST) {
hideKeyboard()
}
applyReadOnlyStateToCurrentNote()
refreshMenuItems()
}
}
private fun setupSearchButtons() {
searchQueryET.onTextChangeListener {
searchTextChanged(it)
}
searchPrevBtn.setOnClickListener {
goToPrevSearchResult()
}
searchNextBtn.setOnClickListener {
goToNextSearchResult()
}
searchClearBtn.setOnClickListener {
closeSearch()
}
binding.viewPager.onPageChangeListener {
currentTextFragment?.removeTextWatcher()
currentNotesView()?.let { noteView ->
noteView.text!!.clearBackgroundSpans()
}
closeSearch()
currentTextFragment?.setTextWatcher()
}
searchQueryET.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
searchNextBtn.performClick()
return@OnEditorActionListener true
}
false
})
}
private fun searchTextChanged(text: String) {
currentNotesView()?.let { noteView ->
currentTextFragment?.removeTextWatcher()
noteView.text!!.clearBackgroundSpans()
if (text.isNotBlank() && text.length > 1) {
searchMatches = noteView.value.searchMatches(text)
noteView.highlightText(text, getProperPrimaryColor())
}
currentTextFragment?.setTextWatcher()
if (searchMatches.isNotEmpty()) {
noteView.requestFocus()
noteView.setSelection(searchMatches.getOrNull(searchIndex) ?: 0)
}
searchQueryET.postDelayed({
searchQueryET.requestFocus()
}, 50)
}
}
private fun goToPrevSearchResult() {
currentNotesView()?.let { noteView ->
if (searchIndex > 0) {
searchIndex--
} else {
searchIndex = searchMatches.lastIndex
}
selectSearchMatch(noteView)
}
}
private fun goToNextSearchResult() {
currentNotesView()?.let { noteView ->
if (searchIndex < searchMatches.lastIndex) {
searchIndex++
} else {
searchIndex = 0
}
selectSearchMatch(noteView)
}
}
private fun getCurrentFragment() = mAdapter?.getFragment(binding.viewPager.currentItem)
private val currentTextFragment: TextFragment? get() = mAdapter?.textFragment(binding.viewPager.currentItem)
private fun selectSearchMatch(editText: MyEditText) {
if (searchMatches.isNotEmpty()) {
editText.requestFocus()
editText.setSelection(searchMatches.getOrNull(searchIndex) ?: 0)
} else {
hideKeyboard()
}
}
private fun openSearch() {
isSearchActive = true
binding.searchWrapper.fadeIn()
showKeyboard(searchQueryET)
currentNotesView()?.let { noteView ->
noteView.requestFocus()
noteView.setSelection(0)
}
searchQueryET.postDelayed({
searchQueryET.requestFocus()
}, 250)
}
private fun closeSearch() {
searchQueryET.text?.clear()
isSearchActive = false
binding.searchWrapper.fadeOut()
hideKeyboard()
}
private fun getWantedNoteIndex(wantedNoteId: Long?): Int {
intent.removeExtra(OPEN_NOTE_ID)
val noteIdToOpen =
if (wantedNoteId == null || wantedNoteId == -1L) config.currentNoteId else wantedNoteId
return getNoteIndexWithId(noteIdToOpen)
}
private fun currentNotesView(): MyEditText? {
return mAdapter?.getCurrentNotesView(binding.viewPager.currentItem)
}
private fun displayRenameDialog() {
RenameNoteDialog(this, mCurrentNote, getCurrentNoteText()) {
mCurrentNote = it
initViewPager(mCurrentNote.id)
}
}
private fun updateSelectedNote(id: Long) {
config.currentNoteId = id
if (mNotes.isEmpty()) {
NotesHelper(this).getNotes {
mNotes = it
updateSelectedNote(id)
}
} else {
val index = getNoteIndexWithId(id)
binding.viewPager.currentItem = index
mCurrentNote = mNotes[index]
applyReadOnlyStateToCurrentNote()
}
}
private fun displayNewNoteDialog(
value: String = "",
title: String? = null,
path: String = "",
setChecklistAsDefault: Boolean = false,
) {
NewNoteDialog(this, title, setChecklistAsDefault) {
it.value = value
it.path = path
addNewNote(it)
}
}
private fun addNewNote(note: Note) {
NotesHelper(this).insertOrUpdateNote(note) {
val newNoteId = it
showSaveButton = false
showUndoButton = false
showRedoButton = false
initViewPager(newNoteId)
updateSelectedNote(newNoteId)
applyReadOnlyStateToCurrentNote()
binding.viewPager.onGlobalLayout {
mAdapter?.focusEditText(getNoteIndexWithId(newNoteId))
}
}
}
private fun launchSettings() {
hideKeyboard()
startActivity(Intent(applicationContext, SettingsActivity::class.java))
}
private fun launchAbout() {
val licenses = LICENSE_RTL
val faqItems = arrayListOf(
FAQItem(
title = org.fossify.commons.R.string.faq_1_title_commons,
text = org.fossify.commons.R.string.faq_1_text_commons
),
FAQItem(
title = R.string.faq_1_title,
text = R.string.faq_1_text
)
)
if (!resources.getBoolean(org.fossify.commons.R.bool.hide_google_relations)) {
faqItems.add(
FAQItem(
title = org.fossify.commons.R.string.faq_2_title_commons,
text = org.fossify.commons.R.string.faq_2_text_commons
)
)
faqItems.add(
FAQItem(
title = org.fossify.commons.R.string.faq_6_title_commons,
text = org.fossify.commons.R.string.faq_6_text_commons
)
)
faqItems.add(
FAQItem(
title = org.fossify.commons.R.string.faq_7_title_commons,
text = org.fossify.commons.R.string.faq_7_text_commons
)
)
faqItems.add(
FAQItem(
title = org.fossify.commons.R.string.faq_10_title_commons,
text = org.fossify.commons.R.string.faq_10_text_commons
)
)
}
startAboutActivity(
appNameId = R.string.app_name,
licenseMask = licenses,
versionName = BuildConfig.VERSION_NAME,
faqItems = faqItems,
showFAQBeforeMail = true
)
}
private fun tryOpenFile() {
hideKeyboard()
if (hasPermission(PERMISSION_READ_STORAGE)) {
openFile()
} else {
Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "*/*"
try {
val mimetypes = arrayOf("text/*", "application/json")
putExtra(Intent.EXTRA_MIME_TYPES, mimetypes)
startActivityForResult(this, PICK_OPEN_FILE_INTENT)
} catch (e: ActivityNotFoundException) {
toast(org.fossify.commons.R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
private fun openFile() {
FilePickerDialog(this, canAddShowHiddenButton = true) {
checkFile(it, true) {
ensureBackgroundThread {
val fileText = it.readText().trim()
val checklistItems = fileText.parseChecklistItems()
if (checklistItems != null) {
val title = it.absolutePath.getFilenameFromPath().substringBeforeLast('.')
val note = Note(
id = null,
title = title,
value = fileText,
type = NoteType.TYPE_CHECKLIST,
path = "",
protectionType = PROTECTION_NONE,
protectionHash = ""
)
runOnUiThread {
OpenFileDialog(this, it.path) {
displayNewNoteDialog(
note.value,
title = it.title,
it.path,
setChecklistAsDefault = true
)
}
}
} else {
runOnUiThread {
OpenFileDialog(this, it.path) {
displayNewNoteDialog(
value = it.value,
title = it.title,
path = it.path
)
}
}
}
}
}
}
}
private fun checkFile(
path: String,
checkTitle: Boolean,
onChecksPassed: (file: File) -> Unit,
) {
val file = File(path)
if (path.isMediaFile()) {
toast(org.fossify.commons.R.string.invalid_file_format)
} else if (file.length() > 1000 * 1000) {
toast(R.string.file_too_large)
} else if (checkTitle && mNotes.any { it.title.equals(path.getFilenameFromPath(), true) }) {
toast(R.string.title_taken)
} else {
onChecksPassed(file)
}
}
private fun checkUri(uri: Uri, onChecksPassed: () -> Unit) {
try {
contentResolver.openInputStream(uri)?.use { inputStream ->
if (inputStream.available() > 1000 * 1000) {
toast(R.string.file_too_large)
} else {
onChecksPassed()
}
} ?: return
} catch (e: Exception) {
showErrorToast(e)
}
}
private fun openFolder(path: String, onChecksPassed: (file: File) -> Unit) {
val file = File(path)
if (file.isDirectory) {
onChecksPassed(file)
}
}
private fun importUri(uri: Uri) {
when (uri.scheme) {
"file" -> openPath(uri.path!!)
"content" -> {
val realPath = getRealPathFromURI(uri)
if (hasPermission(PERMISSION_READ_STORAGE)) {
if (realPath != null) {
openPath(realPath)
} else {
org.fossify.commons.R.string.unknown_error_occurred
}
} else if (realPath != null && realPath != "") {
checkFile(realPath, false) {
addNoteFromUri(uri, realPath.getFilenameFromPath())
}
} else {
checkUri(uri) {
addNoteFromUri(uri)
}
}
}
}
}
private fun addNoteFromUri(uri: Uri, filename: String? = null) {
val noteTitle = when {
filename?.isEmpty() == false -> filename
uri.toString().startsWith("content://") -> getFilenameFromContentUri(uri)
?: getNewNoteTitle()
else -> getNewNoteTitle()
}
val inputStream = contentResolver.openInputStream(uri)
val content = inputStream?.bufferedReader().use { it!!.readText() }
val checklistItems = content.parseChecklistItems()
// if we got here by some other app invoking the file open intent, we have no permission for updating the original file itself
// we can do it only after using "Export as file" or "Open file" from our app
val canSyncNoteWithFile = if (hasPermission(PERMISSION_WRITE_STORAGE)) {
true
} else {
try {
val takeFlags = FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(uri, takeFlags)
true
} catch (e: Exception) {
false
}
}
val noteType = if (checklistItems != null) NoteType.TYPE_CHECKLIST else NoteType.TYPE_TEXT
if (!canSyncNoteWithFile) {
val note = Note(
id = null,
title = noteTitle,
value = content,
type = noteType,
path = "",
protectionType = PROTECTION_NONE,
protectionHash = ""
)
displayNewNoteDialog(note.value, title = noteTitle, "")
} else {
val items = arrayListOf(
RadioItem(IMPORT_FILE_SYNC, getString(R.string.update_file_at_note)),
RadioItem(IMPORT_FILE_NO_SYNC, getString(R.string.only_import_file_content))
)
RadioGroupDialog(this, items) {
val syncFile = it as Int == IMPORT_FILE_SYNC
val path = if (syncFile) uri.toString() else ""
val note = Note(
id = null,
title = noteTitle,
value = content,