forked from ankidroid/Anki-Android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoteEditor.kt
More file actions
2284 lines (2116 loc) · 95.7 KB
/
NoteEditor.kt
File metadata and controls
2284 lines (2116 loc) · 95.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
/***************************************************************************************
* *
* Copyright (c) 2012 Norbert Nagold <norbert.nagold@gmail.com> *
* Copyright (c) 2014 Timothy Rae <perceptualchaos2@gmail.com> *
* *
* 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 com.ichi2.anki
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.*
import android.view.View.OnFocusChangeListener
import android.view.ViewGroup.MarginLayoutParams
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import androidx.activity.addCallback
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.view.menu.MenuBuilder
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.PopupMenu
import androidx.appcompat.widget.TooltipCompat
import androidx.core.content.IntentCompat
import androidx.core.content.edit
import androidx.core.content.res.ResourcesCompat
import androidx.core.text.HtmlCompat
import anki.config.ConfigKey
import anki.notetypes.StockNotetype
import com.google.android.material.color.MaterialColors
import com.google.android.material.snackbar.Snackbar
import com.ichi2.anim.ActivityTransitionAnimation
import com.ichi2.anim.ActivityTransitionAnimation.Direction.*
import com.ichi2.anki.CollectionManager.TR
import com.ichi2.anki.dialogs.ConfirmationDialog
import com.ichi2.anki.dialogs.DeckSelectionDialog.DeckSelectionListener
import com.ichi2.anki.dialogs.DeckSelectionDialog.SelectableDeck
import com.ichi2.anki.dialogs.DiscardChangesDialog
import com.ichi2.anki.dialogs.IntegerDialog
import com.ichi2.anki.dialogs.tags.TagsDialog
import com.ichi2.anki.dialogs.tags.TagsDialogFactory
import com.ichi2.anki.dialogs.tags.TagsDialogListener
import com.ichi2.anki.model.CardStateFilter
import com.ichi2.anki.multimediacard.IMultimediaEditableNote
import com.ichi2.anki.multimediacard.activity.MultimediaEditFieldActivity
import com.ichi2.anki.multimediacard.activity.MultimediaEditFieldActivityExtra
import com.ichi2.anki.multimediacard.fields.*
import com.ichi2.anki.multimediacard.impl.MultimediaEditableNote
import com.ichi2.anki.noteeditor.CustomToolbarButton
import com.ichi2.anki.noteeditor.FieldState
import com.ichi2.anki.noteeditor.FieldState.FieldChangeType
import com.ichi2.anki.noteeditor.Toolbar
import com.ichi2.anki.noteeditor.Toolbar.TextFormatListener
import com.ichi2.anki.noteeditor.Toolbar.TextWrapper
import com.ichi2.anki.pages.ImageOcclusion
import com.ichi2.anki.preferences.sharedPrefs
import com.ichi2.anki.receiver.SdCardReceiver
import com.ichi2.anki.servicelayer.LanguageHintService
import com.ichi2.anki.servicelayer.NoteService
import com.ichi2.anki.snackbar.BaseSnackbarBuilderProvider
import com.ichi2.anki.snackbar.SnackbarBuilder
import com.ichi2.anki.snackbar.showSnackbar
import com.ichi2.anki.ui.setupNoteTypeSpinner
import com.ichi2.anki.widgets.DeckDropDownAdapter.SubtitleListener
import com.ichi2.annotations.NeedsTest
import com.ichi2.compat.CompatHelper.Companion.getSerializableCompat
import com.ichi2.libanki.*
import com.ichi2.libanki.Collection
import com.ichi2.libanki.Decks.Companion.CURRENT_DECK
import com.ichi2.libanki.Note.ClozeUtils
import com.ichi2.libanki.Note.DupeOrEmpty
import com.ichi2.libanki.Notetypes.Companion.NOT_FOUND_NOTE_TYPE
import com.ichi2.libanki.exception.ConfirmModSchemaException
import com.ichi2.utils.*
import com.ichi2.widget.WidgetStatus
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import timber.log.Timber
import java.util.*
import java.util.function.Consumer
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
/**
* Allows the user to edit a note, for instance if there is a typo. A card is a presentation of a note, and has two
* sides: a question and an answer. Any number of fields can appear on each side. When you add a note to Anki, cards
* which show that note are generated. Some models generate one card, others generate more than one.
*
* @see [the Anki Desktop manual](https://docs.ankiweb.net/getting-started.html.cards)
*/
@KotlinCleanup("Go through the class and select elements to fix")
@KotlinCleanup("see if we can lateinit")
class NoteEditor : AnkiActivity(), DeckSelectionListener, SubtitleListener, TagsDialogListener, BaseSnackbarBuilderProvider {
/** Whether any change are saved. E.g. multimedia, new card added, field changed and saved. */
private var changed = false
private var isTagsEdited = false
private var isFieldEdited = false
/**
* Flag which forces the calling activity to rebuild it's definition of current card from scratch
*/
private var mReloadRequired = false
/**
* Broadcast that informs us when the sd card is about to be unmounted
*/
private var mUnmountReceiver: BroadcastReceiver? = null
private var mFieldsLayoutContainer: LinearLayout? = null
private var mMediaRegistration: MediaRegistration? = null
private var mTagsDialogFactory: TagsDialogFactory? = null
private var mTagsButton: AppCompatButton? = null
private var mCardsButton: AppCompatButton? = null
private var mNoteTypeSpinner: Spinner? = null
private var mDeckSpinnerSelection: DeckSpinnerSelection? = null
// non-null after onCollectionLoaded
private var mEditorNote: Note? = null
/* Null if adding a new card. Presently NonNull if editing an existing note - but this is subject to change */
private var mCurrentEditedCard: Card? = null
private var mSelectedTags: ArrayList<String>? = null
@get:VisibleForTesting
var deckId: DeckId = 0
private set
private var mAllModelIds: List<Long>? = null
@KotlinCleanup("this ideally should be Int, Int?")
private var mModelChangeFieldMap: MutableMap<Int, Int>? = null
private var mModelChangeCardMap: HashMap<Int, Int?>? = null
private val mCustomViewIds = ArrayList<Int>()
/* indicates if a new note is added or a card is edited */
private var addNote = false
private var aedictIntent = false
/* indicates which activity called Note Editor */
private var caller = 0
private var mEditFields: LinkedList<FieldEditText?>? = null
private var sourceText: Array<String?>? = null
private val mFieldState = FieldState.fromEditor(this)
private lateinit var toolbar: Toolbar
// Use the same HTML if the same image is pasted multiple times.
private var mPastedImageCache: HashMap<String, String> = HashMap()
// save field index as key and text as value when toggle sticky clicked in Field Edit Text
private var mToggleStickyText: HashMap<Int, String?> = HashMap()
private val mOnboarding = Onboarding.NoteEditor(this)
private val requestAddLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult(),
NoteEditorActivityResultCallback {
if (it.resultCode != RESULT_CANCELED) {
changed = true
}
}
)
private val requestMultiMediaEditLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult(),
@NeedsTest("test to guard against changes in the REQUEST_MULTIMEDIA_EDIT clause preventing text fields to be updated")
NoteEditorActivityResultCallback { result ->
if (result.resultCode != RESULT_CANCELED) {
val col = getColUnsafe
val extras = result.data!!.extras ?: return@NoteEditorActivityResultCallback
val index = extras.getInt(MultimediaEditFieldActivity.EXTRA_RESULT_FIELD_INDEX)
val field = extras.getSerializableCompat<IField>(MultimediaEditFieldActivity.EXTRA_RESULT_FIELD) ?: return@NoteEditorActivityResultCallback
if (field.type != EFieldType.TEXT && (field.imagePath == null && field.audioPath == null)) {
Timber.i("field imagePath and audioPath are both null")
return@NoteEditorActivityResultCallback
}
val note = getCurrentMultimediaEditableNote(col)
note.setField(index, field)
val fieldEditText = mEditFields!![index]
// Import field media
// This goes before setting formattedValue to update
// media paths with the checksum when they have the same name
NoteService.importMediaToDirectory(col, field)
// Completely replace text for text fields (because current text was passed in)
val formattedValue = field.formattedValue
if (field.type === EFieldType.TEXT) {
fieldEditText!!.setText(formattedValue)
} else if (fieldEditText!!.text != null) {
insertStringInField(fieldEditText, formattedValue)
}
changed = true
}
}
)
private val requestTemplateEditLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult(),
NoteEditorActivityResultCallback {
// Model can change regardless of exit type - update ourselves and CardBrowser
mReloadRequired = true
mEditorNote!!.reloadModel()
if (mCurrentEditedCard == null || !mEditorNote!!.cids()
.contains(mCurrentEditedCard!!.id)
) {
if (!addNote) {
/* This can occur, for example, if the
* card type was deleted or if the note
* type was changed without moving this
* card to another type. */
Timber.d("onActivityResult() template edit return - current card is gone, close note editor")
showSnackbar(getString(R.string.template_for_current_card_deleted))
closeNoteEditor()
} else {
Timber.d("onActivityResult() template edit return, in add mode, just re-display")
}
} else {
Timber.d("onActivityResult() template edit return - current card exists")
// reload current card - the template ordinals are possibly different post-edit
mCurrentEditedCard = getColUnsafe.getCard(mCurrentEditedCard!!.id)
updateCards(mEditorNote!!.notetype)
}
}
)
private val requestIOEditorLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult(),
NoteEditorActivityResultCallback { result ->
if (result.resultCode != RESULT_CANCELED) {
ImportUtils.getFileCachedCopy(this@NoteEditor, result.data!!)?.let { path ->
setupImageOcclusionEditor(path)
}
}
}
)
private inner class NoteEditorActivityResultCallback(private val callback: (result: ActivityResult) -> Unit) : ActivityResultCallback<ActivityResult> {
override fun onActivityResult(result: ActivityResult) {
Timber.d("onActivityResult() with result: %s", result.resultCode)
if (result.resultCode == DeckPicker.RESULT_DB_ERROR) {
closeNoteEditor(DeckPicker.RESULT_DB_ERROR, null)
}
callback(result)
}
}
override fun onDeckSelected(deck: SelectableDeck?) {
if (deck == null) {
return
}
deckId = deck.deckId
mDeckSpinnerSelection!!.initializeNoteEditorDeckSpinner()
mDeckSpinnerSelection!!.selectDeckById(deck.deckId, false)
}
override val subtitleText: String
get() = ""
private enum class AddClozeType {
SAME_NUMBER, INCREMENT_NUMBER
}
private fun displayErrorSavingNote() {
val errorMessageId = addNoteErrorResource
showSnackbar(resources.getString(errorMessageId))
}
// COULD_BE_BETTER: We currently don't perform edits inside this class (wat), so we only handle adds.
// Otherwise, display "no cards created".
@get:StringRes
@VisibleForTesting
internal val addNoteErrorResource: Int
get() {
// COULD_BE_BETTER: We currently don't perform edits inside this class (wat), so we only handle adds.
if (isClozeType) {
return R.string.note_editor_no_cloze_delations
}
if (getCurrentFieldText(0).isEmpty()) {
return R.string.note_editor_no_first_field
}
return if (allFieldsHaveContent()) {
R.string.note_editor_no_cards_created_all_fields
} else {
R.string.note_editor_no_cards_created
}
// Otherwise, display "no cards created".
}
override val baseSnackbarBuilder: SnackbarBuilder = {
if (sharedPrefs().getBoolean(PREF_NOTE_EDITOR_SHOW_TOOLBAR, true)) {
anchorView = findViewById<Toolbar>(R.id.editor_toolbar)
}
}
private fun allFieldsHaveContent() = currentFieldStrings.none { it.isNullOrEmpty() }
// ----------------------------------------------------------------------------
// ANDROID METHODS
// ----------------------------------------------------------------------------
@Suppress("UNCHECKED_CAST", "deprecation") // deprecation: getSerializable
@KotlinCleanup("fix suppress")
override fun onCreate(savedInstanceState: Bundle?) {
if (showedActivityFailedScreen(savedInstanceState)) {
return
}
mTagsDialogFactory = TagsDialogFactory(this).attachToActivity<TagsDialogFactory>(this)
mMediaRegistration = MediaRegistration(this)
super.onCreate(savedInstanceState)
mFieldState.setInstanceState(savedInstanceState)
setContentView(R.layout.note_editor)
val intent = intent
if (savedInstanceState != null) {
caller = savedInstanceState.getInt("caller")
addNote = savedInstanceState.getBoolean("addNote")
deckId = savedInstanceState.getLong("did")
mSelectedTags = savedInstanceState.getStringArrayList("tags")
mReloadRequired = savedInstanceState.getBoolean(RELOAD_REQUIRED_EXTRA_KEY)
mPastedImageCache =
savedInstanceState.getSerializable("imageCache") as HashMap<String, String>
mToggleStickyText =
savedInstanceState.getSerializable("toggleSticky") as HashMap<Int, String?>
changed = savedInstanceState.getBoolean(NOTE_CHANGED_EXTRA_KEY)
} else {
caller = intent.getIntExtra(EXTRA_CALLER, CALLER_NO_CALLER)
if (caller == CALLER_NO_CALLER) {
val action = intent.action
if (ACTION_CREATE_FLASHCARD == action || ACTION_CREATE_FLASHCARD_SEND == action || Intent.ACTION_PROCESS_TEXT == action) {
caller = CALLER_NOTEEDITOR_INTENT_ADD
}
}
}
// Set up toolbar
toolbar = findViewById(R.id.editor_toolbar)
toolbar.apply {
formatListener = TextFormatListener { formatter: Toolbar.TextFormatter ->
val currentFocus = currentFocus as? FieldEditText ?: return@TextFormatListener
modifyCurrentSelection(formatter, currentFocus)
}
// Sets the background and icon color of toolbar respectively.
setBackgroundColor(
MaterialColors.getColor(
this@NoteEditor,
R.attr.toolbarBackgroundColor,
0
)
)
setIconColor(MaterialColors.getColor(this@NoteEditor, R.attr.toolbarIconColor, 0))
}
val mainView = findViewById<View>(android.R.id.content)
// Enable toolbar
enableToolbar(mainView)
startLoadingCollection()
mOnboarding.onCreate()
// TODO this callback doesn't handle predictive back navigation!
// see #14678, added to temporarily fix for a bug
onBackPressedDispatcher.addCallback(this) {
Timber.i("NoteEditor:: onBackPressed()")
closeCardEditorWithCheck()
}
}
override fun onSaveInstanceState(savedInstanceState: Bundle) {
addInstanceStateToBundle(savedInstanceState)
super.onSaveInstanceState(savedInstanceState)
}
private fun addInstanceStateToBundle(savedInstanceState: Bundle) {
Timber.i("Saving instance")
savedInstanceState.putInt("caller", caller)
savedInstanceState.putBoolean("addNote", addNote)
savedInstanceState.putLong("did", deckId)
savedInstanceState.putBoolean(NOTE_CHANGED_EXTRA_KEY, changed)
savedInstanceState.putBoolean(RELOAD_REQUIRED_EXTRA_KEY, mReloadRequired)
savedInstanceState.putIntegerArrayList("customViewIds", mCustomViewIds)
savedInstanceState.putSerializable("imageCache", mPastedImageCache)
savedInstanceState.putSerializable("toggleSticky", mToggleStickyText)
if (mSelectedTags == null) {
mSelectedTags = ArrayList(0)
}
savedInstanceState.putStringArrayList("tags", mSelectedTags)
}
private val fieldsAsBundleForPreview: Bundle
get() = NoteService.getFieldsAsBundleForPreview(mEditFields, shouldReplaceNewlines())
// Finish initializing the activity after the collection has been correctly loaded
override fun onCollectionLoaded(col: Collection) {
super.onCollectionLoaded(col)
val intent = intent
Timber.d("NoteEditor() onCollectionLoaded: caller: %d", caller)
registerExternalStorageListener()
mFieldsLayoutContainer = findViewById(R.id.CardEditorEditFieldsLayout)
mTagsButton = findViewById(R.id.CardEditorTagButton)
mCardsButton = findViewById(R.id.CardEditorCardsButton)
mCardsButton!!.setOnClickListener {
Timber.i("NoteEditor:: Cards button pressed. Opening template editor")
showCardTemplateEditor()
}
aedictIntent = false
mCurrentEditedCard = null
when (caller) {
CALLER_NO_CALLER -> {
Timber.e("no caller could be identified, closing")
finish()
return
}
CALLER_REVIEWER_EDIT -> {
mCurrentEditedCard = AbstractFlashcardViewer.editorCard
if (mCurrentEditedCard == null) {
finish()
return
}
mEditorNote = mCurrentEditedCard!!.note()
addNote = false
}
CALLER_STUDYOPTIONS, CALLER_DECKPICKER, CALLER_REVIEWER_ADD, CALLER_CARDBROWSER_ADD, CALLER_NOTEEDITOR ->
addNote =
true
CALLER_CARDBROWSER_EDIT -> {
mCurrentEditedCard = CardBrowser.cardBrowserCard
if (mCurrentEditedCard == null) {
finish()
return
}
mEditorNote = mCurrentEditedCard!!.note()
addNote = false
}
CALLER_NOTEEDITOR_INTENT_ADD -> {
fetchIntentInformation(intent)
if (sourceText == null) {
finish()
return
}
if ("Aedict Notepad" == sourceText!![0] && addFromAedict(sourceText!![1])) {
finish()
return
}
addNote = true
}
else -> {}
}
col.backend.addImageOcclusionNotetype()
val imageOcclusionButton: Button = findViewById(R.id.ImageOcclusionButton)
if (addNote) {
imageOcclusionButton.setText(R.string.select_image)
imageOcclusionButton.setOnClickListener {
val i = Intent()
i.type = "image/*"
i.action = Intent.ACTION_GET_CONTENT
i.addCategory(Intent.CATEGORY_OPENABLE)
launchActivityForResultWithAnimation(Intent.createChooser(i, resources.getString(R.string.select_image)), requestIOEditorLauncher, START)
}
} else {
imageOcclusionButton.setText(R.string.edit_occlusions)
imageOcclusionButton.setOnClickListener {
setupImageOcclusionEditor()
}
}
// Note type Selector
mNoteTypeSpinner = findViewById(R.id.note_type_spinner)
mAllModelIds = setupNoteTypeSpinner(this, mNoteTypeSpinner!!, col)
// Deck Selector
val deckTextView = findViewById<TextView>(R.id.CardEditorDeckText)
// If edit mode and more than one card template distinguish between "Deck" and "Card deck"
if (!addNote && mEditorNote!!.notetype.getJSONArray("tmpls").length() > 1) {
deckTextView.setText(R.string.CardEditorCardDeck)
}
mDeckSpinnerSelection =
DeckSpinnerSelection(
this,
col,
findViewById(R.id.note_deck_spinner),
showAllDecks = false,
alwaysShowDefault = true,
showFilteredDecks = false
)
mDeckSpinnerSelection!!.initializeNoteEditorDeckSpinner()
deckId = intent.getLongExtra(EXTRA_DID, deckId)
val getTextFromSearchView = intent.getStringExtra(EXTRA_TEXT_FROM_SEARCH_VIEW)
setDid(mEditorNote)
setNote(mEditorNote, FieldChangeType.onActivityCreation(shouldReplaceNewlines()))
if (addNote) {
mNoteTypeSpinner!!.onItemSelectedListener = SetNoteTypeListener()
setTitle(R.string.menu_add)
// set information transferred by intent
var contents: String? = null
val tags = intent.getStringArrayExtra(EXTRA_TAGS)
if (sourceText != null) {
if (aedictIntent && mEditFields!!.size == 3 && sourceText!![1]!!.contains("[")) {
contents = sourceText!![1]!!
.replaceFirst("\\[".toRegex(), "\u001f" + sourceText!![0] + "\u001f")
contents = contents.substring(0, contents.length - 1)
} else if (!mEditFields!!.isEmpty()) {
mEditFields!![0]!!.setText(sourceText!![0])
if (mEditFields!!.size > 1) {
mEditFields!![1]!!.setText(sourceText!![1])
}
}
} else {
contents = intent.getStringExtra(EXTRA_CONTENTS)
}
contents?.let { setEditFieldTexts(it) }
tags?.let { setTags(it) }
} else {
mNoteTypeSpinner!!.onItemSelectedListener = EditNoteTypeListener()
setTitle(R.string.cardeditor_title_edit_card)
}
findViewById<View>(R.id.CardEditorTagButton).setOnClickListener {
Timber.i("NoteEditor:: Tags button pressed... opening tags editor")
showTagsDialog()
}
if (!addNote && mCurrentEditedCard != null) {
Timber.i(
"onCollectionLoaded() Edit note activity successfully started with card id %d",
mCurrentEditedCard!!.id
)
}
if (addNote) {
Timber.i(
"onCollectionLoaded() Edit note activity successfully started in add card mode with node id %d",
mEditorNote!!.id
)
}
// don't open keyboard if not adding note
if (!addNote) {
this.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
}
// set focus to FieldEditText 'first' on startup like Anki desktop
if (mEditFields != null && !mEditFields!!.isEmpty()) {
// EXTRA_TEXT_FROM_SEARCH_VIEW takes priority over other intent inputs
if (getTextFromSearchView != null && getTextFromSearchView.isNotEmpty()) {
mEditFields!!.first!!.setText(getTextFromSearchView)
}
mEditFields!!.first!!.requestFocus()
}
}
private fun modifyCurrentSelection(formatter: Toolbar.TextFormatter, textBox: FieldEditText) {
// get the current text and selection locations
val selectionStart = textBox.selectionStart
val selectionEnd = textBox.selectionEnd
// #6762 values are reversed if using a keyboard and pressing Ctrl+Shift+LeftArrow
val start = min(selectionStart, selectionEnd)
val end = max(selectionStart, selectionEnd)
val text = textBox.text?.toString() ?: ""
// Split the text in the places where the formatting will take place
val beforeText = text.substring(0, start)
val selectedText = text.substring(start, end)
val afterText = text.substring(end)
val (newText, newStart, newEnd) = formatter.format(selectedText)
// Update text field with updated text and selection
val length = beforeText.length + newText.length + afterText.length
val newFieldContent =
StringBuilder(length).append(beforeText).append(newText).append(afterText)
textBox.setText(newFieldContent)
textBox.setSelection(start + newStart, start + newEnd)
}
override fun onStop() {
super.onStop()
if (!isFinishing) {
WidgetStatus.updateInBackground(this)
}
}
@KotlinCleanup("convert KeyUtils to extension functions")
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
if (toolbar.onKeyUp(keyCode, event)) {
return true
}
when (keyCode) {
KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent.KEYCODE_ENTER -> if (event.isCtrlPressed) {
launchCatchingTask { saveNote() }
}
KeyEvent.KEYCODE_D -> // null check in case Spinner is moved into options menu in the future
if (event.isCtrlPressed) {
mDeckSpinnerSelection!!.displayDeckSelectionDialog(getColUnsafe)
}
KeyEvent.KEYCODE_L -> if (event.isCtrlPressed) {
showCardTemplateEditor()
}
KeyEvent.KEYCODE_N -> if (event.isCtrlPressed && mNoteTypeSpinner != null) {
mNoteTypeSpinner!!.performClick()
}
KeyEvent.KEYCODE_T -> if (event.isCtrlPressed && event.isShiftPressed) {
showTagsDialog()
}
KeyEvent.KEYCODE_C -> {
if (event.isCtrlPressed && event.isShiftPressed) {
insertCloze(if (event.isAltPressed) AddClozeType.SAME_NUMBER else AddClozeType.INCREMENT_NUMBER)
// Anki Desktop warns, but still inserts the cloze
if (!isClozeType) {
showSnackbar(R.string.note_editor_insert_cloze_no_cloze_note_type)
}
}
}
KeyEvent.KEYCODE_P -> {
if (event.isCtrlPressed) {
Timber.i("Ctrl+P: Preview Pressed")
performPreview()
}
}
else -> {}
}
// 7573: Ctrl+Shift+[Num] to select a field
if (event.isCtrlPressed && event.isShiftPressed && KeyUtils.isDigit(event)) {
val digit = KeyUtils.getDigit(event)
// map: '0' -> 9; '1' to 0
val indexBase10 = ((digit - 1) % 10 + 10) % 10
selectFieldIndex(indexBase10)
}
return super.onKeyUp(keyCode, event)
}
private fun selectFieldIndex(index: Int) {
Timber.i("Selecting field index %d", index)
if (mEditFields!!.size <= index || index < 0) {
Timber.i("Index out of range: %d", index)
return
}
val field: FieldEditText? = try {
mEditFields!![index]
} catch (e: IndexOutOfBoundsException) {
Timber.w(e, "Error selecting index %d", index)
return
}
field!!.requestFocus()
Timber.d("Selected field")
}
private fun insertCloze(addClozeType: AddClozeType) {
val v = currentFocus as? FieldEditText ?: return
convertSelectedTextToCloze(v, addClozeType)
}
private fun fetchIntentInformation(intent: Intent) {
val extras = intent.extras ?: return
sourceText = arrayOfNulls(2)
if (Intent.ACTION_PROCESS_TEXT == intent.action) {
val stringExtra = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT)
Timber.d("Obtained %s from intent: %s", stringExtra, Intent.EXTRA_PROCESS_TEXT)
sourceText!![0] = stringExtra ?: ""
sourceText!![1] = ""
} else if (ACTION_CREATE_FLASHCARD == intent.action) {
// mSourceLanguage = extras.getString(SOURCE_LANGUAGE);
// mTargetLanguage = extras.getString(TARGET_LANGUAGE);
sourceText!![0] = extras.getString(SOURCE_TEXT)
sourceText!![1] = extras.getString(TARGET_TEXT)
} else {
var first: String?
var second: String?
first = if (extras.getString(Intent.EXTRA_SUBJECT) != null) {
extras.getString(Intent.EXTRA_SUBJECT)
} else {
""
}
second = if (extras.getString(Intent.EXTRA_TEXT) != null) {
extras.getString(Intent.EXTRA_TEXT)
} else {
""
}
// Some users add cards via SEND intent from clipboard. In this case SUBJECT is empty
if ("" == first) {
// Assume that if only one field was sent then it should be the front
first = second
second = ""
}
val messages = Pair(first, second)
sourceText!![0] = messages.first
sourceText!![1] = messages.second
}
}
private fun addFromAedict(extra_text: String?): Boolean {
var category: String
val notepadLines = extra_text!!.split("\n".toRegex()).toTypedArray()
for (i in notepadLines.indices) {
if (notepadLines[i].startsWith("[") && notepadLines[i].endsWith("]")) {
category = notepadLines[i].substring(1, notepadLines[i].length - 1)
if ("default" == category) {
if (notepadLines.size > i + 1) {
val entryLines = notepadLines[i + 1].split(":".toRegex()).toTypedArray()
if (entryLines.size > 1) {
sourceText!![0] = entryLines[1]
sourceText!![1] = entryLines[0]
aedictIntent = true
return false
}
}
showSnackbar(resources.getString(R.string.intent_aedict_empty))
return true
}
}
}
showSnackbar(resources.getString(R.string.intent_aedict_category))
return true
}
private fun hasUnsavedChanges(): Boolean {
if (!collectionHasLoaded()) {
return false
}
// changed note type?
if (!addNote && mCurrentEditedCard != null) {
val newModel: JSONObject? = currentlySelectedNotetype
val oldModel: JSONObject = mCurrentEditedCard!!.model()
if (newModel != oldModel) {
return true
}
}
// changed deck?
if (!addNote && mCurrentEditedCard != null && mCurrentEditedCard!!.did != deckId) {
return true
}
// changed fields?
if (isFieldEdited) {
for (value in mEditFields!!) {
if (value?.text.toString() != "") {
return true
}
}
return false
} else {
return isTagsEdited
}
// changed tags?
}
private fun collectionHasLoaded(): Boolean {
return mAllModelIds != null
}
// ----------------------------------------------------------------------------
// SAVE NOTE METHODS
// ----------------------------------------------------------------------------
/**
* @param noOfAddedCards
*/
@KotlinCleanup("return early and simplify if possible")
private fun onNoteAdded() {
var closeEditorAfterSave = false
var closeIntent: Intent? = null
changed = true
sourceText = null
refreshNoteData(FieldChangeType.refreshWithStickyFields(shouldReplaceNewlines()))
showSnackbar(TR.addingAdded(), Snackbar.LENGTH_SHORT)
if (caller == CALLER_NOTEEDITOR || aedictIntent) {
closeEditorAfterSave = true
} else if (caller == CALLER_NOTEEDITOR_INTENT_ADD) {
closeEditorAfterSave = true
closeIntent = Intent().apply { putExtra(EXTRA_ID, intent.getStringExtra(EXTRA_ID)) }
} else if (!mEditFields!!.isEmpty()) {
mEditFields!!.first!!.focusWithKeyboard()
}
if (closeEditorAfterSave) {
closeNoteEditor(closeIntent ?: Intent())
} else {
// Reset check for changes to fields
isFieldEdited = false
isTagsEdited = false
}
}
@VisibleForTesting
@NeedsTest("14664: 'first field must not be empty' no longer applies after saving the note")
suspend fun saveNote() {
val res = resources
if (mSelectedTags == null) {
mSelectedTags = ArrayList(0)
}
saveToggleStickyMap()
// treat add new note and edit existing note independently
if (addNote) {
// Different from libAnki, block if there are no cloze deletions.
// DEFECT: This does not block addition if cloze transpositions are in non-cloze fields.
if (isClozeType && !hasClozeDeletions()) {
displayErrorSavingNote()
return
}
if (getCurrentFieldText(0).isEmpty()) {
displayErrorSavingNote()
return
}
// load all of the fields into the note
for (f in mEditFields!!) {
updateField(f)
}
// Save deck to model
mEditorNote!!.notetype.put("did", deckId)
// Save tags to model
mEditorNote!!.setTagsFromStr(tagsAsString(mSelectedTags!!))
val tags = JSONArray()
for (t in mSelectedTags!!) {
tags.put(t)
}
mReloadRequired = true
// adding current note to collection
withProgress(resources.getString(R.string.saving_facts)) {
undoableOp {
notetypes.current().put("tags", tags)
addNote(mEditorNote!!, deckId)
}
}
// update UI based on the result, noOfAddedCards
onNoteAdded()
updateFieldsFromStickyText()
} else {
// Check whether note type has been changed
val newModel = currentlySelectedNotetype
val oldModel = if (mCurrentEditedCard == null) null else mCurrentEditedCard!!.model()
if (newModel != oldModel) {
mReloadRequired = true
if (mModelChangeCardMap!!.size < mEditorNote!!.numberOfCards() || mModelChangeCardMap!!.containsValue(
null
)
) {
// If cards will be lost via the new mapping then show a confirmation dialog before proceeding with the change
val dialog = ConfirmationDialog()
dialog.setArgs(res.getString(R.string.confirm_map_cards_to_nothing))
val confirm = Runnable {
// Bypass the check once the user confirms
changeNoteTypeWithErrorHandling(oldModel, newModel)
}
dialog.setConfirm(confirm)
showDialogFragment(dialog)
} else {
// Otherwise go straight to changing note type
changeNoteTypeWithErrorHandling(oldModel, newModel)
}
return
}
// Regular changes in note content
var modified = false
// changed did? this has to be done first as remFromDyn() involves a direct write to the database
if (mCurrentEditedCard != null && mCurrentEditedCard!!.did != deckId) {
mReloadRequired = true
getColUnsafe.setDeck(listOf(mCurrentEditedCard!!.id), deckId)
// refresh the card object to reflect the database changes from above
mCurrentEditedCard!!.load()
// also reload the note object
mEditorNote = mCurrentEditedCard!!.note()
// then set the card ID to the new deck
mCurrentEditedCard!!.did = deckId
modified = true
}
// now load any changes to the fields from the form
for (f in mEditFields!!) {
modified = modified or updateField(f)
}
// added tag?
for (t in mSelectedTags!!) {
modified = modified || !mEditorNote!!.hasTag(t)
}
// removed tag?
modified = modified || mEditorNote!!.tags.size > mSelectedTags!!.size
if (modified) {
mEditorNote!!.setTagsFromStr(tagsAsString(mSelectedTags!!))
changed = true
}
closeNoteEditor()
}
}
/**
* Change the note type from oldModel to newModel, handling the case where a full sync will be required
*/
private fun changeNoteTypeWithErrorHandling(oldNotetype: NotetypeJson?, newNotetype: NotetypeJson?) {
val res = resources
try {
changeNoteType(oldNotetype, newNotetype)
} catch (e: ConfirmModSchemaException) {
e.log()
// Libanki has determined we should ask the user to confirm first
val dialog = ConfirmationDialog()
dialog.setArgs(res.getString(R.string.full_sync_confirmation))
val confirm = Runnable {
// Bypass the check once the user confirms
getColUnsafe.modSchemaNoCheck()
try {
changeNoteType(oldNotetype, newNotetype)
} catch (e2: ConfirmModSchemaException) {
// This should never be reached as we explicitly called modSchemaNoCheck()
throw RuntimeException(e2)
}
}
dialog.setConfirm(confirm)
showDialogFragment(dialog)
}
}
/**
* Change the note type from oldModel to newModel
* @throws ConfirmModSchemaException If a full sync will be required
*/
@Throws(ConfirmModSchemaException::class)
private fun changeNoteType(oldNotetype: NotetypeJson?, newNotetype: NotetypeJson?) {
val noteId = mEditorNote!!.id
getColUnsafe.notetypes.change(oldNotetype!!, noteId, newNotetype!!, mModelChangeFieldMap!!, mModelChangeCardMap!!)
// refresh the note object to reflect the database changes
mEditorNote!!.load()
// close note editor
closeNoteEditor()
}
override fun onDestroy() {
super.onDestroy()
if (mUnmountReceiver != null) {
unregisterReceiver(mUnmountReceiver)
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
updateToolbar()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.note_editor, menu)
if (addNote) {
menu.findItem(R.id.action_copy_note).isVisible = false
} else {
menu.findItem(R.id.action_add_note_from_note_editor).isVisible = true
}
if (mEditFields != null) {
for (i in mEditFields!!.indices) {
val fieldText = mEditFields!![i]!!.text
if (fieldText != null && fieldText.isNotEmpty()) {
menu.findItem(R.id.action_copy_note).isEnabled = true
break
} else if (i == mEditFields!!.size - 1) {
menu.findItem(R.id.action_copy_note).isEnabled = false
}
}
}
menu.findItem(R.id.action_show_toolbar).isChecked =
!shouldHideToolbar()
menu.findItem(R.id.action_capitalize).isChecked =
this.sharedPrefs().getBoolean(PREF_NOTE_EDITOR_CAPITALIZE, true)
menu.findItem(R.id.action_scroll_toolbar).isChecked =
this.sharedPrefs().getBoolean(PREF_NOTE_EDITOR_SCROLL_TOOLBAR, true)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
Timber.i("NoteEditor:: Home button pressed")
closeCardEditorWithCheck()
return true
}
R.id.action_preview -> {
Timber.i("NoteEditor:: Preview button pressed")
performPreview()
return true
}
R.id.action_save -> {
Timber.i("NoteEditor:: Save note button pressed")
launchCatchingTask { saveNote() }
return true
}
R.id.action_add_note_from_note_editor -> {
Timber.i("NoteEditor:: Add Note button pressed")