-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
app_model.dart
3658 lines (3185 loc) · 120 KB
/
app_model.dart
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
import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'dart:ui';
import 'package:audio_service/audio_service.dart' as ag;
import 'package:cancelable_compute/cancelable_compute.dart' as cancelable;
import 'package:collection/collection.dart';
import 'package:clipboard/clipboard.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:external_app_launcher/external_app_launcher.dart';
import 'package:external_path/external_path.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_charset_detector/flutter_charset_detector.dart';
import 'package:flutter_exit_app/flutter_exit_app.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_vlc_player/flutter_vlc_player.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:isar/isar.dart';
import 'package:intl/intl.dart' as intl;
import 'package:path/path.dart' as path;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:remove_emoji/remove_emoji.dart';
import 'package:restart_app/restart_app.dart';
import 'package:subtitle/subtitle.dart';
import 'package:wakelock/wakelock.dart';
import 'package:yuuna/creator.dart';
import 'package:yuuna/dictionary.dart';
import 'package:yuuna/language.dart';
import 'package:yuuna/media.dart';
import 'package:yuuna/models.dart';
import 'package:yuuna/pages.dart';
import 'package:yuuna/utils.dart';
/// Schemas used in Isar database.
final List<CollectionSchema> globalSchemas = [
DictionarySchema,
DictionaryEntrySchema,
DictionaryHeadingSchema,
DictionaryPitchSchema,
DictionaryFrequencySchema,
DictionaryTagSchema,
DictionarySearchResultSchema,
MediaItemSchema,
AnkiMappingSchema,
SearchHistoryItemSchema,
MessageItemSchema,
MokuroCatalogSchema,
BrowserBookmarkSchema,
];
/// A list of fields that the app will support at runtime.
final List<Field> globalFields = List<Field>.unmodifiable(
[
SentenceField.instance,
TermField.instance,
ReadingField.instance,
MeaningField.instance,
NotesField.instance,
ImageField.instance,
AudioField.instance,
AudioSentenceField.instance,
PitchAccentField.instance,
FuriganaField.instance,
FrequencyField.instance,
ContextField.instance,
ClozeBeforeField.instance,
ClozeInsideField.instance,
ClozeAfterField.instance,
ExpandedMeaningField.instance,
CollapsedMeaningField.instance,
HiddenMeaningField.instance,
TagsField.instance,
],
);
/// A list of media types that the app will support at runtime.
final Map<String, Field> fieldsByKey = Map.unmodifiable(
Map<String, Field>.fromEntries(
globalFields.map(
(field) => MapEntry(field.uniqueKey, field),
),
),
);
/// A global [Provider] for app-wide configuration and state management.
final appProvider = ChangeNotifierProvider<AppModel>((ref) {
return AppModel();
});
/// Provides color for all quick actions.
final quickActionColorProvider =
FutureProvider.family<Map<String, Color?>, DictionaryHeading>(
(ref, heading) async {
AppModel appModel = ref.watch(appProvider);
List<Future<Color?>> futures = appModel.quickActions.values.map((e) async {
return e.getIconColor(
appModel: appModel,
heading: heading,
);
}).toList();
List<Color?> colors = await Future.wait(futures);
return Map<String, Color?>.fromEntries(
appModel.quickActions.values.mapIndexed((i, action) {
return MapEntry(action.uniqueKey, colors[i]);
}));
});
/// A global [Provider] for maintaining visible once state.
final visibleOnceProvider =
StateProvider.family<bool, DictionaryHeading>((ref, heading) => false);
/// A global [Provider] for listening to search term changes in PIP mode.
final pipSearchTermProvider = StateProvider<String>((ref) => '');
/// A global [Provider] for listening to search term position changes in PIP mode.
final pipSearchPositionProvider = StateProvider<int>((ref) => 0);
/// A scoped model for parameters that affect the entire application.
/// RiverPod is used for global state management across multiple layers,
/// especially for preferences that persist across application restarts.
class AppModel with ChangeNotifier {
/// Used for showing dialogs without needing to pass around a [BuildContext].
GlobalKey<NavigatorState> get navigatorKey => _navigatorKey;
late final GlobalKey<NavigatorState> _navigatorKey =
GlobalKey<NavigatorState>();
/// Used to get the versioning metadata of the app. See [initialise].
RouteObserver<PageRoute> get routeObserver => _routeObserver;
final RouteObserver<PageRoute> _routeObserver = RouteObserver<PageRoute>();
/// Used for accessing persistent key-value data. See [initialise].
late final Box _preferences;
/// Used for accessing persistent dictonary history. See [initialise].
late final Box<int> _dictionaryHistory;
/// Used for accessing persistent database data. See [initialise].
late final Isar _database;
/// Used to get the versioning metadata of the app. See [initialise].
PackageInfo get packageInfo => _packageInfo;
late final PackageInfo _packageInfo;
/// Used to get information on the Android version of the device.
AndroidDeviceInfo get androidDeviceInfo => _androidDeviceInfo;
late final AndroidDeviceInfo _androidDeviceInfo;
/// Used for caching images and audio produced from media seeds.
DefaultCacheManager get cacheManager => _cacheManager;
final _cacheManager = DefaultCacheManager();
/// Used to notify dictionary widgets to dictionary history additions.
final ChangeNotifier dictionaryEntriesNotifier = ChangeNotifier();
/// Used to notify dictionary widgets to dictionary import additions.
final ChangeNotifier dictionarySearchAgainNotifier = ChangeNotifier();
/// Used to notify dictionary widgets to dictionary menu changes.
final ChangeNotifier dictionaryMenuNotifier = ChangeNotifier();
/// For refreshing on dictionary result additions.
void refreshDictionaryHistory() {
dictionaryMenuNotifier.notifyListeners();
}
/// Used to strip emoji from search terms.
final _removeEmoji = RemoveEmoji();
/// Used to notify toggling incognito. Updates the app logo to and from
/// grayscale.
final ChangeNotifier incognitoNotifier = ChangeNotifier();
/// Notifies app to stop showing any screens.
final ChangeNotifier databaseCloseNotifier = ChangeNotifier();
/// These directories are prepared at startup in order to reduce redundancy
/// in actual runtime.
/// Directory where data that may be dumped is stored.
Directory get temporaryDirectory => _temporaryDirectory;
late final Directory _temporaryDirectory;
/// Directory where data may be persisted.
Directory get appDirectory => _appDirectory;
late final Directory _appDirectory;
/// Directory where database data is persisted.
Directory get databaseDirectory => _databaseDirectory;
late final Directory _databaseDirectory;
/// Directory where browser cache data may be persisted.
Directory get browserDirectory => _browserDirectory;
late final Directory _browserDirectory;
/// Directory where media source thumbnails may be persisted.
Directory get thumbnailsDirectory => _thumbnailsDirectory;
late final Directory _thumbnailsDirectory;
/// Directory where Hive key-value data is stored.
Directory get hiveDirectory => _hiveDirectory;
late final Directory _hiveDirectory;
/// Directory where Isar database data is stored.
Directory get isarDirectory => _isarDirectory;
late final Directory _isarDirectory;
/// Directory where media for export is stored for communication with
/// third-party APIs.
Directory get exportDirectory => _exportDirectory;
late final Directory _exportDirectory;
/// Directory where the browser media source saves web archives for offline
/// use.
Directory get webArchiveDirectory => _webArchiveDirectory;
late final Directory _webArchiveDirectory;
/// Directory where media for export is stored for communication with
/// third-party APIs. Fallback for failure.
Directory get alternateExportDirectory => _alternateExportDirectory;
late final Directory _alternateExportDirectory;
/// Directory used as a working directory for dictionary imports.
Directory get dictionaryImportWorkingDirectory =>
_dictionaryImportWorkingDirectory;
late final Directory _dictionaryImportWorkingDirectory;
/// Used to fetch a language by its locale tag with constant time performance.
/// Initialised with [populateLanguages] at startup.
late final Map<String, Language> languages;
/// Used to fetch an app locale by its locale tag with constant time
/// performance. Initialised with [populateLocales] at startup.
late final Map<String, Locale> locales;
/// Used to fetch a dictionary format by its unique key with constant time
/// performance. Initialised with [populateDictionaryFormats] at startup.
late final Map<String, DictionaryFormat> dictionaryFormats;
/// Used to fetch a media type by its unique key with constant time
/// performance. Initialised with [populateMediaTypes] at startup.
late final Map<String, MediaType> mediaTypes;
/// Used to fetch initialised fields by their unique key with constant
/// time performance. Initialised with [populateEnhancements] at startup.
late final Map<String, Field> fields;
/// Used to fetch initialised enhancements by their unique key with constant
/// time performance. Initialised with [populateEnhancements] at startup.
late final Map<Field, Map<String, Enhancement>> enhancements;
/// Used to fetch initialised actions by their unique key with constant
/// time performance. Initialised with [populateQuickActions] at startup.
late final Map<String, QuickAction> quickActions;
/// Used to fetch initialised sources by their unique key with constant
/// time performance. Initialised with [populateMediaSources] at startup.
late final Map<MediaType, Map<String, MediaSource>> mediaSources;
/// Maximum number of manual enhancements in a field.
final int maximumFieldEnhancements = 5;
/// Maximum number of quick actions.
final int maximumQuickActions = 6;
/// Maximum number of search history items.
final int maximumSearchHistoryItems = 60;
/// Maximum number of media history items.
final int maximumMediaHistoryItems = 100;
/// Maximum number of dictionary history items.
final int maximumDictionaryHistoryItems = 10;
/// Maximum number of dictionary search results stored in the database.
final int maximumDictionarySearchResults = 200;
/// Maximum number of headwords in a returned dictionary result for
/// performance purposes.
final int defaultMaximumDictionaryTermsInResult = 10;
/// Used as the history key used for the Stash.
final String stashKey = 'stash';
/// Used to check if the dictionary tab should be refreshed on switching tabs.
bool shouldRefreshTabs = false;
/// Returns all dictionaries imported into the database. Sorted by the
/// user-defined order in the dictionary menu.
List<Dictionary> get dictionaries =>
_database.dictionarys.where().sortByOrder().findAllSync();
/// Returns all export profiles.
List<AnkiMapping> get mappings =>
_database.ankiMappings.where().sortByOrder().findAllSync();
/// Returns all Mokuro catalogs.
List<MokuroCatalog> get mokuroCatalogs =>
_database.mokuroCatalogs.where().sortByOrder().findAllSync();
/// Returns all Browser bookmarks.
List<BrowserBookmark> get browserBookmarks =>
_database.browserBookmarks.where().anyId().findAllSync();
/// Returns the message log for the [ReaderChatgptSource].
List<MessageItem> get messages =>
_database.messageItems.where().findAllSync();
/// Adds a message to the log for the [ReaderChatgptSource].
int addMessage(MessageItem message) {
late int id;
_database.writeTxnSync(() {
id = _database.messageItems.putSync(message);
});
return id;
}
/// Removes the last message from the log for the [ReaderChatgptSource].
void removeMessage(int id) {
_database.writeTxnSync(() {
_database.messageItems.deleteSync(id);
});
}
/// Clears the message log for the [ReaderChatgptSource].
Future<void> clearMessages() async {
await _database.writeTxn(() async {
await _database.messageItems.clear();
});
}
/// Returns all dictionary history results. Oldest is first.
List<DictionarySearchResult> get dictionaryHistory =>
_database.dictionarySearchResults
.getAllSync(_dictionaryHistory.values.toList())
.whereNotNull()
.toList();
/// For watching the dictionary history collection.
Stream<void> Function(int) get watchDictionaryItem =>
_database.dictionarySearchResults.watchObjectLazy;
/// For invoking pauses from media where needed.
Stream<void> get currentMediaPauseStream =>
_currentMediaPauseController.stream;
final StreamController<void> _currentMediaPauseController =
StreamController.broadcast();
/// For listening to searches made inside the Card Creator.
Stream<void> get cardCreatorRecursiveSearchStream =>
_cardCreatorRecursiveSearchStreamController.stream;
final StreamController<void> _cardCreatorRecursiveSearchStreamController =
StreamController.broadcast();
/// Broadcast that a search was made in the Card Creator
void notifyRecursiveSearch() {
_cardCreatorRecursiveSearchStreamController.add(null);
}
/// Allows actions to be performed upon Play/Pause on headset buttons.
Stream<void> get playPauseHeadsetActionStream =>
_playPauseHeadsetActionStreamController.stream;
final StreamController<void> _playPauseHeadsetActionStreamController =
StreamController.broadcast();
/// For listening to changes for whether or not the Card Creator is open.
Stream<bool> get creatorActiveStream => _creatorActiveController.stream;
final StreamController<bool> _creatorActiveController =
StreamController.broadcast();
/// Used to check whether or not the creator is currently in the navigation
/// stack.
bool get isCreatorOpen => _isCreatorOpen;
bool _isCreatorOpen = false;
/// Used to check whether or not the app is currently using a media source.
bool get isMediaOpen => _currentMediaSource != null;
/// Current active media source.
MediaSource? get currentMediaSource => _currentMediaSource;
MediaSource? _currentMediaSource;
/// Current active media item.
MediaItem? get currentMediaItem => _currentMediaItem;
MediaItem? _currentMediaItem;
/// Blocks creator from processing initial media while player controller is not ready.
bool blockCreatorInitialMedia = false;
/// Get the app-wide text style.
TextStyle get textStyle => TextStyle(
fontFamily: targetLanguage.defaultFontFamily,
fontFeatures: const [FontFeature('liga', 0)],
locale: targetLanguage.locale,
textBaseline: targetLanguage.textBaseline,
);
/// This override is a workaround required to theme the app-wide [TextTheme]
/// based on the [Locale] and [TextBaseline] of the active target language.
TextTheme get textTheme => TextTheme(
displayLarge: textStyle,
displayMedium: textStyle,
displaySmall: textStyle,
headlineLarge: textStyle,
headlineMedium: textStyle,
headlineSmall: textStyle,
titleLarge: textStyle,
titleMedium: textStyle,
titleSmall: textStyle,
bodyLarge: textStyle,
bodyMedium: textStyle,
bodySmall: textStyle,
labelLarge: textStyle,
labelMedium: textStyle,
labelSmall: textStyle,
);
/// Shows when the current mode is a light theme.
ThemeData get theme => ThemeData(
scaffoldBackgroundColor: Colors.white,
unselectedWidgetColor: Colors.black54,
textTheme: textTheme,
appBarTheme: const AppBarTheme(
elevation: 0,
centerTitle: false,
backgroundColor: Colors.white,
foregroundColor: Colors.black,
),
switchTheme: SwitchThemeData(
thumbColor: MaterialStateColor.resolveWith((states) {
return states.contains(MaterialState.selected)
? Colors.red
: Colors.white;
}),
trackColor: MaterialStateColor.resolveWith((states) {
return states.contains(MaterialState.selected)
? Colors.red.withOpacity(0.5)
: Colors.grey;
}),
),
bottomNavigationBarTheme: BottomNavigationBarThemeData(
elevation: 0,
type: BottomNavigationBarType.fixed,
selectedLabelStyle: textTheme.labelSmall,
unselectedLabelStyle: textTheme.labelSmall,
showSelectedLabels: true,
showUnselectedLabels: true,
backgroundColor: Colors.white,
),
popupMenuTheme: const PopupMenuThemeData(
color: Colors.white,
shape: RoundedRectangleBorder(),
),
dialogTheme: const DialogTheme(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(),
),
cardColor: Colors.white,
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: Colors.black,
),
),
listTileTheme: ListTileThemeData(
dense: true,
selectedTileColor: Colors.grey.shade300,
selectedColor: Colors.black,
horizontalTitleGap: 0,
),
inputDecorationTheme: const InputDecorationTheme(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.black54,
),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
),
scrollbarTheme: ScrollbarThemeData(
thickness: MaterialStateProperty.all(3),
thumbVisibility: MaterialStateProperty.all(true),
),
sliderTheme: const SliderThemeData(
thumbColor: Colors.red,
activeTrackColor: Colors.red,
inactiveTrackColor: Colors.grey,
trackShape: RectangularSliderTrackShape(),
trackHeight: 2,
thumbShape: RoundSliderThumbShape(enabledThumbRadius: 6),
),
colorScheme: ColorScheme.fromSwatch()
.copyWith(
primary: Colors.red,
secondary: Colors.red,
brightness: Brightness.light,
)
.copyWith(background: Colors.white),
);
/// Shows when the current mode is a dark theme.
ThemeData get darkTheme => ThemeData(
scaffoldBackgroundColor: Colors.black,
textTheme: textTheme,
switchTheme: SwitchThemeData(
thumbColor: MaterialStateColor.resolveWith((states) {
return states.contains(MaterialState.selected)
? Colors.red
: Colors.grey;
}),
trackColor: MaterialStateColor.resolveWith((states) {
return states.contains(MaterialState.selected)
? Colors.red.withOpacity(0.5)
: Colors.grey;
}),
),
appBarTheme: const AppBarTheme(
elevation: 0,
centerTitle: false,
backgroundColor: Colors.black,
foregroundColor: Colors.white,
),
bottomNavigationBarTheme: BottomNavigationBarThemeData(
elevation: 0,
type: BottomNavigationBarType.fixed,
selectedLabelStyle: textTheme.labelSmall,
unselectedLabelStyle: textTheme.labelSmall,
showSelectedLabels: true,
showUnselectedLabels: true,
backgroundColor: Colors.black,
),
popupMenuTheme: const PopupMenuThemeData(
color: Color.fromARGB(255, 30, 30, 30),
shape: RoundedRectangleBorder(),
),
dialogTheme: const DialogTheme(
backgroundColor: Color.fromARGB(255, 30, 30, 30),
shape: RoundedRectangleBorder(),
),
cardColor: const Color.fromARGB(255, 30, 30, 30),
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: Colors.white,
),
),
listTileTheme: ListTileThemeData(
dense: true,
selectedTileColor: Colors.grey.shade600,
selectedColor: Colors.white,
horizontalTitleGap: 0,
),
inputDecorationTheme: const InputDecorationTheme(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.white70,
),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
),
scrollbarTheme: ScrollbarThemeData(
thumbVisibility: MaterialStateProperty.all(true),
),
sliderTheme: const SliderThemeData(
thumbColor: Colors.red,
activeTrackColor: Colors.red,
inactiveTrackColor: Colors.grey,
trackShape: RectangularSliderTrackShape(),
trackHeight: 2,
thumbShape: RoundSliderThumbShape(enabledThumbRadius: 6),
),
colorScheme: ColorScheme.fromSwatch()
.copyWith(
primary: Colors.red,
secondary: Colors.red,
brightness: Brightness.dark,
)
.copyWith(background: Colors.black),
);
/// Get the sentence to be used by the [SentenceField] upon card creation.
JidoujishoTextSelection getCurrentSentence() {
if (isMediaOpen) {
return _currentMediaSource!.currentSentence;
} else {
MediaType mediaType = mediaTypes.values.toList()[currentHomeTabIndex];
if (mediaType is DictionaryMediaType) {
return JidoujishoTextSelection(
text: '',
);
} else {
return (_currentMediaSource ??
(getCurrentSourceForMediaType(mediaType: mediaType)))
.currentSentence;
}
}
}
/// This should all be refactored as part of [MediaItem] if possible. No
/// reason to expose it here if not for card export functions. This is super
/// cursed. Need to extract this to its own Provider at some point.
/// Current player controller.
VlcPlayerController? currentPlayerController;
/// Current subtitle.
ValueNotifier<Subtitle?> get currentSubtitle => _currentSubtitle;
final ValueNotifier<Subtitle?> _currentSubtitle =
ValueNotifier<Subtitle?>(null);
/// Current subtitle options.
ValueNotifier<SubtitleOptions>? get currentSubtitleOptions {
_currentSubtitleOptions ??= ValueNotifier<SubtitleOptions>(subtitleOptions);
return _currentSubtitleOptions;
}
ValueNotifier<SubtitleOptions>? _currentSubtitleOptions;
/// Override color for the dictionary widget.
Color? get overrideDictionaryColor => _overrideDictionaryColor;
Color? _overrideDictionaryColor;
/// Override theme for the dictionary widget.
ThemeData? get overrideDictionaryTheme => _overrideDictionaryTheme;
ThemeData? _overrideDictionaryTheme;
/// Override color for the dictionary widget.
void setOverrideDictionaryColor(Color? color) {
_overrideDictionaryColor = color;
}
/// Override theme for the dictionary widget.
void setOverrideDictionaryTheme(ThemeData? themeData) {
_overrideDictionaryTheme = themeData;
}
/// Get the current media item for use in tracking history and generating
/// media for card creation based on media progress.
MediaItem? getCurrentMediaItem() {
if (_currentMediaSource == null) {
return null;
} else {
return _currentMediaItem;
}
}
/// Manually flag that the app is now using a media item. Prefer [openMedia]
/// instead of this.
void setCurrentMediaItem(MediaItem mediaItem) {
_currentMediaItem = mediaItem;
_currentMediaSource = mediaItem.getMediaSource(appModel: this);
}
/// Get a mapping with a given mapping name.
AnkiMapping? getMappingFromLabel(String label) {
return _database.ankiMappings.where().labelEqualTo(label).findFirstSync();
}
/// Change this once a field hide/show system is in place.
List<Field> get activeFields => [
...lastSelectedMapping.getCreatorFields(),
...lastSelectedMapping.getCreatorCollapsedFields()
];
/// Update the user-defined order of a given dictionary in the database.
/// See the dictionary dialog's [ReorderableListView] for usage.
void updateDictionaryOrder(List<Dictionary> newDictionaries) async {
_database.writeTxnSync(() {
_database.dictionarys.putAllSync(newDictionaries);
});
}
/// Update the user-defined order of a given dictionary in the database.
/// See the dictionary dialog's [ReorderableListView] for usage.
void updateMappingsOrder(List<AnkiMapping> newMappings) async {
_database.writeTxnSync(() {
_database.ankiMappings.clearSync();
_database.ankiMappings.putAllSync(newMappings);
});
}
/// Update the user-defined order of given catalogs in the database.
/// See the catalog dialog's [ReorderableListView] for usage.
void updateCatalogsOrder(List<MokuroCatalog> newCatalogs) async {
_database.writeTxnSync(() {
_database.mokuroCatalogs.clearSync();
_database.mokuroCatalogs.putAllSync(newCatalogs);
});
}
/// Populate maps for languages at startup to optimise performance.
void populateLanguages() async {
/// A list of languages that the app will support at runtime.
final List<Language> availableLanguages = List<Language>.unmodifiable(
[
JapaneseLanguage.instance,
EnglishLanguage.instance,
],
);
languages = Map<String, Language>.unmodifiable(
Map<String, Language>.fromEntries(
availableLanguages.map(
(language) => MapEntry(language.locale.toLanguageTag(), language),
),
),
);
}
/// Populate maps for locales at startup to optimise performance.
void populateLocales() async {
/// A list of locales that the app will support at runtime. This is not
/// related to supported target languages.
final List<Locale> availableLocales = List<Locale>.unmodifiable(
[
const Locale('en', 'US'),
],
);
locales = Map<String, Locale>.unmodifiable(
Map<String, Locale>.fromEntries(
availableLocales.map(
(locale) => MapEntry(locale.toLanguageTag(), locale),
),
),
);
}
/// Populate maps for media types at startup to optimise performance.
void populateMediaTypes() async {
/// A list of media types that the app will support at runtime.
final List<MediaType> availableMediaTypes = List<MediaType>.unmodifiable(
[
PlayerMediaType.instance,
ReaderMediaType.instance,
DictionaryMediaType.instance,
],
);
mediaTypes = Map<String, MediaType>.unmodifiable(
Map<String, MediaType>.fromEntries(
availableMediaTypes.map(
(mediaType) => MapEntry(mediaType.uniqueKey, mediaType),
),
),
);
}
/// Populate maps for media sources at startup to optimise performance.
void populateMediaSources() async {
/// A list of media sources that the app will support at runtime.
final Map<MediaType, List<MediaSource>> availableMediaSources = {
PlayerMediaType.instance: [
PlayerLocalMediaSource.instance,
PlayerYoutubeSource.instance,
PlayerNetworkStreamSource.instance
],
ReaderMediaType.instance: [
ReaderTtuSource.instance,
ReaderMokuroSource.instance,
ReaderBrowserSource.instance,
ReaderLyricsSource.instance,
ReaderChatgptSource.instance,
ReaderClipboardSource.instance,
ReaderWebsocketSource.instance,
],
ViewerMediaType.instance: [
ViewerCameraSource.instance,
],
DictionaryMediaType.instance: [],
};
mediaSources = Map<MediaType, Map<String, MediaSource>>.unmodifiable(
availableMediaSources.map(
(type, sources) => MapEntry(
type,
Map<String, MediaSource>.unmodifiable(
Map<String, MediaSource>.fromEntries(
sources.map(
(source) => MapEntry(source.uniqueKey, source),
),
),
),
),
),
);
}
/// Populate maps for dictionary formats at startup to optimise performance.
void populateDictionaryFormats() async {
/// A list of dictionary formats that the app will support at runtime.
final List<DictionaryFormat> availableDictionaryFormats =
List<DictionaryFormat>.unmodifiable(
[
YomichanFormat.instance,
MigakuFormat.instance,
AbbyyLingvoFormat.instance,
],
);
dictionaryFormats = Map<String, DictionaryFormat>.unmodifiable(
Map<String, DictionaryFormat>.fromEntries(
availableDictionaryFormats.map(
(dictionaryFormat) => MapEntry(
dictionaryFormat.uniqueKey,
dictionaryFormat,
),
),
),
);
}
/// Populate maps for fields at startup to optimise performance.
void populateFields() async {
fields = Map<String, Field>.unmodifiable(
Map<String, Field>.fromEntries(
globalFields.map(
(field) => MapEntry(field.uniqueKey, field),
),
),
);
}
/// Populate maps for enhancements at startup to optimise performance.
void populateEnhancements() async {
/// A list of enhancements that the app will support at runtime.
final Map<Field, List<Enhancement>> availableEnhancements = {
AudioField.instance: [
ClearFieldEnhancement(field: AudioField.instance),
JapanesePod101AudioEnhancement(),
ForvoAudioEnhancement(),
PickAudioEnhancement(field: AudioField.instance),
AudioRecorderEnhancement(field: AudioField.instance),
],
AudioSentenceField.instance: [
ClearFieldEnhancement(field: AudioSentenceField.instance),
PickAudioEnhancement(field: AudioSentenceField.instance),
AudioRecorderEnhancement(field: AudioSentenceField.instance),
],
NotesField.instance: [
ClearFieldEnhancement(field: NotesField.instance),
OpenStashEnhancement(field: NotesField.instance),
PopFromStashEnhancement(field: NotesField.instance),
TextSegmentationEnhancement(field: NotesField.instance),
],
ImageField.instance: [
ClearFieldEnhancement(field: ImageField.instance),
BingImagesSearchEnhancement(),
CropImageEnhancement(),
PickImageEnhancement(),
CameraEnhancement(),
],
MeaningField.instance: [
ClearFieldEnhancement(field: MeaningField.instance),
SentencePickerEnhancement(field: MeaningField.instance),
TextSegmentationEnhancement(field: MeaningField.instance),
],
ReadingField.instance: [
ClearFieldEnhancement(field: ReadingField.instance),
],
SentenceField.instance: [
ClearFieldEnhancement(field: SentenceField.instance),
TextSegmentationEnhancement(field: SentenceField.instance),
SentencePickerEnhancement(field: SentenceField.instance),
OpenStashEnhancement(field: SentenceField.instance),
PopFromStashEnhancement(field: SentenceField.instance),
],
TermField.instance: [
ClearFieldEnhancement(field: TermField.instance),
SearchDictionaryEnhancement(),
MassifExampleSentencesEnhancement(),
TatoebaExampleSentencesEnhancement(),
ImmersionKitEnhancement(),
OpenStashEnhancement(field: TermField.instance),
PopFromStashEnhancement(field: TermField.instance),
],
ContextField.instance: [
ClearFieldEnhancement(field: ContextField.instance),
OpenStashEnhancement(field: ContextField.instance),
PopFromStashEnhancement(field: ContextField.instance),
],
PitchAccentField.instance: [
ClearFieldEnhancement(field: PitchAccentField.instance),
],
FuriganaField.instance: [
ClearFieldEnhancement(field: FuriganaField.instance),
],
FrequencyField.instance: [
ClearFieldEnhancement(field: FrequencyField.instance),
],
CollapsedMeaningField.instance: [
ClearFieldEnhancement(field: CollapsedMeaningField.instance),
SentencePickerEnhancement(field: CollapsedMeaningField.instance),
TextSegmentationEnhancement(field: CollapsedMeaningField.instance),
],
ExpandedMeaningField.instance: [
ClearFieldEnhancement(field: ExpandedMeaningField.instance),
SentencePickerEnhancement(field: ExpandedMeaningField.instance),
TextSegmentationEnhancement(field: ExpandedMeaningField.instance),
],
HiddenMeaningField.instance: [
ClearFieldEnhancement(field: HiddenMeaningField.instance),
SentencePickerEnhancement(field: HiddenMeaningField.instance),
TextSegmentationEnhancement(field: HiddenMeaningField.instance),
],
TagsField.instance: [
ClearFieldEnhancement(field: TagsField.instance),
SaveTagsEnhancement(),
],
ClozeBeforeField.instance: [
ClearFieldEnhancement(field: ClozeBeforeField.instance),
],
ClozeAfterField.instance: [
ClearFieldEnhancement(field: ClozeAfterField.instance),
],
ClozeInsideField.instance: [
ClearFieldEnhancement(field: ClozeInsideField.instance),
],
};
enhancements = Map<Field, Map<String, Enhancement>>.unmodifiable(
availableEnhancements.map(
(field, enhancements) => MapEntry(
field,
Map<String, Enhancement>.unmodifiable(
Map<String, Enhancement>.fromEntries(
enhancements.map(
(enhancement) => MapEntry(enhancement.uniqueKey, enhancement),
),
),
),
),
),
);
}
/// Populate maps for actions at startup to optimise performance.
void populateQuickActions() async {
/// A list of actions that the app will support at runtime.
final List<QuickAction> availableQuickActions = [
CardCreatorAction(),
InstantExportAction(),
AddToStashAction(),
CopyToClipboardAction(),
ShareAction(),
PlayAudioAction(),
];
quickActions = Map<String, QuickAction>.unmodifiable(
Map<String, QuickAction>.fromEntries(
availableQuickActions.map(
(quickAction) => MapEntry(quickAction.uniqueKey, quickAction),
),
),
);
}
/// Populate default mapping if it does not exist in the database.
void populateDefaultMapping(Language language) async {
if (_database.ankiMappings.where().findAllSync().isEmpty) {
_database.writeTxnSync(() {
_database.ankiMappings.putSync(AnkiMapping.defaultMapping(
language: language,
order: 0,
));
});
} else {
AnkiMapping standardProfile = _database.ankiMappings
.where()
.labelEqualTo(AnkiMapping.standardProfileName)
.findFirstSync()!;
if (standardProfile.model != AnkiMapping.standardModelName) {
String newLabel = 'Legacy Standard';
int attempts = 1;
while (_database.ankiMappings
.where()
.labelEqualTo(newLabel)
.findAllSync()
.isNotEmpty) {
attempts += 1;
newLabel = 'Legacy Standard ($attempts)';
}
AnkiMapping legacyProfile = standardProfile.copyWith(
label: newLabel,
);
_database.writeTxnSync(() {
_database.ankiMappings.putAllSync(