forked from ankidroid/Anki-Android
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCardTemplateEditor.kt
More file actions
1641 lines (1489 loc) · 70.3 KB
/
Copy pathCardTemplateEditor.kt
File metadata and controls
1641 lines (1489 loc) · 70.3 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
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Copyright (c) 2014 Timothy Rae <perceptualchaos2@gmail.com>
// SPDX-FileCopyrightText: Copyright (c) 2018 Mike Hardy <mike@mikehardy.net>
package com.ichi2.anki
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.ActionMode
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.CheckResult
import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.AlertDialog
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.core.view.size
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.commitNow
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import anki.notetypes.StockNotetype
import anki.notetypes.StockNotetype.OriginalStockKind.ORIGINAL_STOCK_KIND_UNKNOWN_VALUE
import anki.notetypes.notetypeId
import com.google.android.material.card.MaterialCardView
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.ichi2.anki.CollectionManager.TR
import com.ichi2.anki.CollectionManager.withCol
import com.ichi2.anki.android.input.ShortcutGroup
import com.ichi2.anki.android.input.shortcut
import com.ichi2.anki.cardviewer.SingleCardSide
import com.ichi2.anki.common.android.animationDisabled
import com.ichi2.anki.common.android.appContext
import com.ichi2.anki.common.annotations.NeedsTest
import com.ichi2.anki.common.utils.android.getColorFromAttr
import com.ichi2.anki.common.utils.android.showThemedToast
import com.ichi2.anki.common.utils.annotation.KotlinCleanup
import com.ichi2.anki.compat.CompatHelper.Companion.getSerializableCompat
import com.ichi2.anki.databinding.ActivityCardTemplateEditorBinding
import com.ichi2.anki.databinding.FragmentCardTemplateEditorTemplateBinding
import com.ichi2.anki.databinding.IncludeCardTemplateEditorMainBinding
import com.ichi2.anki.databinding.IncludeCardTemplateEditorTopBinding
import com.ichi2.anki.dialogs.ConfirmationDialog
import com.ichi2.anki.dialogs.DiscardChangesDialog
import com.ichi2.anki.dialogs.InsertFieldDialog
import com.ichi2.anki.dialogs.InsertFieldMetadata
import com.ichi2.anki.dialogs.registerDeckSelectedHandler
import com.ichi2.anki.dialogs.startDeckSelection
import com.ichi2.anki.libanki.CardOrdinal
import com.ichi2.anki.libanki.CardTemplates
import com.ichi2.anki.libanki.Collection
import com.ichi2.anki.libanki.Note
import com.ichi2.anki.libanki.NoteId
import com.ichi2.anki.libanki.NoteTypeId
import com.ichi2.anki.libanki.NotetypeJson
import com.ichi2.anki.libanki.Notetypes
import com.ichi2.anki.libanki.Notetypes.Companion.NOT_FOUND_NOTE_TYPE
import com.ichi2.anki.libanki.exception.ConfirmModSchemaException
import com.ichi2.anki.libanki.getStockNotetype
import com.ichi2.anki.libanki.getStockNotetypeKinds
import com.ichi2.anki.libanki.utils.append
import com.ichi2.anki.model.SelectableDeck
import com.ichi2.anki.notetype.CardTypeName
import com.ichi2.anki.notetype.RenameCardTypeDialog
import com.ichi2.anki.notetype.RepositionCardTemplateDialog
import com.ichi2.anki.observability.undoableOp
import com.ichi2.anki.previewer.TemplatePreviewerArguments
import com.ichi2.anki.previewer.TemplatePreviewerFragment
import com.ichi2.anki.previewer.TemplatePreviewerPage
import com.ichi2.anki.settings.Prefs
import com.ichi2.anki.snackbar.showSnackbar
import com.ichi2.anki.startup.ensureStorageIsReady
import com.ichi2.anki.ui.ResizablePaneManager
import com.ichi2.anki.ui.internationalization.sentenceCase
import com.ichi2.anki.utils.ext.dismissAllDialogFragments
import com.ichi2.anki.utils.ext.doOnTabSelected
import com.ichi2.anki.utils.ext.showDialogFragment
import com.ichi2.anki.utils.postDelayed
import com.ichi2.utils.copyToClipboard
import com.ichi2.utils.dp
import com.ichi2.utils.listItems
import com.ichi2.utils.show
import dev.androidbroadcast.vbpd.viewBinding
import kotlinx.coroutines.launch
import net.ankiweb.rsdroid.Translations
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import timber.log.Timber
import java.util.regex.Pattern
import kotlin.math.max
import kotlin.math.min
import kotlin.time.Duration.Companion.seconds
private typealias BackendCardTemplate = com.ichi2.anki.libanki.CardTemplate
/**
* Allows the user to view the template for the current note type
*/
@KotlinCleanup("lateinit wherever possible")
open class CardTemplateEditor : AnkiActivity(R.layout.activity_card_template_editor) {
private val binding by viewBinding(ActivityCardTemplateEditorBinding::bind)
@VisibleForTesting
val topBinding: IncludeCardTemplateEditorTopBinding
get() = binding.templateEditorTop
@VisibleForTesting
internal val mainBinding: IncludeCardTemplateEditorMainBinding
get() = binding.templateEditor
// TODO: see if it is feasible to use mockk to cause a crash
@VisibleForTesting
var tempNoteType: CardTemplateNotetype? = null
private var fieldNames: List<String>? = null
private var noteTypeId: NoteTypeId = 0
private var noteId: NoteId = 0
/**
* Stores the cursor position for each editor window (front, style, back) within each card template.
* The outer HashMap's key is the card template's ordinal (position).
* The inner HashMap's key is the editor window ID (e.g., R.id.front_edit).
* The value is the cursor position within that editor window.
*/
private var tabToCursorPositions: HashMap<CardOrdinal, HashMap<Int, Int>> = HashMap()
// the current editor view among front/style/back
private var tabToViewId: HashMap<Int, Int?> = HashMap()
private var startingOrdId: CardOrdinal = 0
/**
* The ordinal of the current template being edited
*
* Valid for use in [tempNoteType]
*/
private val ord: Int
get() = mainBinding.cardTemplateEditorPager.currentItem
/**
* If true, the view is split in two. The template editor appears on the leading side and the previewer on the trailing side.
* This occurs when the screen size is large
*/
private var fragmented = false
val displayDiscardChangesCallback =
object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() {
showDiscardChangesDialog()
}
}
/**
* Triggered when a card template ('Card 1') is selected in the top tab view
*/
// ----------------------------------------------------------------------------
// Listeners
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ANDROID METHODS
// ----------------------------------------------------------------------------
override fun onCreate(savedInstanceState: Bundle?) {
if (showedActivityFailedScreen(savedInstanceState)) {
return
}
super.onCreate(savedInstanceState)
if (!ensureStorageIsReady()) {
return
}
// Load the args either from the intent or savedInstanceState bundle
if (savedInstanceState == null) {
// get note type id
noteTypeId = intent.getLongExtra(EDITOR_NOTE_TYPE_ID, NOT_FOUND_NOTE_TYPE)
if (noteTypeId == NOT_FOUND_NOTE_TYPE) {
Timber.e("CardTemplateEditor :: no note type ID was provided")
finish()
return
}
// get id for currently edited note (optional)
noteId = intent.getLongExtra(EDITOR_NOTE_ID, -1L)
// get id for currently edited template (optional)
startingOrdId = intent.getIntExtra(EDITOR_START_ORD_ID, -1)
tabToCursorPositions[0] = hashMapOf()
tabToViewId[0] = R.id.front_edit
} else {
noteTypeId = savedInstanceState.getLong(EDITOR_NOTE_TYPE_ID)
noteId = savedInstanceState.getLong(EDITOR_NOTE_ID)
startingOrdId = savedInstanceState.getInt(EDITOR_START_ORD_ID)
tabToCursorPositions = savedInstanceState.getSerializableCompat<HashMap<Int, HashMap<Int, Int>>>(TAB_TO_CURSOR_POSITION_KEY)!!
tabToViewId = savedInstanceState.getSerializableCompat<HashMap<Int, Int?>>(TAB_TO_VIEW_ID)!!
tempNoteType = CardTemplateNotetype.fromBundle(savedInstanceState)
}
fragmented = binding.fragmentContainer?.isVisible == true
setNavigationBarColor(R.attr.alternativeBackgroundColor)
// Disable the home icon
enableToolbar()
startLoadingCollection()
if (fragmented) {
ResizablePaneManager(
parentLayout = requireNotNull(binding.cardTemplateEditorXlView) { "cardTemplateEditorXlView" },
divider = requireNotNull(binding.cardTemplateEditorResizingDivider) { "cardTemplateEditorResizingDivider" },
leftPane = requireNotNull(binding.templateEditor.root) { "templateEditor.root" },
rightPane = requireNotNull(binding.fragmentContainer) { "fragmentContainer" },
sharedPrefs = Prefs.getUiConfig(this),
leftPaneWeightKey = PREF_TEMPLATE_EDITOR_PANE_WEIGHT,
rightPaneWeightKey = PREF_TEMPLATE_PREVIEWER_PANE_WEIGHT,
)
}
// Open TemplatePreviewerFragment if in fragmented mode
loadTemplatePreviewerFragmentIfFragmented()
onBackPressedDispatcher.addCallback(this, displayDiscardChangesCallback)
topBinding.slidingTabs.doOnTabSelected { tab ->
Timber.i("selected card index: %s", tab.position)
loadTemplatePreviewerFragmentIfFragmented(tab.position)
}
registerDeckSelectedHandler(action = ::onDeckSelected)
}
/**
* Loads or reloads [tempNoteType] in [R.id.fragment_container] if the view is fragmented. Do nothing otherwise.
*/
private fun loadTemplatePreviewerFragmentIfFragmented(ord: CardOrdinal = mainBinding.cardTemplateEditorPager.currentItem) {
if (!fragmented) {
return
}
launchCatchingTask {
val notetype = tempNoteType!!.notetype
val notetypeFile = NotetypeFile(this@CardTemplateEditor, notetype)
val note = withCol { currentFragment?.getNote(this) ?: Note.fromNotetypeId(this@withCol, notetype.id) }
val args =
TemplatePreviewerArguments(
notetypeFile = notetypeFile,
id = note.id,
ord = ord,
fields = note.fields,
tags = note.tags,
fillEmpty = true,
)
val fragment = TemplatePreviewerFragment.newInstance(args)
supportFragmentManager.commitNow {
replace(R.id.fragment_container, fragment)
}
// Modify the "Show Answer" button height to 80dp to maintain visual consistency with the BottomNavigationView,
// which has a default height of 80dp.
fragment.view?.post {
fragment.binding.showAnswer.let { button ->
button.layoutParams.height = 80.dp.toPx(button.context)
button.requestLayout()
}
// Adjust the top margin of the webview container to match template editor top margin
fragment.binding.webViewContainer.let { container ->
val params = container.layoutParams as ViewGroup.MarginLayoutParams
val topMargin = resources.getDimensionPixelSize(R.dimen.reviewer_side_margin)
params.topMargin = topMargin
container.layoutParams = params
}
}
}
}
public override fun onSaveInstanceState(outState: Bundle) {
with(outState) {
tempNoteType?.let { putAll(it.toBundle()) }
putLong(EDITOR_NOTE_TYPE_ID, noteTypeId)
putLong(EDITOR_NOTE_ID, noteId)
putInt(EDITOR_START_ORD_ID, startingOrdId)
putSerializable(TAB_TO_VIEW_ID, tabToViewId)
putSerializable(TAB_TO_CURSOR_POSITION_KEY, tabToCursorPositions)
super.onSaveInstanceState(this)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressedDispatcher.onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
/**
* Callback used to finish initializing the activity after the collection has been correctly loaded
* @param col Collection which has been loaded
*/
override fun onCollectionLoaded(col: Collection) {
super.onCollectionLoaded(col)
// without this call the editor doesn't see the latest changes to notetypes, see #16630
@NeedsTest("Add test to check that renaming notetypes in ManageNotetypes is seen in CardTemplateEditor(#16630)")
col.notetypes.clearCache()
// The first time the activity loads it has a model id but no edits yet, so no edited model
// take the passed model id load it up for editing
if (tempNoteType == null) {
tempNoteType = CardTemplateNotetype(col.notetypes.get(noteTypeId)!!.deepClone())
// Timber.d("onCollectionLoaded() model is %s", mTempModel.getModel().toString(2));
}
fieldNames = tempNoteType!!.notetype.fieldsNames
// Set up the ViewPager with the sections adapter.
mainBinding.cardTemplateEditorPager.adapter = TemplatePagerAdapter(this@CardTemplateEditor)
// Keep more fragments in memory to reduce menu flickering during tab switches (issue #18555).
// When switching between non-adjacent tabs, ViewPager2's default behavior destroys fragments,
// causing their MenuProviders to fire and create visual flicker.
// Capped at 7 (keeping up to 15 fragments total) to balance flicker reduction with memory usage,
// as templates can contain large content (JS bundles, CSS frameworks, etc.).
mainBinding.cardTemplateEditorPager.offscreenPageLimit = 7
TabLayoutMediator(
topBinding.slidingTabs,
mainBinding.cardTemplateEditorPager,
) { tab: TabLayout.Tab, position: Int ->
tab.text = tempNoteType!!.getTemplate(position).name
}.apply { attach() }
// Set activity title
supportActionBar?.let {
it.setTitle(R.string.title_activity_template_editor)
it.subtitle = tempNoteType!!.notetype.name
}
// Close collection opening dialog if needed
Timber.i("CardTemplateEditor:: Card template editor successfully started for note type id %d", noteTypeId)
// Set the tab to the current template if an ord id was provided
Timber.d("Setting starting tab to %d", startingOrdId)
if (startingOrdId != -1) {
mainBinding.cardTemplateEditorPager.setCurrentItem(startingOrdId, animationDisabled())
}
}
fun noteTypeHasChanged(): Boolean {
val oldNoteType: NotetypeJson? = getColUnsafe.notetypes.get(noteTypeId)
return tempNoteType != null && tempNoteType!!.notetype.toString() != oldNoteType.toString()
}
private fun enableDiscardChangesDialog() {
displayDiscardChangesCallback.isEnabled = noteTypeHasChanged()
}
private fun showDiscardChangesDialog() =
DiscardChangesDialog.showDialog(this) {
Timber.i("TemplateEditor:: OK button pressed to confirm discard changes")
// Clear the edited note type from any cache files, and clear it from this objects memory to discard changes
CardTemplateNotetype.clearTempNoteTypeFiles()
tempNoteType = null
finish()
}
/** When a deck is selected via Deck Override */
fun onDeckSelected(deck: SelectableDeck?) {
require(deck is SelectableDeck.Deck?)
if (tempNoteType!!.notetype.isCloze) {
Timber.w("Attempted to set deck for cloze note type")
showSnackbar(getString(R.string.multimedia_editor_something_wrong), Snackbar.LENGTH_SHORT)
return
}
val template = tempNoteType!!.getTemplate(ord)
val templateName = template.name
if (deck != null && getColUnsafe.decks.isFiltered(deck.deckId)) {
Timber.w("Attempted to set default deck of %s to dynamic deck %s", templateName, deck.name)
showSnackbar(getString(R.string.multimedia_editor_something_wrong), Snackbar.LENGTH_SHORT)
return
}
val message: String =
if (deck == null) {
Timber.i("Removing default template from template '%s'", templateName)
template.jsonObject.put("did", JSONObject.NULL)
getString(R.string.model_manager_deck_override_removed_message, templateName)
} else {
Timber.i("Setting template '%s' to '%s'", templateName, deck.name)
template.jsonObject.put("did", deck.deckId)
getString(R.string.model_manager_deck_override_added_message, templateName, deck.name)
}
showSnackbar(message, Snackbar.LENGTH_SHORT)
// Deck Override can change from "on" <-> "off"
invalidateOptionsMenu()
enableDiscardChangesDialog()
}
override fun onKeyUp(
keyCode: Int,
event: KeyEvent,
): Boolean {
val currentFragment = currentFragment ?: return super.onKeyUp(keyCode, event)
if (!event.isCtrlPressed) {
return super.onKeyUp(keyCode, event)
}
when (keyCode) {
KeyEvent.KEYCODE_P -> {
Timber.i("Ctrl+P: Perform preview from keypress")
currentFragment.performPreview()
}
KeyEvent.KEYCODE_1 -> {
Timber.i("Ctrl+1: Edit front template from keypress")
currentFragment.binding.bottomNavigation.selectedItemId = R.id.front_edit
}
KeyEvent.KEYCODE_2 -> {
Timber.i("Ctrl+2: Edit back template from keypress")
currentFragment.binding.bottomNavigation.selectedItemId = R.id.back_edit
}
KeyEvent.KEYCODE_3 -> {
Timber.i("Ctrl+3: Edit styling from keypress")
currentFragment.binding.bottomNavigation.selectedItemId = R.id.styling_edit
}
KeyEvent.KEYCODE_S -> {
Timber.i("Ctrl+S: Save note from keypress")
currentFragment.saveNoteType()
}
KeyEvent.KEYCODE_I -> {
Timber.i("Ctrl+I: Insert field from keypress")
currentFragment.showInsertFieldDialog()
}
KeyEvent.KEYCODE_N -> {
Timber.i("Ctrl+N: Add card template from keypress")
currentFragment.addCardTemplate()
}
KeyEvent.KEYCODE_R -> {
Timber.i("Ctrl+R: Rename card from keypress")
currentFragment.showRenameDialog()
}
KeyEvent.KEYCODE_B -> {
Timber.i("Ctrl+B: Open browser appearance from keypress")
currentFragment.openBrowserAppearance()
}
KeyEvent.KEYCODE_D -> {
Timber.i("Ctrl+D: Delete card from keypress")
currentFragment.deleteCardTemplate()
}
KeyEvent.KEYCODE_O -> {
Timber.i("Ctrl+O: Display deck override dialog from keypress")
currentFragment.displayDeckOverrideDialog(currentFragment.tempModel)
}
KeyEvent.KEYCODE_M -> {
Timber.i("Ctrl+M: Copy markdown from keypress")
currentFragment.copyMarkdownTemplateToClipboard()
}
else -> {
return super.onKeyUp(keyCode, event)
}
}
// We reach this only if we didn't reach the `else` case.
return true
}
@get:VisibleForTesting
val currentFragment: CardTemplateFragment?
get() =
try {
supportFragmentManager.findFragmentByTag("f" + ord) as CardTemplateFragment?
} catch (e: Exception) {
Timber.w("Failed to get current fragment")
null
}
// ----------------------------------------------------------------------------
// INNER CLASSES
// ----------------------------------------------------------------------------
/**
* A [androidx.viewpager2.adapter.FragmentStateAdapter] that returns a fragment corresponding to
* one of the tabs.
*/
inner class TemplatePagerAdapter(
fragmentActivity: FragmentActivity,
) : FragmentStateAdapter(fragmentActivity) {
private var baseId: Long = 0
override fun createFragment(position: Int): Fragment {
val editorViewId = tabToViewId[position] ?: R.id.front_edit
return CardTemplateFragment.newInstance(position, noteId, editorViewId)
}
override fun getItemCount(): Int = tempNoteType?.templateCount ?: 0
override fun getItemId(position: Int): Long = baseId + position
override fun containsItem(id: Long): Boolean {
@Suppress("ConvertTwoComparisonsToRangeCheck") // more readable without the range check
return (id - baseId < itemCount) && (id - baseId >= 0)
}
/** Force fragments to reinitialize contents by invalidating previous set of ordinal-based ids */
fun ordinalShift() {
baseId += (itemCount + 1).toLong()
}
}
override val shortcuts
get() =
ShortcutGroup(
listOf(
shortcut("Ctrl+P", R.string.card_editor_preview_card),
shortcut("Ctrl+1", R.string.edit_front_template),
shortcut("Ctrl+2", R.string.edit_back_template),
shortcut("Ctrl+3", R.string.edit_styling),
shortcut("Ctrl+S", R.string.save),
shortcut("Ctrl+I", R.string.card_template_editor_insert_field),
shortcut("Ctrl+A", Translations::cardTemplatesAddCardType),
shortcut("Ctrl+R", Translations::cardTemplatesRenameCardType),
shortcut("Ctrl+B", R.string.edit_browser_appearance),
shortcut("Ctrl+D", Translations::cardTemplatesRemoveCardType),
shortcut("Ctrl+O", Translations::cardTemplatesDeckOverride),
shortcut("Ctrl+M", R.string.copy_the_template),
),
R.string.card_template_editor_group,
)
class CardTemplateFragment : Fragment(R.layout.fragment_card_template_editor_template) {
@VisibleForTesting
internal val binding by viewBinding(FragmentCardTemplateEditorTemplateBinding::bind)
private val refreshFragmentHandler = Handler(Looper.getMainLooper())
// Index of this card template fragment in ViewPager
private val cardIndex
get() = requireArguments().getInt(CARD_INDEX)
private val templateName
get() = tempModel.notetype.templates[cardIndex].name
val insertFieldRequestKey
get() = "request_field_insert_$cardIndex"
var currentEditorViewId = 0
private val currentEditTab: EditTab?
get() =
when (currentEditorViewId) {
R.id.front_edit -> EditTab.FRONT
R.id.back_edit -> EditTab.BACK
R.id.styling_edit -> EditTab.STYLING
else -> null
}
private lateinit var templateEditor: CardTemplateEditor
lateinit var tempModel: CardTemplateNotetype
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?,
) {
// Storing a reference to the templateEditor allows us to use member variables
templateEditor = activity as CardTemplateEditor
tempModel = templateEditor.tempNoteType!!
// Load template
val template: BackendCardTemplate =
try {
tempModel.getTemplate(cardIndex)
} catch (e: JSONException) {
Timber.d(e, "Exception loading template in CardTemplateFragment. Probably stale fragment.")
return
}
// initializing the hash map which stores the cursor position for each editor window
if (templateEditor.tabToCursorPositions[cardIndex] == null) {
templateEditor.tabToCursorPositions[cardIndex] = hashMapOf()
}
binding.editText.customInsertionActionModeCallback = ActionModeCallback()
// If in fragmented mode, wrap the edit area in a MaterialCardView
if (templateEditor.fragmented) {
// Set the background color of the main layout to match the previewer
binding.mainLayout.setBackgroundColor(
getColorFromAttr(
requireContext(),
R.attr.alternativeBackgroundColor,
),
)
// Create a MaterialCardView to wrap the editText
val cardView =
MaterialCardView(requireContext()).apply {
layoutParams =
LinearLayout
.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
0,
1f,
).apply {
val sideMargin = resources.getDimensionPixelSize(R.dimen.reviewer_side_margin)
setMargins(sideMargin, 0, sideMargin, 0)
}
}
// Remove the ScrollView from the main layout and add it to the cardView
binding.mainLayout.removeViewInLayout(binding.scrollView)
cardView.addView(
binding.scrollView,
ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
),
)
binding.mainLayout.addView(cardView, 0)
}
binding.bottomNavigation.menu
.findItem(R.id.front_edit)
.title = TR.notetypesFrontField()
binding.bottomNavigation.menu
.findItem(R.id.styling_edit)
.title = TR.cardTemplatesTemplateStyling()
binding.bottomNavigation.setOnItemSelectedListener { item: MenuItem ->
val currentSelectedId = item.itemId
templateEditor.tabToViewId[cardIndex] = currentSelectedId
Timber.i("selected editor view: %s", item.title)
when (currentSelectedId) {
R.id.styling_edit ->
setCurrentEditorView(
currentSelectedId,
cardIndex,
tempModel.css,
)
R.id.back_edit ->
setCurrentEditorView(
currentSelectedId,
cardIndex,
template.afmt,
)
else -> setCurrentEditorView(currentSelectedId, cardIndex, template.qfmt)
}
// contents of menu have changed and menu should be redrawn
templateEditor.invalidateOptionsMenu()
true
}
// set saved or default view
binding.bottomNavigation.selectedItemId =
templateEditor.tabToViewId[cardIndex] ?: requireArguments().getInt(EDITOR_VIEW_ID_KEY)
// Set text change listeners
val templateEditorWatcher: TextWatcher =
object : TextWatcher {
/**
* Declare a nullable variable refreshFragmentRunnable of type Runnable.
* This will hold a reference to the Runnable that refreshes the previewer fragment.
* It is used to manage delayed fragment updates and can be null if no updates in card.
*/
private var refreshFragmentRunnable: Runnable? = null
override fun afterTextChanged(arg0: Editable) {
refreshFragmentRunnable?.let { refreshFragmentHandler.removeCallbacks(it) }
when (currentEditTab) {
EditTab.STYLING -> tempModel.css = binding.editText.text.toString()
EditTab.BACK -> template.afmt = binding.editText.text.toString()
EditTab.FRONT -> template.qfmt = binding.editText.text.toString()
else -> template.qfmt = binding.editText.text.toString()
}
templateEditor.tempNoteType!!.updateTemplate(cardIndex, template)
val updateRunnable =
Runnable {
templateEditor.loadTemplatePreviewerFragmentIfFragmented()
}
refreshFragmentRunnable = updateRunnable
refreshFragmentHandler.postDelayed(updateRunnable, REFRESH_PREVIEW_DELAY)
templateEditor.enableDiscardChangesDialog()
}
override fun beforeTextChanged(
arg0: CharSequence,
arg1: Int,
arg2: Int,
arg3: Int,
) {
// do nothing
}
override fun onTextChanged(
arg0: CharSequence,
arg1: Int,
arg2: Int,
arg3: Int,
) {
// do nothing
}
}
binding.editText.addTextChangedListener(templateEditorWatcher)
/* When keyboard is visible, hide the bottom navigation bar to allow viewing
of all template text when resize happens */
ViewCompat.setOnApplyWindowInsetsListener(binding.root) { _, insets ->
binding.bottomNavigation.isVisible = !insets.isVisible(WindowInsetsCompat.Type.ime())
insets
}
/*
* We focus on the editText to indicate it's editable, but we don't automatically
* show the keyboard. This is intentional - the keyboard should only appear
* when the user taps on the edit field, not every time the fragment loads.
*/
binding.editText.post {
binding.editText.requestFocus()
}
parentFragmentManager.setFragmentResultListener(insertFieldRequestKey, viewLifecycleOwner) { key, bundle ->
// this is guaranteed to be non null, as we put a non null value on the other side
insertField(bundle.getString(InsertFieldDialog.KEY_INSERTED_FIELD)!!)
}
setupMenu()
}
/*
* Custom ActionMode.Callback implementation for adding new field action
* button in the text selection menu.
*/
private inner class ActionModeCallback : ActionMode.Callback {
private val insertFieldId = 1
override fun onCreateActionMode(
mode: ActionMode,
menu: Menu,
): Boolean = true
override fun onPrepareActionMode(
mode: ActionMode,
menu: Menu,
): Boolean {
if (menu.findItem(insertFieldId) != null) {
return false
}
val initialSize = menu.size
if (currentEditorViewId != R.id.styling_edit) {
// 10644: Do not pass in a R.string as the final parameter as MIUI on Android 12 crashes.
menu.add(Menu.FIRST, insertFieldId, 0, getString(R.string.card_template_editor_insert_field))
}
return initialSize != menu.size
}
override fun onActionItemClicked(
mode: ActionMode,
item: MenuItem,
): Boolean {
val itemId = item.itemId
return if (itemId == insertFieldId) {
showInsertFieldDialog()
mode.finish()
true
} else {
false
}
}
override fun onDestroyActionMode(mode: ActionMode) {
// Left empty on purpose
}
}
@NeedsTest(
"the kotlin migration made this method crash due to a recursive call when the dialog would return its data",
)
fun showInsertFieldDialog() {
launchCatchingTask {
val fieldNames = templateEditor.fieldNames ?: return@launchCatchingTask
val side =
when (currentEditTab) {
EditTab.FRONT -> SingleCardSide.FRONT
EditTab.BACK -> SingleCardSide.BACK
else -> SingleCardSide.FRONT
}
val noteId = if (templateEditor.noteId > 0) templateEditor.noteId else null
// use the ord of the selected template, not the ord of the currently edited card
val ord =
// deletions change ordinals, don't try to preview metadata if this occurs.
if (tempModel.templateChanges.any {
it.type == CardTemplateNotetype.ChangeType.DELETE
}
) {
null
} else {
templateEditor.ord
}
val dialog =
InsertFieldDialog.newInstance(
fieldItems = fieldNames,
metadata =
InsertFieldMetadata.query(
side = side,
noteId = noteId,
ord = ord,
cardTemplateName = templateName,
noteTypeName = tempModel.notetype.name,
),
requestKey = insertFieldRequestKey,
)
templateEditor.showDialogFragment(dialog)
}
}
@NeedsTest("Cancellation")
@NeedsTest("Prefill is correct")
@NeedsTest("Does not work for Cloze/Occlusion")
@NeedsTest("UI is updated on success")
fun showRenameDialog() {
if (noteTypeCreatesDynamicNumberOfNotes()) {
Timber.w("attempted to rename a dynamic note type")
return
}
val ordinal = templateEditor.ord
val template = templateEditor.tempNoteType!!.getTemplate(ordinal)
// obtain the current names (potentially unsaved)
val existingNames =
templateEditor.tempNoteType!!
.notetype.templates
.map { CardTypeName.fromString(it.name) }
RenameCardTypeDialog.showInstance(
requireContext(),
prefill = template.name,
currentName = CardTypeName.fromString(template.name),
existingNames = existingNames,
) { newName ->
template.name = newName.value
templateEditor.enableDiscardChangesDialog()
Timber.i("updated card template name")
Timber.d("updated name of template %d to '%s'", ordinal, newName)
// update the tab
templateEditor.mainBinding.cardTemplateEditorPager.adapter!!
.notifyDataSetChanged()
// Update the tab name in previewer
templateEditor.loadTemplatePreviewerFragmentIfFragmented()
}
}
private fun showRepositionDialog() {
RepositionCardTemplateDialog.showInstance(
requireContext(),
templateEditor.mainBinding.cardTemplateEditorPager.adapter!!
.itemCount,
) { newPosition ->
val currentPosition = templateEditor.ord
Timber.w("moving card template %d to %d", currentPosition, newPosition)
TODO("CardTemplateNotetype is a complex class and requires significant testing")
}
}
private fun insertField(fieldToInsert: String) {
val start = max(binding.editText.selectionStart, 0)
val end = max(binding.editText.selectionEnd, 0)
// add string to editText
binding.editText.text!!.replace(min(start, end), max(start, end), fieldToInsert, 0, fieldToInsert.length)
}
fun setCurrentEditorView(
viewId: Int,
cardId: Int,
editorContent: String,
) {
// saving the cursor position before changing the editor view
templateEditor.tabToCursorPositions[cardId]?.set(
currentEditorViewId,
binding.editText.selectionStart,
)
currentEditorViewId = viewId
binding.editText.setText(editorContent)
binding.editText.requestFocus()
binding.editText.setSelection(
templateEditor.tabToCursorPositions[cardId]?.get(
currentEditorViewId,
) ?: 0,
)
}
/**
* Cloze and image occlusion note types can generate an arbitrary number of cards from a note
* Anki only offers:
* * Restore to Default
* * Browser Appearance
*/
@NeedsTest("cannot perform operations on Image Occlusion")
private fun noteTypeCreatesDynamicNumberOfNotes(): Boolean {
val noteType = templateEditor.tempNoteType!!.notetype
return noteType.isCloze || noteType.isImageOcclusion
}
private fun setupMenu() {
(requireActivity() as MenuHost).addMenuProvider(
object : MenuProvider {
override fun onCreateMenu(
menu: Menu,
menuInflater: MenuInflater,
) {
menuInflater.inflate(R.menu.card_template_editor, menu)
setupCommonMenu(menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean = handleCommonMenuItemSelected(menuItem)
},
viewLifecycleOwner,
Lifecycle.State.RESUMED,
)
}
fun deleteCardTemplate() {
templateEditor.lifecycleScope.launch {
val tempModel = templateEditor.tempNoteType
val ordinal = templateEditor.ord
val template = tempModel!!.getTemplate(ordinal)
// Don't do anything if only one template
if (tempModel.templateCount < 2) {
templateEditor.showSimpleMessageDialog(resources.getString(R.string.card_template_editor_cant_delete))
return@launch
}
if (deletionWouldOrphanNote(tempModel, ordinal)) {
showOrphanNoteDialog()
return@launch
}
// Show confirmation dialog
val numAffectedCards =
if (!CardTemplateNotetype.isOrdinalPendingAdd(tempModel, ordinal)) {
Timber.d("Ordinal is not a pending add, so we'll get the current card count for confirmation")
withCol { notetypes.tmplUseCount(tempModel.notetype, ordinal) }
} else {
0
}
confirmDeleteCards(template, tempModel.notetype, numAffectedCards)
}
}
/* showOrphanNoteDialog shows a AlertDialog if the deletionWouldOrphanNote returns true
* it displays a warning for the user when they attempt to delete a card type that
would leave some notes without any cards (orphan notes) */
private fun showOrphanNoteDialog() {
val builder =
AlertDialog
.Builder(requireContext())
.setTitle(R.string.orphan_note_title)
.setMessage(R.string.orphan_note_message)
.setPositiveButton(android.R.string.ok, null)
builder.show()
}
fun openBrowserAppearance(): Boolean {
val currentTemplate = getCurrentTemplate()
currentTemplate?.let { launchCardBrowserAppearance(it) }
return true
}
fun addCardTemplate() {
if (templateEditor.tempNoteType!!.notetype.isCloze) {
Timber.w("addCardTemplate attempted on cloze note type")
return
}
// Show confirmation dialog
// isOrdinalPendingAdd method will check if there are any new card types added or not,
// if TempModel has new card type then numAffectedCards will be 0 by default.
val numAffectedCards =
if (!CardTemplateNotetype.isOrdinalPendingAdd(templateEditor.tempNoteType!!, templateEditor.ord)) {
templateEditor.getColUnsafe.notetypes.tmplUseCount(templateEditor.tempNoteType!!.notetype, templateEditor.ord)
} else {
0
}