diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6fbecf6af6..6a5ad7c5fc 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -27,6 +27,9 @@ jobs: - name: Setup Gradle uses: gradle/actions/setup-gradle@v6 + - name: Fetch native dependencies + run: tools/memorize/fetch_sherpa_onnx.sh + - name: Build debug APK run: ./gradlew assembleMadaniDebug @@ -45,7 +48,7 @@ jobs: run: ./gradlew verifySqlDelightMigration - name: Run tests - run: ./gradlew testMadaniDebug testReleaseUnitTest -PdisableFirebase + run: ./gradlew testMadaniDebug testReleaseUnitTest :feature:memorize:tracker:test -PdisableFirebase - name: Upload test report uses: actions/upload-artifact@v7 diff --git a/.github/workflows/merge.yml b/.github/workflows/merge.yml index de4ca742c3..86898a1e80 100644 --- a/.github/workflows/merge.yml +++ b/.github/workflows/merge.yml @@ -21,6 +21,9 @@ jobs: - name: Setup Gradle uses: gradle/actions/setup-gradle@v6 + - name: Fetch native dependencies + run: tools/memorize/fetch_sherpa_onnx.sh + - name: Build debug APK run: ./gradlew assembleMadaniDebug diff --git a/.github/workflows/post_merge.yml b/.github/workflows/post_merge.yml index 3896dcb276..2c99194998 100644 --- a/.github/workflows/post_merge.yml +++ b/.github/workflows/post_merge.yml @@ -26,6 +26,9 @@ jobs: - name: Setup Gradle uses: gradle/actions/setup-gradle@v6 + - name: Fetch native dependencies + run: tools/memorize/fetch_sherpa_onnx.sh + - name: Build debug Apk run: ./gradlew assembleDebug diff --git a/.gitignore b/.gitignore index 0fd568532c..85e5d7c54a 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,6 @@ crashlytics-build.properties com_crashlytics_export_strings.xml extras app/google-services.json + +# memorize feature: vendored native dependencies (tools/memorize/fetch_sherpa_onnx.sh) +/third_party/ diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 913700fd25..65eea3f4f3 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -224,6 +224,7 @@ dependencies { implementation(project(":common:networking")) implementation(project(":common:pages")) implementation(project(":common:preference")) + implementation(project(":common:progress")) implementation(project(":common:reading")) implementation(project(":common:recitation")) implementation(project(":common:search")) @@ -236,6 +237,7 @@ dependencies { implementation(project(":feature:audiobar")) implementation(project(":feature:ayahbookmark")) implementation(project(":feature:pagetheme")) + implementation(project(":feature:progress")) implementation(project(":feature:downloadmanager")) implementation(project(":feature:qarilist")) implementation(project(":feature:sync")) diff --git a/app/pluggable.gradle b/app/pluggable.gradle index cfd167d926..02e570514a 100644 --- a/app/pluggable.gradle +++ b/app/pluggable.gradle @@ -1,5 +1,8 @@ dependencies { implementation project(path: ':pages:madani') implementation project(path: ':pages:common:madani') - implementation project(path: ':feature:recitation') + implementation project(path: ':feature:memorize') + // page types drawn line by line + implementation project(path: ':feature:linebyline') + implementation project(path: ':pages:linebyline') } diff --git a/app/src/main/java/com/quran/labs/androidquran/QuranApplication.kt b/app/src/main/java/com/quran/labs/androidquran/QuranApplication.kt index 830b9f6432..0944bd5c68 100644 --- a/app/src/main/java/com/quran/labs/androidquran/QuranApplication.kt +++ b/app/src/main/java/com/quran/labs/androidquran/QuranApplication.kt @@ -1,6 +1,7 @@ package com.quran.labs.androidquran import android.app.Application +import android.os.Build import androidx.core.os.UserManagerCompat import androidx.work.Configuration import androidx.work.WorkManager @@ -13,10 +14,12 @@ import com.quran.labs.androidquran.widget.BookmarksWidgetSubscriber import com.quran.mobile.di.QuranApplicationComponent import com.quran.mobile.di.QuranApplicationComponentProvider import com.quran.mobile.feature.sync.QuranSyncManager +import com.quran.mobile.feature.progress.ProgressStartup import dev.zacsweers.metro.HasMemberInjections import dev.zacsweers.metro.Inject import dev.zacsweers.metro.createGraphFactory import timber.log.Timber +import java.io.File @HasMemberInjections open class QuranApplication : Application(), QuranApplicationComponentProvider, Configuration.Provider { @@ -26,6 +29,7 @@ open class QuranApplication : Application(), QuranApplicationComponentProvider, @Inject lateinit var bookmarksWidgetSubscriber: BookmarksWidgetSubscriber @Inject lateinit var quranSettings: QuranSettings @Inject lateinit var quranSyncManager: QuranSyncManager + @Inject lateinit var progressStartup: ProgressStartup override fun provideQuranApplicationComponent(): QuranApplicationComponent { return applicationComponent @@ -33,11 +37,15 @@ open class QuranApplication : Application(), QuranApplicationComponentProvider, override fun onCreate() { super.onCreate() + // A secondary process (e.g. memorize's double-check, which keeps its model apart from the + // speech engine's) runs a service of its own and needs none of the app's setup. + if (isSecondaryProcess()) return setupTimber() applicationComponent = initializeInjector() applicationComponent.inject(this) quranSyncManager.startForegroundSync() initializeWorkManager() + startProgress() bookmarksWidgetSubscriber.subscribeBookmarksWidgetIfNecessary() // theme setup @@ -45,6 +53,15 @@ open class QuranApplication : Application(), QuranApplicationComponentProvider, ThemeUtil.setTheme(theme) } + private fun isSecondaryProcess(): Boolean { + val name = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + getProcessName() + } else { + runCatching { File("/proc/self/cmdline").readText().trim(Char(0), ' ') }.getOrNull() + } + return name != null && name.contains(':') + } + open fun setupTimber() { Timber.plant(RecordingLogTree()) } @@ -59,6 +76,14 @@ open class QuranApplication : Application(), QuranApplicationComponentProvider, .setWorkerFactory(quranWorkerFactory) .build() + /** + * Progress keeps each reading bookmark's moves and checks the daily reminder (its data is only + * readable once the user unlocked, as WorkManager is only initialized then). + */ + open fun startProgress() { + if (UserManagerCompat.isUserUnlocked(this)) progressStartup.start() + } + open fun initializeWorkManager() { if (UserManagerCompat.isUserUnlocked(this)) { WorkManager.initialize(this, workManagerConfiguration) diff --git a/app/src/main/java/com/quran/labs/androidquran/data/AyahInfoDatabaseHandler.java b/app/src/main/java/com/quran/labs/androidquran/data/AyahInfoDatabaseHandler.java index 74821bf094..fe7481abd2 100644 --- a/app/src/main/java/com/quran/labs/androidquran/data/AyahInfoDatabaseHandler.java +++ b/app/src/main/java/com/quran/labs/androidquran/data/AyahInfoDatabaseHandler.java @@ -6,6 +6,7 @@ import android.graphics.RectF; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import com.quran.labs.androidquran.database.DatabaseUtils; import com.quran.labs.androidquran.util.QuranFileUtils; @@ -14,6 +15,8 @@ import com.quran.page.common.data.AyahMarkerLocation; import com.quran.page.common.data.PageCoordinates; import com.quran.page.common.data.SuraHeaderLocation; +import com.quran.page.common.data.coordinates.GlyphSize; +import com.quran.page.common.data.coordinates.GlyphTypeResolver; import com.quran.page.common.data.coordinates.PageGlyphsCoords; import java.io.File; @@ -42,9 +45,17 @@ public class AyahInfoDatabaseHandler { private final SQLiteDatabase database; private final boolean hasGlyphData; + @Nullable private final GlyphTypeResolver glyphTypeResolver; static AyahInfoDatabaseHandler getAyahInfoDatabaseHandler( String databaseName, QuranFileUtils quranFileUtils) { + return getAyahInfoDatabaseHandler(databaseName, quranFileUtils, null); + } + + static AyahInfoDatabaseHandler getAyahInfoDatabaseHandler( + String databaseName, + QuranFileUtils quranFileUtils, + @Nullable GlyphTypeResolver glyphTypeResolver) { final File currentAyahDatabaseDirectory = quranFileUtils.getQuranAyahDatabaseDirectory(); if (!currentAyahDatabaseDirectory.equals(quranDatabaseDirectory)) { quranDatabaseDirectory = currentAyahDatabaseDirectory; @@ -54,7 +65,8 @@ static AyahInfoDatabaseHandler getAyahInfoDatabaseHandler( AyahInfoDatabaseHandler handler = ayahInfoCache.get(databaseName); if (handler == null) { try { - AyahInfoDatabaseHandler db = new AyahInfoDatabaseHandler(databaseName, quranFileUtils); + AyahInfoDatabaseHandler db = + new AyahInfoDatabaseHandler(databaseName, quranFileUtils, glyphTypeResolver); if (db.validDatabase()) { ayahInfoCache.put(databaseName, db); handler = db; @@ -82,11 +94,13 @@ private static void clearAyahInfoCache() { } private AyahInfoDatabaseHandler(String databaseName, - QuranFileUtils quranFileUtils) throws SQLException { + QuranFileUtils quranFileUtils, + @Nullable GlyphTypeResolver glyphTypeResolver) throws SQLException { File base = quranFileUtils.getQuranAyahDatabaseDirectory(); File path = new File(base, databaseName); database = SQLiteDatabase.openDatabase(path.getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); hasGlyphData = quranFileUtils.getAyahInfoDbHasGlyphData(); + this.glyphTypeResolver = glyphTypeResolver; } private boolean validDatabase() { @@ -128,6 +142,10 @@ private RectF getPageBounds(int page) { public AyahCoordinates getVersesBoundsForPage(int page) { boolean includeGlyphData = hasGlyphData && haveGlyphData(); GlyphsBuilder glyphsBuilder = new GlyphsBuilder(); + Map derivedTypes = + (!includeGlyphData && glyphTypeResolver != null) ? derivedGlyphTypesForPage(page) : null; + GlyphsBuilder wordGlyphsBuilder = derivedTypes != null ? new GlyphsBuilder() : null; + Map wordNumbers = new HashMap<>(); Map> ayahBounds = new HashMap<>(); Cursor cursor = null; try { @@ -142,13 +160,26 @@ public AyahCoordinates getVersesBoundsForPage(int page) { int maxX = cursor.getInt(7); int maxY = cursor.getInt(8); + String key = sura + ":" + ayah; if (includeGlyphData) { String glyphType = cursor.getString(9); RectF r = new RectF(minX, minY, maxX, maxY); glyphsBuilder.append(sura, ayah, position, line, glyphType, r); + } else if (wordGlyphsBuilder != null) { + String types = derivedTypes.get(key); + if (types != null) { + int[] words = wordNumbers.get(key); + if (words == null) { + words = wordNumbers(types); + wordNumbers.put(key, words); + } + char type = types.charAt(position - 1); + Integer wordPosition = type == GlyphTypeResolver.WORD ? words[position - 1] : null; + RectF r = new RectF(minX, minY, maxX, maxY); + wordGlyphsBuilder.append(sura, ayah, position, line, glyphTypeName(type), r, wordPosition); + } } - String key = sura + ":" + ayah; List bounds = ayahBounds.get(key); if (bounds == null) { bounds = new ArrayList<>(); @@ -173,8 +204,89 @@ public AyahCoordinates getVersesBoundsForPage(int page) { PageGlyphsCoords glyphCoords = includeGlyphData ? new PageGlyphsCoords(page, glyphsBuilder.build()) : null; + PageGlyphsCoords wordGlyphCoords = wordGlyphsBuilder != null ? + new PageGlyphsCoords(page, wordGlyphsBuilder.build()) : null; + + return new AyahCoordinates(page, ayahBounds, glyphCoords, new HashMap<>(), 0f, wordGlyphCoords); + } - return new AyahCoordinates(page, ayahBounds, glyphCoords); + /** + * Glyph types for the ayat on this page from the {@link GlyphTypeResolver}, keyed by "sura:ayah", + * worked out from the sizes of each ayah's glyphs in this database (every page type has its own + * font). An ayah is left out (so it keeps ayah level behavior) if its glyphs can't be told apart + * or its positions aren't numbered 1..n. + */ + @Nullable + private Map derivedGlyphTypesForPage(int page) { + Map result = new HashMap<>(); + Cursor cursor = null; + try { + // all glyphs of every ayah that is (even partly) on this page; a join rather than a row value + // comparison (SQLite 3.15+, API 26+) so that both lookups use an index + cursor = database.rawQuery( + "SELECT g." + COL_SURA + ", g." + COL_AYAH + ", g." + COL_POSITION + ", g." + MAX_X + + " - g." + MIN_X + ", g." + MAX_Y + " - g." + MIN_Y + + " FROM (SELECT DISTINCT " + COL_SURA + ", " + COL_AYAH + " FROM " + GLYPHS_TABLE + + " WHERE " + COL_PAGE + " = ?) AS p JOIN " + GLYPHS_TABLE + " AS g ON g." + COL_SURA + + " = p." + COL_SURA + " AND g." + COL_AYAH + " = p." + COL_AYAH + + " ORDER BY g." + COL_SURA + ", g." + COL_AYAH + ", g." + COL_POSITION, + new String[] { String.valueOf(page) }); + int sura = -1; + int ayah = -1; + List glyphs = new ArrayList<>(); + boolean numbered = true; + while (cursor.moveToNext()) { + int rowSura = cursor.getInt(0); + int rowAyah = cursor.getInt(1); + if (rowSura != sura || rowAyah != ayah) { + addDerivedTypes(result, sura, ayah, glyphs, numbered); + sura = rowSura; + ayah = rowAyah; + glyphs = new ArrayList<>(); + numbered = true; + } + numbered &= cursor.getInt(2) == glyphs.size() + 1; + glyphs.add(new GlyphSize(cursor.getInt(3), cursor.getInt(4))); + } + addDerivedTypes(result, sura, ayah, glyphs, numbered); + } catch (SQLException e) { + return null; + } finally { + DatabaseUtils.closeCursor(cursor); + } + return result; + } + + private void addDerivedTypes( + Map result, int sura, int ayah, List glyphs, boolean numbered) { + if (glyphs.isEmpty() || !numbered || glyphTypeResolver == null) return; + String types = glyphTypeResolver.glyphTypes(sura, ayah, glyphs); + if (types != null && types.length() == glyphs.size()) { + result.put(sura + ":" + ayah, types); + } + } + + /** The word number of each glyph of an ayah, counting only the glyphs that are words. */ + private static int[] wordNumbers(String types) { + int[] result = new int[types.length()]; + int words = 0; + for (int i = 0; i < types.length(); i++) { + if (types.charAt(i) == GlyphTypeResolver.WORD) { + words++; + } + result[i] = words; + } + return result; + } + + private static String glyphTypeName(char type) { + switch (type) { + case GlyphTypeResolver.WORD: return GlyphsBuilder.WORD; + case GlyphTypeResolver.PAUSE: return GlyphsBuilder.PAUSE; + case GlyphTypeResolver.SAJDAH: return GlyphsBuilder.SAJDAH; + case GlyphTypeResolver.HIZB: return GlyphsBuilder.HIZB; + default: return GlyphsBuilder.END; + } } private boolean haveVerseMarkerData() { diff --git a/app/src/main/java/com/quran/labs/androidquran/data/AyahInfoDatabaseProvider.kt b/app/src/main/java/com/quran/labs/androidquran/data/AyahInfoDatabaseProvider.kt index e70e7e5426..b392303b35 100644 --- a/app/src/main/java/com/quran/labs/androidquran/data/AyahInfoDatabaseProvider.kt +++ b/app/src/main/java/com/quran/labs/androidquran/data/AyahInfoDatabaseProvider.kt @@ -4,13 +4,15 @@ import android.content.Context import com.quran.data.di.ActivityScope import com.quran.labs.androidquran.util.QuranFileUtils import com.quran.mobile.di.qualifier.ApplicationContext +import com.quran.page.common.data.coordinates.GlyphTypeResolver import dev.zacsweers.metro.Inject @ActivityScope class AyahInfoDatabaseProvider @Inject constructor( @ApplicationContext private val context: Context, private val widthParameter: String, - private val quranFileUtils: QuranFileUtils + private val quranFileUtils: QuranFileUtils, + private val glyphTypeResolvers: Set ) { private var databaseHandler: AyahInfoDatabaseHandler? = null @@ -19,7 +21,8 @@ class AyahInfoDatabaseProvider @Inject constructor( val filename = quranFileUtils.getAyaPositionFileName(widthParameter) databaseHandler = AyahInfoDatabaseHandler.getAyahInfoDatabaseHandler( filename, - quranFileUtils + quranFileUtils, + glyphTypeResolvers.firstOrNull() ) } return databaseHandler diff --git a/app/src/main/java/com/quran/labs/androidquran/data/Constants.kt b/app/src/main/java/com/quran/labs/androidquran/data/Constants.kt index 55c7933eca..b094961db3 100644 --- a/app/src/main/java/com/quran/labs/androidquran/data/Constants.kt +++ b/app/src/main/java/com/quran/labs/androidquran/data/Constants.kt @@ -63,6 +63,7 @@ object Constants { const val PREF_HAVE_UPDATED_TRANSLATIONS = "haveUpdatedTranslations" const val PREF_USE_NEW_BACKGROUND = "useNewBackground" const val PREF_USE_VOLUME_KEY_NAV = "volumeKeyNavigation" + const val PREF_SWAP_VOLUME_KEYS = "swapVolumeKeys" const val PREF_SORT_BOOKMARKS = "sortBookmarks" const val PREF_GROUP_BOOKMARKS_BY_TAG = "groupBookmarksByTag" const val PREF_SHOW_RECENTS = "showRecents" diff --git a/app/src/main/java/com/quran/labs/androidquran/data/GlyphsBuilder.kt b/app/src/main/java/com/quran/labs/androidquran/data/GlyphsBuilder.kt index 6c568f344b..1f23390ba7 100644 --- a/app/src/main/java/com/quran/labs/androidquran/data/GlyphsBuilder.kt +++ b/app/src/main/java/com/quran/labs/androidquran/data/GlyphsBuilder.kt @@ -23,7 +23,21 @@ class GlyphsBuilder { private var curAyah: SuraAyah? = null private var nextWordPos: Int = 1 - fun append(sura: Int, ayah: Int, glyphPosition: Int, line: Int, type: String, bounds: RectF) { + /** + * @param wordPosition the word position of a [WORD] glyph when it is known up front (e.g. when an + * ayah continues from the previous page and the first word on this page isn't word 1). When + * null, words are numbered in the order they are appended. + */ + @JvmOverloads + fun append( + sura: Int, + ayah: Int, + glyphPosition: Int, + line: Int, + type: String, + bounds: RectF, + wordPosition: Int? = null + ) { val suraAyah = SuraAyah(sura, ayah) // If we're on a different ayah, reset word position to 1 @@ -37,7 +51,11 @@ class GlyphsBuilder { SAJDAH -> SajdahGlyph(suraAyah, glyphPosition) PAUSE -> PauseGlyph(suraAyah, glyphPosition) END -> AyahEndGlyph(suraAyah, glyphPosition) - WORD -> WordGlyph(suraAyah, glyphPosition, nextWordPos++) + WORD -> { + val position = wordPosition ?: nextWordPos + nextWordPos = position + 1 + WordGlyph(suraAyah, glyphPosition, position) + } else -> throw IllegalArgumentException("Unknown glyph type $type") } @@ -48,7 +66,7 @@ class GlyphsBuilder { // Glyph Type keys // Note: it's important these types match what is defined in the ayahinfo db - private companion object { + companion object { const val HIZB = "hizb" const val SAJDAH = "sajdah" const val PAUSE = "pause" diff --git a/app/src/main/java/com/quran/labs/androidquran/di/component/activity/ActivityComponent.kt b/app/src/main/java/com/quran/labs/androidquran/di/component/activity/ActivityComponent.kt index d840074197..7537cc964f 100644 --- a/app/src/main/java/com/quran/labs/androidquran/di/component/activity/ActivityComponent.kt +++ b/app/src/main/java/com/quran/labs/androidquran/di/component/activity/ActivityComponent.kt @@ -3,6 +3,8 @@ package com.quran.labs.androidquran.di.component.activity import android.content.Context import com.quran.data.di.ActivityLevelScope import com.quran.data.di.ActivityScope +import com.quran.labs.androidquran.model.quran.CoordinatesModelInterface +import com.quran.labs.androidquran.ui.helpers.QuranPageLoaderInterface import com.quran.mobile.di.qualifier.ActivityContext import dev.zacsweers.metro.GraphExtension import dev.zacsweers.metro.Provides @@ -14,6 +16,10 @@ interface ActivityComponent { fun pagerActivityComponentFactory(): PagerActivityComponent.Factory fun quranActivityComponentFactory(): QuranActivityComponent.Factory + // pages outside the reading screen (AppPagePreviews) + fun quranPageLoader(): QuranPageLoaderInterface + fun coordinatesModel(): CoordinatesModelInterface + @GraphExtension.Factory interface Factory { fun generate(@Provides @ActivityContext context: Context): ActivityComponent diff --git a/app/src/main/java/com/quran/labs/androidquran/di/module/application/ApplicationModule.kt b/app/src/main/java/com/quran/labs/androidquran/di/module/application/ApplicationModule.kt index 60137efe43..c5e2e97862 100644 --- a/app/src/main/java/com/quran/labs/androidquran/di/module/application/ApplicationModule.kt +++ b/app/src/main/java/com/quran/labs/androidquran/di/module/application/ApplicationModule.kt @@ -27,6 +27,7 @@ import com.quran.mobile.di.ExtraPreferencesProvider import com.quran.mobile.di.ExtraScreenProvider import com.quran.mobile.di.qualifier.ApplicationContext import com.quran.page.common.data.QuranNaming +import com.quran.page.common.data.coordinates.GlyphTypeResolver import dev.zacsweers.metro.BindingContainer import dev.zacsweers.metro.ElementsIntoSet import dev.zacsweers.metro.Named @@ -125,6 +126,12 @@ object ApplicationModule { return emptySet() } + @Provides + @ElementsIntoSet + fun provideGlyphTypeResolvers(): Set { + return emptySet() + } + @Provides fun provideAudioUtilsInterface(impl: AudioUtils): AudioUtilsInterface = impl diff --git a/app/src/main/java/com/quran/labs/androidquran/feature/reading/bridge/AudioStatusRepositoryBridge.kt b/app/src/main/java/com/quran/labs/androidquran/feature/reading/bridge/AudioStatusRepositoryBridge.kt index 21715ad171..017ceaf4bd 100644 --- a/app/src/main/java/com/quran/labs/androidquran/feature/reading/bridge/AudioStatusRepositoryBridge.kt +++ b/app/src/main/java/com/quran/labs/androidquran/feature/reading/bridge/AudioStatusRepositoryBridge.kt @@ -50,6 +50,7 @@ class AudioStatusRepositoryBridge( AudioBarEvent.Stop -> audioBarListener.onStopPressed() AudioBarEvent.EndSession -> audioBarRecitationListener.onEndRecitationSessionPressed() AudioBarEvent.HideVerses -> audioBarRecitationListener.onHideVersesPressed() + AudioBarEvent.RecitationHint -> audioBarRecitationListener.onRecitationHintPressed() AudioBarEvent.PauseRecitation -> audioBarRecitationListener.onPauseRecitationPressed() AudioBarEvent.PlayRecitation -> audioBarRecitationListener.onPlayRecitationPressed() AudioBarEvent.Recitation, AudioBarEvent.Record -> audioBarRecitationListener.onRecitationPressed() diff --git a/app/src/main/java/com/quran/labs/androidquran/feature/reading/presenter/ReadingBookmarkPresenter.kt b/app/src/main/java/com/quran/labs/androidquran/feature/reading/presenter/ReadingBookmarkPresenter.kt index 112255db62..a395baf614 100644 --- a/app/src/main/java/com/quran/labs/androidquran/feature/reading/presenter/ReadingBookmarkPresenter.kt +++ b/app/src/main/java/com/quran/labs/androidquran/feature/reading/presenter/ReadingBookmarkPresenter.kt @@ -15,7 +15,6 @@ import com.quran.labs.androidquran.util.QuranSettings import dev.zacsweers.metro.ContributesBinding import dev.zacsweers.metro.Inject import dev.zacsweers.metro.SingleIn -import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.MainScope import kotlinx.coroutines.delay @@ -24,7 +23,6 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext import kotlin.time.Duration.Companion.seconds @SingleIn(AppScope::class) @@ -49,7 +47,7 @@ class ReadingBookmarkPresenter @Inject constructor( ) { page, bookmarks -> page to bookmarks } .onEach { (page, bookmarks) -> readingBookmarks = bookmarks - // any of the three pins sitting on this page fills the action bar icon + // any pin sitting on this page fills the action bar icon screen.setPageReadingBookmarkSelected( bookmarks.any { it.isAt(ReadingBookmarkTarget.Page(page)) } ) @@ -59,10 +57,10 @@ class ReadingBookmarkPresenter @Inject constructor( fun unbind(screen: Screen) { if (this.screen === screen) { + // the screen is going away (or just pausing): a toast left up would outlive its timeout + dismissToast() this.screen = null readingBookmarks = emptyList() - toastTimeoutJob?.cancel() - toastTimeoutJob = null currentJob?.cancel() currentJob = null } @@ -110,9 +108,9 @@ class ReadingBookmarkPresenter @Inject constructor( private fun showToast(change: ReadingBookmarkChange, isEducation: Boolean) { toastTimeoutJob?.cancel() - toastTimeoutJob = appCoroutineScope.launch { + toastTimeoutJob = scope.launch { delay(if (isEducation) educationTimeout else changeTimeout) - withContext(Dispatchers.Main) { dismissToast() } + dismissToast() } screen?.showReadingBookmarkChangedToast( @@ -166,8 +164,8 @@ class ReadingBookmarkPresenter @Inject constructor( } companion object { - val educationTimeout = 9.seconds - val changeTimeout = 5.seconds + val educationTimeout = 20.seconds + val changeTimeout = 10.seconds } } diff --git a/app/src/main/java/com/quran/labs/androidquran/feature/reading/presenter/ReadingTimePresenter.kt b/app/src/main/java/com/quran/labs/androidquran/feature/reading/presenter/ReadingTimePresenter.kt new file mode 100644 index 0000000000..d58e03c6aa --- /dev/null +++ b/app/src/main/java/com/quran/labs/androidquran/feature/reading/presenter/ReadingTimePresenter.kt @@ -0,0 +1,97 @@ +package com.quran.labs.androidquran.feature.reading.presenter + +import com.quran.data.constant.DependencyInjectionConstants +import com.quran.data.di.ActivityScope +import com.quran.mobile.progress.reading.ReaderPresence +import com.quran.mobile.progress.reading.ReadingTimeAccumulator +import com.quran.mobile.progress.reading.ReadingTimeLog +import com.quran.mobile.progress.time.ProgressClock +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.Named +import kotlinx.coroutines.Job +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch + +/** + * Keeps how long Quran pages are open in the reader, for Progress (see [ReadingTimeAccumulator]): + * while the reader is resumed, by the page or pages on screen, saved every minute and when it's left. + */ +@ActivityScope +class ReadingTimePresenter @Inject constructor( + private val readingTimeLog: ReadingTimeLog, + private val readerPresence: ReaderPresence, + private val clock: ProgressClock, + @param:Named(DependencyInjectionConstants.CURRENT_PAGE_TYPE) private val pageType: String, +) { + private val scope = MainScope() + private val accumulator = ReadingTimeAccumulator(zone = { clock.zone() }) + private var pagesJob: Job? = null + private var tickJob: Job? = null + private var lastSavedAt = 0L + + /** Starts counting the pages [pageFlow] shows; [visiblePages] gives all those on screen with one. */ + fun bind(pageFlow: Flow, visiblePages: (Int) -> Set) { + cancelJobs() + readerPresence.open = true + lastSavedAt = clock.nowMs() + var resumed = false + pagesJob = pageFlow + .onEach { page -> + val now = clock.nowMs() + if (resumed) { + accumulator.onPages(now, visiblePages(page)) + } else { + accumulator.onResume(now, visiblePages(page)) + resumed = true + } + } + .launchIn(scope) + tickJob = scope.launch { + while (isActive) { + delay(TICK_MS) + val now = clock.nowMs() + accumulator.tick(now) + if (now - lastSavedAt >= SAVE_MS) save(now) + } + } + } + + /** The user touched the reader (e.g. scrolling a translation): they're still reading. */ + fun onInteraction() { + if (pagesJob != null) accumulator.onInteraction(clock.nowMs()) + } + + fun unbind() { + if (pagesJob == null) return + cancelJobs() + val now = clock.nowMs() + accumulator.onPause(now) + readerPresence.open = false + save(now) + } + + private fun cancelJobs() { + pagesJob?.cancel() + tickJob?.cancel() + pagesJob = null + tickJob = null + } + + private fun save(now: Long) { + lastSavedAt = now + val times = accumulator.drain() + if (times.isEmpty()) return + scope.launch(NonCancellable) { readingTimeLog.add(times, pageType, now) } + } + + private companion object { + const val TICK_MS = 30_000L + const val SAVE_MS = 60_000L + } +} diff --git a/app/src/main/java/com/quran/labs/androidquran/feature/reading/presenter/recitation/PagerActivityRecitationPresenter.kt b/app/src/main/java/com/quran/labs/androidquran/feature/reading/presenter/recitation/PagerActivityRecitationPresenter.kt index e2796745ec..cf4136ee96 100644 --- a/app/src/main/java/com/quran/labs/androidquran/feature/reading/presenter/recitation/PagerActivityRecitationPresenter.kt +++ b/app/src/main/java/com/quran/labs/androidquran/feature/reading/presenter/recitation/PagerActivityRecitationPresenter.kt @@ -21,11 +21,14 @@ import com.quran.recitation.events.RecitationEventPresenter import com.quran.recitation.events.RecitationSelection import com.quran.recitation.presenter.RecitationPlaybackPresenter import com.quran.recitation.presenter.RecitationPresenter +import com.quran.recitation.presenter.RecitationStart import com.quran.recitation.presenter.RecitationSettings import dev.zacsweers.metro.Inject import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import timber.log.Timber @@ -47,15 +50,25 @@ class PagerActivityRecitationPresenter @Inject constructor( val ayahToolBar: () -> AyahToolBar?, val ensurePage: (ayah: SuraAyah) -> Unit, val showSlider: (sliderPage: Int) -> Unit, + /** Called when a recitation session starts or ends (e.g. to handle back presses). */ + val onSessionActiveChanged: (isActive: Boolean) -> Unit = {}, + /** Stops any Quran audio that is playing, so it doesn't compete with the user's recitation. */ + val stopAudio: () -> Unit = {}, + val isShowingTranslation: () -> Boolean = { false }, + val switchToQuran: () -> Unit = {}, ) - private fun isRecitationEnabled(): Boolean { + fun isRecitationEnabled(): Boolean { return recitationPresenter.isRecitationEnabled() } fun bind(activity: PagerActivity, bridge: Bridge) { if (!isRecitationEnabled()) return this.bridge = bridge + recitationPresenter.setReadingScreen(::pagesOnScreen) { start -> + if (!recitationEventPresenter.hasRecitationSession()) prepareForNewSession() + recitationPresenter.startOrStopRecitation({ firstAyahToMemorize() }, start) + } activity.lifecycle.addObserver(this) } @@ -93,6 +106,13 @@ class PagerActivityRecitationPresenter @Inject constructor( .onEach { onRecitationEnabledStateChanged(it) } .launchIn(scope) + // Session start / end + recitationEventPresenter.recitationSessionFlow + .map { it != null } + .distinctUntilChanged() + .onEach { bridge.onSessionActiveChanged(it) } + .launchIn(scope) + // Recitation Events recitationEventPresenter.recitationChangeFlow .onEach { onRecitationChange(it) } @@ -142,17 +162,41 @@ class PagerActivityRecitationPresenter @Inject constructor( playback.ayah()?.let { bridge.ensurePage(it) } } + fun hasSession(): Boolean = isRecitationEnabled() && recitationEventPresenter.hasRecitationSession() + + /** + * The toolbar's "Memorize" action: starts from the selected ayah (or the first ayah on the page) + * or ends the current session. + */ + fun onMemorizeMenuPressed() { + if (!isRecitationEnabled()) return + if (recitationEventPresenter.hasRecitationSession()) { + recitationPresenter.endSession() + } else { + prepareForNewSession() + recitationPresenter.startOrStopRecitation({ firstAyahToMemorize() }) + } + } + + private fun prepareForNewSession() { + bridge.stopAudio() + if (bridge.isShowingTranslation()) bridge.switchToQuran() + } + // AudioBarRecitationListener + // the audio bar's microphone (and "Recite from here"): the user chooses how to recite override fun onRecitationPressed() { - recitationPresenter.startOrStopRecitation({ ayahToStartFrom() }) + if (!recitationEventPresenter.hasRecitationSession()) prepareForNewSession() + recitationPresenter.startOrStopRecitation({ firstAyahToMemorize() }, RecitationStart.CHOOSE) } override fun onRecitationLongPressed() { - recitationPresenter.startOrStopRecitation({ ayahToStartFrom() }, true) + recitationPresenter.startOrStopRecitation({ firstAyahToMemorize() }, RecitationStart.CHOOSE_ALL) } override fun onRecitationTranscriptPressed() { + if (!recitationPresenter.supportsTranscript()) return if (recitationEventPresenter.hasRecitationSession()) { bridge.showSlider(SlidingPagerAdapter.TRANSCRIPT_PAGE) } else { @@ -160,6 +204,10 @@ class PagerActivityRecitationPresenter @Inject constructor( } } + override fun onRecitationHintPressed() { + recitationPresenter.onHintRequested() + } + override fun onHideVersesPressed() { recitationSettings.toggleAyahVisibility() } @@ -176,20 +224,26 @@ class PagerActivityRecitationPresenter @Inject constructor( recitationPlaybackPresenter.pauseIfPlaying() } - private fun ayahToStartFrom(): SuraAyah { - val page = if (bridge.isDualPageVisible()) { - // subtracting 1 because in dual mode currentPage gives 2, 4, 6.. instead of 1, 3, 5.. - // but we want to start from the first ayah of the first visible page - bridge.currentPage() - 1 - } else { - bridge.currentPage() - } - - // If we're in ayah mode, start from selected ayah + private fun firstAyahToMemorize(): SuraAyah { + val page = pagesOnScreen().first() return readingEventPresenter.currentAyahSelection().startSuraAyah() - // If a sura starts on this page, assume the user meant to start there - ?: quranInfo.getListOfSurahWithStartingOnPage(page).firstNotNullOfOrNull { SuraAyah(it, 1) } - // Otherwise, start from the beginning of the page ?: SuraAyah(quranInfo.getSuraOnPage(page), quranInfo.getFirstAyahOnPage(page)) } + + private fun pagesOnScreen(): List = + pagesOnScreen(bridge.currentPage(), bridge.isDualPageVisible(), quranInfo.numberOfPages) + + internal companion object { + /** + * The pages on screen. In dual page mode, currentPage is the first page of the pair (1, 3, 5...) + * and the pair shows it and the next one, which a mushaf with an odd number of pages lacks at + * its end. + */ + fun pagesOnScreen(currentPage: Int, isDualPageVisible: Boolean, numberOfPages: Int): List = + if (isDualPageVisible) { + listOf(currentPage, currentPage + 1).filter { it <= numberOfPages } + } else { + listOf(currentPage) + } + } } diff --git a/app/src/main/java/com/quran/labs/androidquran/feature/reading/preview/AppPagePreviews.kt b/app/src/main/java/com/quran/labs/androidquran/feature/reading/preview/AppPagePreviews.kt new file mode 100644 index 0000000000..6b830c759f --- /dev/null +++ b/app/src/main/java/com/quran/labs/androidquran/feature/reading/preview/AppPagePreviews.kt @@ -0,0 +1,239 @@ +package com.quran.labs.androidquran.feature.reading.preview + +import android.annotation.SuppressLint +import android.app.Activity +import android.view.MotionEvent +import android.view.View +import androidx.annotation.StringRes +import androidx.core.graphics.drawable.toDrawable +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import com.quran.data.core.QuranInfo +import com.quran.data.di.AppScope +import com.quran.data.model.AyahGlyph +import com.quran.data.model.SuraAyah +import com.quran.data.model.highlight.HighlightType +import com.quran.labs.androidquran.QuranApplication +import com.quran.labs.androidquran.R +import com.quran.labs.androidquran.common.Response +import com.quran.labs.androidquran.data.QuranDisplayData +import com.quran.labs.androidquran.model.quran.CoordinatesModelInterface +import com.quran.labs.androidquran.ui.helpers.AyahSelectedListener +import com.quran.labs.androidquran.ui.helpers.QuranDisplayHelper +import com.quran.labs.androidquran.ui.helpers.QuranPageLoaderInterface +import com.quran.labs.androidquran.ui.util.ImageAyahUtils +import com.quran.labs.androidquran.ui.util.PageController +import com.quran.labs.androidquran.util.QuranSettings +import com.quran.labs.androidquran.util.QuranUtils +import com.quran.labs.androidquran.view.QuranImagePageLayout +import com.quran.page.common.data.AyahCoordinates +import com.quran.page.common.data.PageCoordinates +import com.quran.page.common.draw.ImageDrawHelper +import com.quran.recitation.pages.PagePreview +import com.quran.recitation.pages.PagePreviews +import com.quran.recitation.pages.PageRenderer +import com.quran.recitation.presenter.RecitationHighlightsPresenter.HighlightAction +import dev.zacsweers.metro.ContributesBinding +import dev.zacsweers.metro.Inject +import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers +import io.reactivex.rxjava3.disposables.CompositeDisposable + +/** + * Mushaf pages outside the reading screen (e.g. a recorded session played back on its pages), + * loaded and drawn as [com.quran.labs.androidquran.ui.fragment.QuranPageFragment] draws them. + */ +@ContributesBinding(AppScope::class) +class AppPagePreviews @Inject constructor( + private val quranSettings: QuranSettings, + private val quranInfo: QuranInfo, + private val quranDisplayData: QuranDisplayData, + private val imageDrawHelpers: Set, +) : PagePreviews { + + override fun open(activity: Activity): PageRenderer { + // the activity's own graph: its image width, as the reading screen's + val component = (activity.application as QuranApplication).applicationComponent + .activityComponentFactory() + .generate(activity) + return Renderer(activity, component.quranPageLoader(), component.coordinatesModel()) + } + + private inner class Renderer( + private val activity: Activity, + private val loader: QuranPageLoaderInterface, + private val coordinates: CoordinatesModelInterface, + ) : PageRenderer { + private val open = LinkedHashSet() + + override val isNightMode: Boolean get() = quranSettings.isNightMode + + override fun page(page: Int, onTapped: (ayah: SuraAyah, word: Int?) -> Unit): PagePreview = + Preview(activity, page, loader, coordinates, onTapped) { open -= it }.also { open += it } + + override fun close() { + open.toList().forEach { it.release() } + } + } + + private inner class Preview( + private val activity: Activity, + private val page: Int, + private val loader: QuranPageLoaderInterface, + private val coordinatesModel: CoordinatesModelInterface, + private val onTapped: (SuraAyah, Int?) -> Unit, + private val onReleased: (Preview) -> Unit, + ) : PagePreview, PageController { + // fits the page in whatever room it has, in landscape too (no scrolling) + private val layout = object : QuranImagePageLayout(activity) { + override fun shouldWrapWithScrollView(): Boolean = false + } + private val image = layout.getImageView() + private val loading = CompositeDisposable() + private var ayahCoordinates: AyahCoordinates? = null + // what should be highlighted, by type (word -1: a whole ayah) + private val wanted = LinkedHashMap>>() + + override val view: View get() = layout + + init { + layout.setPageController(this, page, quranInfo.skip) + layout.updateView(quranSettings) + // not at the top of a window: no room to keep for a display cutout + ViewCompat.setOnApplyWindowInsetsListener(layout) { _, _ -> WindowInsetsCompat.CONSUMED } + loadImage() + loadCoordinates() + } + + private fun loadImage() { + loading.add( + loader.loadPages(arrayOf(page)) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe( + { response -> + val bitmap = response.bitmap + if (bitmap != null) { + layout.hideError() + image.setImageDrawable(bitmap.toDrawable(activity.resources)) + } else { + layout.showError(errorMessage(response.errorCode)) + } + }, + { layout.showError(R.string.download_error_general) }, + ) + ) + } + + private fun loadCoordinates() { + loading.add( + coordinatesModel.getPageCoordinates(quranSettings.shouldOverlayPageInfo(), page) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(::setPageCoordinates, {}, ::loadAyahCoordinates) + ) + } + + private fun loadAyahCoordinates() { + loading.add( + coordinatesModel.getAyahCoordinates(page) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ coordinates -> + ayahCoordinates = coordinates + image.setAyahData(coordinates) + // now that the words' places are known + wanted.keys.toList().forEach { redraw(it) } + image.invalidate() + }, {}) + ) + } + + /** As the reading screen's page (AyahImageTrackerItem.onSetPageBounds). */ + private fun setPageCoordinates(pageCoordinates: PageCoordinates) { + val pageBounds = pageCoordinates.pageBounds + if (!pageBounds.isEmpty) { + image.setPageBounds(pageBounds) + image.setOverlayText( + quranDisplayData.getSuraNameFromPage(activity, page, true), + quranDisplayData.getJuzDisplayStringForPage(activity, page), + QuranUtils.getLocalizedNumber(page), + QuranDisplayHelper.displayRub3(activity, quranInfo, page), + quranDisplayData.getManzilForPage(activity, page), + ) + } + // without it nothing is highlighted + image.setPageData(pageCoordinates, imageDrawHelpers) + image.invalidate() + } + + override fun apply(actions: List) { + val changed = LinkedHashSet() + for (action in actions) { + when (action) { + is HighlightAction.Highlight -> with(action.highlightInfo) { + wanted.getOrPut(highlightType) { LinkedHashSet() } += Triple(sura, ayah, word) + changed += highlightType + } + is HighlightAction.Unhighlight -> with(action.highlightInfo) { + wanted[highlightType]?.remove(Triple(sura, ayah, word)) + changed += highlightType + } + is HighlightAction.UnhighlightAll -> { + wanted.remove(action.highlightType) + changed += action.highlightType + } + } + } + changed.forEach { redraw(it) } + image.invalidate() + } + + /** Draws what is wanted of [type] (a word the page can't place is drawn as its ayah). */ + private fun redraw(type: HighlightType) { + image.unHighlight(type) + val coordinates = ayahCoordinates ?: return + val glyphs = coordinates.glyphCoordinates ?: coordinates.wordGlyphCoordinates + wanted[type]?.forEach { (sura, ayah, word) -> + val placed = word > 0 && glyphs?.getBoundsForWord(SuraAyah(sura, ayah), word)?.isNotEmpty() == true + image.highlightAyah(sura, ayah, if (placed) word else -1, type) + } + } + + override fun release() { + loading.dispose() + wanted.keys.forEach { image.unHighlight(it) } + wanted.clear() + image.setImageDrawable(null) + onReleased(this) + } + + @SuppressLint("ClickableViewAccessibility") + override fun handleTouchEvent(event: MotionEvent, eventType: AyahSelectedListener.EventType, page: Int): Boolean { + if (eventType != AyahSelectedListener.EventType.SINGLE_TAP) return false + val coordinates = ayahCoordinates ?: return false + val ayah = ImageAyahUtils.getAyahFromCoordinates(coordinates.ayahCoordinates, image, event.x, event.y) ?: return false + val glyphs = coordinates.glyphCoordinates ?: coordinates.wordGlyphCoordinates + val word = ImageAyahUtils.getPageXY(event.x, event.y, image) + ?.let { (x, y) -> glyphs?.getGlyphAtPoint(x, y) as? AyahGlyph.WordGlyph } + ?.takeIf { it.ayah == ayah } + ?.wordPosition + onTapped(ayah, word) + return true + } + + override fun handleRetryClicked() { + layout.hideError() + loadImage() + } + + override fun onScrollChanged(y: Float) {} + + override fun handleLongPress(suraAyah: SuraAyah) {} + + override fun endAyahMode() {} + } + + @StringRes + private fun errorMessage(errorCode: Int): Int = when (errorCode) { + Response.ERROR_SD_CARD_NOT_FOUND -> R.string.sdcard_error + Response.ERROR_NO_INTERNET, Response.ERROR_DOWNLOADING_ERROR -> R.string.download_error_network + else -> R.string.download_error_general + } +} diff --git a/app/src/main/java/com/quran/labs/androidquran/model/bookmark/BookmarkImportExportModel.kt b/app/src/main/java/com/quran/labs/androidquran/model/bookmark/BookmarkImportExportModel.kt index 93eea9653e..9561a04585 100644 --- a/app/src/main/java/com/quran/labs/androidquran/model/bookmark/BookmarkImportExportModel.kt +++ b/app/src/main/java/com/quran/labs/androidquran/model/bookmark/BookmarkImportExportModel.kt @@ -11,6 +11,7 @@ import com.quran.data.model.bookmark.BackupReadingBookmark import com.quran.data.model.bookmark.BookmarkData import com.quran.labs.androidquran.R import com.quran.mobile.bookmark.importdata.BookmarkBackupImportNormalizer +import com.quran.mobile.bookmark.importdata.LocalReadingBookmarkImporter import com.quran.mobile.bookmark.importdata.MobileSyncImporter import com.quran.mobile.bookmark.model.ReadingBookmarkPageMapper import com.quran.mobile.di.qualifier.ApplicationContext @@ -33,7 +34,8 @@ class BookmarkImportExportModel @Inject internal constructor( private val readingBookmarksDao: ReadingBookmarksDao, private val pageMapper: ReadingBookmarkPageMapper, private val backupImportNormalizer: BookmarkBackupImportNormalizer, - private val mobileSyncImporter: MobileSyncImporter + private val mobileSyncImporter: MobileSyncImporter, + private val localReadingBookmarkImporter: LocalReadingBookmarkImporter, ) { fun readBookmarks(source: BufferedSource): Single { return Single.defer { @@ -100,6 +102,12 @@ class BookmarkImportExportModel @Inject internal constructor( val pageType = pageMapper.currentPageType() val allTags = bookmarksDao.tags() val systemTagIds = allTags.filter { tag -> tag.isSystem }.mapTo(mutableSetOf()) { it.id } + val readingBookmarks = readingBookmarksDao.readingBookmarks() + .mapNotNull { bookmark -> + BackupReadingBookmark.fromReadingBookmark(bookmark) { sura, ayah -> + pageMapper.suraAyahToPage(sura, ayah, pageType) + } + } BookmarkData( tags = allTags.filterNot { tag -> tag.isSystem }, bookmarks = bookmarksDao.bookmarks(BookmarkSortOrder.SORT_DATE_ADDED) @@ -110,13 +118,9 @@ class BookmarkImportExportModel @Inject internal constructor( bookmark.copy(id = (index + 1).toString()).withTags(bookmark.tags - systemTagIds) }, recentPages = recentPagesDao.recentPages(), - readingBookmarks = readingBookmarksDao.readingBookmarks() - .mapNotNull { bookmark -> - BackupReadingBookmark.fromReadingBookmark(bookmark) { sura, ayah -> - pageMapper.suraAyahToPage(sura, ayah, pageType) - } - }, - pageType = pageType + readingBookmarks = readingBookmarks.filter { it.slot.synced }, + pageType = pageType, + localReadingBookmarks = readingBookmarks.filterNot { it.slot.synced }, ) } }.subscribeOn(Schedulers.io()) @@ -136,6 +140,7 @@ class BookmarkImportExportModel @Inject internal constructor( if (!importData.isEmpty()) { mobileSyncImporter.importData(importData, deleteExisting = false) } + localReadingBookmarkImporter.import(data.localReadingBookmarks, data.pageType) } companion object { diff --git a/app/src/main/java/com/quran/labs/androidquran/model/quran/CoordinatesModel.kt b/app/src/main/java/com/quran/labs/androidquran/model/quran/CoordinatesModel.kt index 8d5c021bb0..d79384aa01 100644 --- a/app/src/main/java/com/quran/labs/androidquran/model/quran/CoordinatesModel.kt +++ b/app/src/main/java/com/quran/labs/androidquran/model/quran/CoordinatesModel.kt @@ -68,7 +68,8 @@ class CoordinatesModel @Inject internal constructor( normalizedMap, ayahCoordinates.glyphCoordinates, ayahLineCoordinates, - pageProvider.ayahUnderlineRaiseRatio() + pageProvider.ayahUnderlineRaiseRatio(), + ayahCoordinates.wordGlyphCoordinates ) } diff --git a/app/src/main/java/com/quran/labs/androidquran/pageselect/PageSelectActivity.kt b/app/src/main/java/com/quran/labs/androidquran/pageselect/PageSelectActivity.kt index 0cf0a23e2b..96931cd324 100644 --- a/app/src/main/java/com/quran/labs/androidquran/pageselect/PageSelectActivity.kt +++ b/app/src/main/java/com/quran/labs/androidquran/pageselect/PageSelectActivity.kt @@ -25,6 +25,7 @@ class PageSelectActivity : AppCompatActivity() { private lateinit var viewPager: ViewPager private var isProcessing = false + private var showedCurrentPageType = false override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() @@ -83,6 +84,12 @@ class PageSelectActivity : AppCompatActivity() { fun onUpdatedData(data: List) { adapter.replaceItems(data, viewPager) + if (!showedCurrentPageType && data.isNotEmpty()) { + // open on the page type in use + showedCurrentPageType = true + val current = data.indexOfFirst { it.pageType == quranSettings.pageType } + if (current > 0) viewPager.setCurrentItem(current, false) + } } private fun onPageTypeSelected(type: String) { diff --git a/app/src/main/java/com/quran/labs/androidquran/pageselect/PageSelectPresenter.kt b/app/src/main/java/com/quran/labs/androidquran/pageselect/PageSelectPresenter.kt index 833259a024..43a685f483 100644 --- a/app/src/main/java/com/quran/labs/androidquran/pageselect/PageSelectPresenter.kt +++ b/app/src/main/java/com/quran/labs/androidquran/pageselect/PageSelectPresenter.kt @@ -33,7 +33,7 @@ constructor( File(outputPath, ".nomedia").createNewFile() } - val data = pageTypes.map { + val data = pageTypes.entries.sortedBy { order(it.key) }.map { val provider = it.value val previewImage = File(outputPath, "${it.key}.png") val downloadedImage = if (previewImage.exists()) { @@ -65,6 +65,9 @@ constructor( currentView?.onUpdatedData(data) } + // the classic Madani mushaf first, then the newer Madani prints, then the others + private fun order(pageType: String) = PAGE_TYPE_ORDER.indexOf(pageType).takeIf { it >= 0 } ?: PAGE_TYPE_ORDER.size + override fun bind(what: PageSelectActivity) { currentView = what generateData() @@ -77,4 +80,10 @@ constructor( downloadingSet.clear() } } + + private companion object { + val PAGE_TYPE_ORDER = listOf( + "madani", "new_madani", "new_madani_1441", "madani_1441_lines", "new_madani_1439_lines", "tajweed", "shemerly" + ) + } } diff --git a/app/src/main/java/com/quran/labs/androidquran/presenter/quran/ayahtracker/AyahImageTrackerItem.kt b/app/src/main/java/com/quran/labs/androidquran/presenter/quran/ayahtracker/AyahImageTrackerItem.kt index b22b6fa090..b3f78941f3 100644 --- a/app/src/main/java/com/quran/labs/androidquran/presenter/quran/ayahtracker/AyahImageTrackerItem.kt +++ b/app/src/main/java/com/quran/labs/androidquran/presenter/quran/ayahtracker/AyahImageTrackerItem.kt @@ -51,7 +51,7 @@ open class AyahImageTrackerItem @JvmOverloads constructor( if (this.page == ayahCoordinates.page) { val coordinates = ayahCoordinates.ayahCoordinates this.coordinates = coordinates - this.pageGlyphsCoords = ayahCoordinates.glyphCoordinates + this.pageGlyphsCoords = ayahCoordinates.glyphCoordinates ?: ayahCoordinates.wordGlyphCoordinates if (coordinates.isNotEmpty()) { ayahView.setAyahData(ayahCoordinates) ayahView.invalidate() diff --git a/app/src/main/java/com/quran/labs/androidquran/presenter/quran/ayahtracker/AyahTrackerPresenter.kt b/app/src/main/java/com/quran/labs/androidquran/presenter/quran/ayahtracker/AyahTrackerPresenter.kt index b6d1414921..7346f0dec0 100644 --- a/app/src/main/java/com/quran/labs/androidquran/presenter/quran/ayahtracker/AyahTrackerPresenter.kt +++ b/app/src/main/java/com/quran/labs/androidquran/presenter/quran/ayahtracker/AyahTrackerPresenter.kt @@ -496,23 +496,39 @@ class AyahTrackerPresenter @Inject constructor( } private fun highlight(highlightInfo: HighlightInfo) { - val page = quranInfo.getPageFromSuraAyah(highlightInfo.sura, highlightInfo.ayah) + val pages = pagesOf(highlightInfo) items.asSequence() - .filter { it.page == page } - .forEach { it.onHighlight(page, highlightInfo) } + .filter { it.page in pages } + .forEach { it.onHighlight(it.page, highlightInfo) } } private fun unhighlight(highlightInfo: HighlightInfo) { - val page = quranInfo.getPageFromSuraAyah(highlightInfo.sura, highlightInfo.ayah) + val pages = pagesOf(highlightInfo) items.asSequence() - .filter { it.page == page } - .forEach { it.onUnhighlight(page, highlightInfo) } + .filter { it.page in pages } + .forEach { it.onUnhighlight(it.page, highlightInfo) } } + private fun pagesOf(highlightInfo: HighlightInfo): Set = + pagesOfAyah(quranInfo, highlightInfo.sura, highlightInfo.ayah) + private fun unHighlightAyahs(type: HighlightType, page: Int? = null) { items.asSequence() .filter { page == null || page == it.page } .forEach { it.onUnHighlightAyahType(type) } } + internal companion object { + /** + * The pages an ayah may be on. QuranInfo gives the last one; an ayah that begins a page may + * have begun on the page before, in a mushaf whose ayat run on to the next page (Shemerly). + * Elsewhere, that page has no bounds for it and draws nothing. + */ + fun pagesOfAyah(quranInfo: QuranInfo, sura: Int, ayah: Int): Set { + val page = quranInfo.getPageFromSuraAyah(sura, ayah) + if (!quranInfo.isValidPage(page)) return setOf(page) + val beginsPage = quranInfo.getSuraOnPage(page) == sura && quranInfo.getFirstAyahOnPage(page) == ayah + return if (beginsPage && quranInfo.isValidPage(page - 1)) setOf(page - 1, page) else setOf(page) + } + } } diff --git a/app/src/main/java/com/quran/labs/androidquran/ui/PagerActivity.kt b/app/src/main/java/com/quran/labs/androidquran/ui/PagerActivity.kt index 78c1dace9f..7ed15ca3ec 100644 --- a/app/src/main/java/com/quran/labs/androidquran/ui/PagerActivity.kt +++ b/app/src/main/java/com/quran/labs/androidquran/ui/PagerActivity.kt @@ -84,6 +84,7 @@ import com.quran.labs.androidquran.feature.reading.presenter.AudioPresenter import com.quran.labs.androidquran.feature.reading.presenter.AudioPresenterScreen import com.quran.labs.androidquran.feature.reading.presenter.ReadingBookmarkChange import com.quran.labs.androidquran.feature.reading.presenter.ReadingBookmarkPresenter +import com.quran.labs.androidquran.feature.reading.presenter.ReadingTimePresenter import com.quran.labs.androidquran.feature.reading.presenter.RecentPagePresenter import com.quran.labs.androidquran.feature.reading.presenter.recitation.PagerActivityRecitationPresenter import com.quran.labs.androidquran.model.translation.ArabicDatabaseUtils @@ -112,6 +113,7 @@ import com.quran.labs.androidquran.ui.listener.AudioBarListener import com.quran.labs.androidquran.ui.readingbookmark.createReadingBookmarkToastView import com.quran.labs.androidquran.ui.util.ToastCompat.makeText import com.quran.labs.androidquran.ui.util.TranslationsSpinnerAdapter +import com.quran.labs.androidquran.ui.util.VolumeKeyNavigation import com.quran.labs.androidquran.util.AudioUtils import com.quran.labs.androidquran.util.OrientationLockUtils import com.quran.labs.androidquran.util.QuranFileUtils @@ -235,6 +237,7 @@ class PagerActivity : AppCompatActivity(), AudioBarListener, OnBookmarkTagsUpdat @Inject lateinit var bookmarksDao: BookmarksDao @Inject lateinit var recentPagePresenter: RecentPagePresenter @Inject lateinit var readingBookmarkPresenter: ReadingBookmarkPresenter + @Inject lateinit var readingTimePresenter: ReadingTimePresenter @Inject lateinit var quranSettings: QuranSettings @Inject lateinit var quranNaming: QuranNaming @Inject lateinit var quranScreenInfo: QuranScreenInfo @@ -630,7 +633,14 @@ class PagerActivity : AppCompatActivity(), AudioBarListener, OnBookmarkTagsUpdat { currentPage }, { ayahToolBar }, { ayah: SuraAyah -> ensurePage(ayah.sura, ayah.ayah) }, - { sliderPage: Int -> showSlider(slidingPagerAdapter.getPagePosition(sliderPage)) } + { sliderPage: Int -> showSlider(slidingPagerAdapter.getPagePosition(sliderPage)) }, + onSessionActiveChanged = { isActive -> + onEndSessionBackCallback.isEnabled = isActive + invalidateOptionsMenu() + }, + stopAudio = { if (audioStatusRepositoryBridge.audioRequest() != null) onStopPressed() }, + isShowingTranslation = { showingTranslation }, + switchToQuran = { switchToQuran() }, )) } @@ -873,12 +883,12 @@ class PagerActivity : AppCompatActivity(), AudioBarListener, OnBookmarkTagsUpdat override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { val navigate = (audioStatusRepositoryBridge.audioRequest() == null && quranSettings.navigateWithVolumeKeys()) - if (navigate && keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { - viewPager.currentItem -= 1 - return true - } else if (navigate && keyCode == KeyEvent.KEYCODE_VOLUME_UP) { - viewPager.currentItem += 1 - return true + if (navigate) { + val offset = VolumeKeyNavigation.pagerOffset(keyCode, quranSettings.shouldSwapVolumeKeys()) + if (offset != 0) { + viewPager.currentItem += offset + return true + } } return super.onKeyDown(keyCode, event) } @@ -900,6 +910,9 @@ class PagerActivity : AppCompatActivity(), AudioBarListener, OnBookmarkTagsUpdat audioPresenter.bind(this) recentPagePresenter.bind(currentPageFlow) readingBookmarkPresenter.bind(currentPageFlow, this) + readingTimePresenter.bind(currentPageFlow) { page -> + if (isDualPageVisible) setOfNotNull(page, (page + 1).takeIf { quranInfo.isValidPage(it) }) else setOf(page) + } if (shouldReconnect) { foregroundDisposable.add( @@ -1105,6 +1118,11 @@ class PagerActivity : AppCompatActivity(), AudioBarListener, OnBookmarkTagsUpdat quranNavigator.jumpTo(SuraAyah(sura, ayah)) } + override fun onUserInteraction() { + super.onUserInteraction() + readingTimePresenter.onInteraction() + } + public override fun onPause() { quranSettings.unregisterPreferencesListener(themePreferencesListener) foregroundDisposable.clear() @@ -1112,6 +1130,7 @@ class PagerActivity : AppCompatActivity(), AudioBarListener, OnBookmarkTagsUpdat promptDialog = null recentPagePresenter.unbind() readingBookmarkPresenter.unbind(this) + readingTimePresenter.unbind() quranSettings.wasShowingTranslation = pagerAdapter.isShowingTranslation super.onPause() @@ -1193,6 +1212,14 @@ class PagerActivity : AppCompatActivity(), AudioBarListener, OnBookmarkTagsUpdat translation.isVisible = false } } + + menu.findItem(R.id.memorize)?.let { memorize -> + memorize.isVisible = !showingTranslation && pagerActivityRecitationPresenter.isRecitationEnabled() + memorize.setTitle( + if (pagerActivityRecitationPresenter.hasSession()) R.string.menu_memorize_stop else R.string.menu_memorize + ) + } + return true } @@ -1201,6 +1228,9 @@ class PagerActivity : AppCompatActivity(), AudioBarListener, OnBookmarkTagsUpdat if (itemId == R.id.favorite_item) { showReadingBookmarkSheet(ReadingBookmarkTarget.Page(currentPage)) return true + } else if (itemId == R.id.memorize) { + pagerActivityRecitationPresenter.onMemorizeMenuPressed() + return true } else if (itemId == R.id.goto_quran) { switchToQuran() return true diff --git a/app/src/main/java/com/quran/labs/androidquran/ui/fragment/BookmarksFragment.kt b/app/src/main/java/com/quran/labs/androidquran/ui/fragment/BookmarksFragment.kt index 8f7586ad54..3eead3e15d 100644 --- a/app/src/main/java/com/quran/labs/androidquran/ui/fragment/BookmarksFragment.kt +++ b/app/src/main/java/com/quran/labs/androidquran/ui/fragment/BookmarksFragment.kt @@ -34,6 +34,7 @@ import com.quran.labs.androidquran.ui.QuranActivity import com.quran.labs.androidquran.ui.helpers.BookmarkUIConverter import com.quran.labs.androidquran.ui.helpers.QuranListAdapter import com.quran.labs.androidquran.ui.helpers.QuranListAdapter.QuranTouchListener +import com.quran.mobile.feature.progress.ProgressActivity import com.quran.labs.androidquran.ui.helpers.QuranRow import com.quran.mobile.feature.sync.BookmarksSignInCard import com.quran.mobile.feature.sync.QuranSyncActivity @@ -94,6 +95,7 @@ class BookmarksFragment : Fragment(), QuranTouchListener { val bookmarksAdapter = QuranListAdapter(context, recyclerView, emptyArray(), true) bookmarksAdapter.setQuranTouchListener(this) + bookmarksAdapter.setShowProgress(true) this.bookmarksAdapter = bookmarksAdapter recyclerView.setAdapter(bookmarksAdapter) @@ -274,6 +276,11 @@ class BookmarksFragment : Fragment(), QuranTouchListener { * The trailing chevron on a collection header, and a tap anywhere on a highlight color row, * open that collection or color as its own screen. */ + override fun onProgressClicked(row: QuranRow, position: Int) { + val context = context ?: return + startActivity(ProgressActivity.intent(context, row.readingBookmarkType)) + } + override fun onOpenClicked(row: QuranRow, position: Int) { if (bookmarksContextualModePresenter.isInActionMode()) { // while selecting, the chevron is part of the row rather than a way out of the screen diff --git a/app/src/main/java/com/quran/labs/androidquran/ui/helpers/HighlightTypes.kt b/app/src/main/java/com/quran/labs/androidquran/ui/helpers/HighlightTypes.kt index 464345dea1..2321c08e32 100644 --- a/app/src/main/java/com/quran/labs/androidquran/ui/helpers/HighlightTypes.kt +++ b/app/src/main/java/com/quran/labs/androidquran/ui/helpers/HighlightTypes.kt @@ -34,26 +34,25 @@ object HighlightTypes { private val FIRST_READING_BOOKMARK_ID = FIRST_HIGHLIGHT_ID + HIGHLIGHTS.size - private val READING_BOOKMARKS: Map = mapOf( - ReadingBookmarkType.TEAL to HighlightType( - FIRST_READING_BOOKMARK_ID, - UiCoreR.color.reading_bookmark_page_teal, - UNDERLINE, - nightColorResId = UiCoreR.color.reading_bookmark_page_teal_night - ), - ReadingBookmarkType.ORANGE to HighlightType( - FIRST_READING_BOOKMARK_ID + 1, - UiCoreR.color.reading_bookmark_page_orange, - UNDERLINE, - nightColorResId = UiCoreR.color.reading_bookmark_page_orange_night - ), - ReadingBookmarkType.RED to HighlightType( - FIRST_READING_BOOKMARK_ID + 2, - UiCoreR.color.reading_bookmark_page_red, - UNDERLINE, - nightColorResId = UiCoreR.color.reading_bookmark_page_red_night - ) - ) + private val READING_BOOKMARKS: Map = + ReadingBookmarkType.entries.associateWith { slot -> + val (day, night) = when (slot) { + ReadingBookmarkType.TEAL -> UiCoreR.color.reading_bookmark_page_teal to UiCoreR.color.reading_bookmark_page_teal_night + ReadingBookmarkType.ORANGE -> + UiCoreR.color.reading_bookmark_page_orange to UiCoreR.color.reading_bookmark_page_orange_night + ReadingBookmarkType.RED -> UiCoreR.color.reading_bookmark_page_red to UiCoreR.color.reading_bookmark_page_red_night + ReadingBookmarkType.GREEN -> + UiCoreR.color.reading_bookmark_page_green to UiCoreR.color.reading_bookmark_page_green_night + ReadingBookmarkType.BLUE -> UiCoreR.color.reading_bookmark_page_blue to UiCoreR.color.reading_bookmark_page_blue_night + ReadingBookmarkType.PURPLE -> + UiCoreR.color.reading_bookmark_page_purple to UiCoreR.color.reading_bookmark_page_purple_night + ReadingBookmarkType.BROWN -> + UiCoreR.color.reading_bookmark_page_brown to UiCoreR.color.reading_bookmark_page_brown_night + ReadingBookmarkType.GREY -> UiCoreR.color.reading_bookmark_page_grey to UiCoreR.color.reading_bookmark_page_grey_night + } + // ids follow the slot order, so where two bookmarks underline one ayah the first slot's shows + HighlightType(FIRST_READING_BOOKMARK_ID + slot.ordinal, day, UNDERLINE, nightColorResId = night) + } val readingBookmarks: Collection = READING_BOOKMARKS.values diff --git a/app/src/main/java/com/quran/labs/androidquran/ui/helpers/QuranListAdapter.kt b/app/src/main/java/com/quran/labs/androidquran/ui/helpers/QuranListAdapter.kt index 7943e7bbc7..e87adf645c 100644 --- a/app/src/main/java/com/quran/labs/androidquran/ui/helpers/QuranListAdapter.kt +++ b/app/src/main/java/com/quran/labs/androidquran/ui/helpers/QuranListAdapter.kt @@ -39,6 +39,7 @@ class QuranListAdapter( private var tagMap: Map = emptyMap() private var showTags = false private var showDate = false + private var showProgress = false private var touchListener: QuranTouchListener? = null @@ -156,6 +157,11 @@ class QuranListAdapter( this.showDate = showDate } + /** Whether reading bookmark rows get a button to their days in Progress. */ + fun setShowProgress(showProgress: Boolean) { + this.showProgress = showProgress + } + private fun getQuranRow(position: Int): QuranRow = elements[position] private fun bindRow(vh: HeaderHolder, position: Int) { @@ -165,6 +171,7 @@ class QuranListAdapter( with(holder) { number.text = QuranUtils.getLocalizedNumber(item.sura) + progress?.visibility = if (showProgress && item.isReadingBookmark) View.VISIBLE else View.GONE metadata.visibility = View.VISIBLE metadata.text = item.metadata tags.visibility = View.GONE @@ -332,6 +339,15 @@ class QuranListAdapter( val image: ImageView = itemView.findViewById(R.id.rowIcon) val tags: TagsViewGroup = itemView.findViewById(R.id.tags) val date: TextView? = itemView.findViewById(R.id.show_date) + // every variant of the row layout has it; a missing one shouldn't take the list down + val progress: View? = itemView.findViewById(R.id.progressButton)?.also { button -> + button.setOnClickListener { + val position = bindingAdapterPosition + if (position != RecyclerView.NO_POSITION) { + touchListener?.onProgressClicked(elements[position], position) + } + } + } } private inner class CollectionHeaderHolder(itemView: View) : HeaderHolder(itemView) { @@ -354,6 +370,7 @@ class QuranListAdapter( fun onClick(row: QuranRow, position: Int) fun onLongClick(row: QuranRow, position: Int): Boolean fun onOpenClicked(row: QuranRow, position: Int) = Unit + fun onProgressClicked(row: QuranRow, position: Int) = Unit } private companion object { diff --git a/app/src/main/java/com/quran/labs/androidquran/ui/listener/AudioBarRecitationListener.kt b/app/src/main/java/com/quran/labs/androidquran/ui/listener/AudioBarRecitationListener.kt index a9bd20412b..f710eac75d 100644 --- a/app/src/main/java/com/quran/labs/androidquran/ui/listener/AudioBarRecitationListener.kt +++ b/app/src/main/java/com/quran/labs/androidquran/ui/listener/AudioBarRecitationListener.kt @@ -9,4 +9,5 @@ interface AudioBarRecitationListener { fun onEndRecitationSessionPressed() fun onPlayRecitationPressed() fun onPauseRecitationPressed() + fun onRecitationHintPressed() {} } diff --git a/app/src/main/java/com/quran/labs/androidquran/ui/readingbookmark/ReadingBookmarkMovedIcons.kt b/app/src/main/java/com/quran/labs/androidquran/ui/readingbookmark/ReadingBookmarkMovedIcons.kt index c6bf210cde..2a6702beeb 100644 --- a/app/src/main/java/com/quran/labs/androidquran/ui/readingbookmark/ReadingBookmarkMovedIcons.kt +++ b/app/src/main/java/com/quran/labs/androidquran/ui/readingbookmark/ReadingBookmarkMovedIcons.kt @@ -9,7 +9,7 @@ import androidx.compose.ui.unit.dp private const val IconDimension = 24f -// an "x", used to dismiss the first-time reading bookmark education toast +// an "x", used to dismiss the reading bookmark toast internal val DismissIcon: ImageVector by lazy { ImageVector.Builder( name = "ReadingBookmarkMovedDismiss", diff --git a/app/src/main/java/com/quran/labs/androidquran/ui/readingbookmark/ReadingBookmarkMovedToast.kt b/app/src/main/java/com/quran/labs/androidquran/ui/readingbookmark/ReadingBookmarkMovedToast.kt index 5f9b15051d..0cd6d7f465 100644 --- a/app/src/main/java/com/quran/labs/androidquran/ui/readingbookmark/ReadingBookmarkMovedToast.kt +++ b/app/src/main/java/com/quran/labs/androidquran/ui/readingbookmark/ReadingBookmarkMovedToast.kt @@ -140,7 +140,7 @@ private fun ReadingBookmarkMovedToastShortPreview() { ), movedFromText = null, body = null, - onDismiss = null, + onDismiss = {}, onUndo = {}, modifier = Modifier.padding(14.dp) ) @@ -162,7 +162,7 @@ private fun ReadingBookmarkMovedToastShortAddedPreview() { movedFromText = null, body = null, onUndo = null, - onDismiss = null, + onDismiss = {}, modifier = Modifier.padding(14.dp) ) } diff --git a/app/src/main/java/com/quran/labs/androidquran/ui/readingbookmark/ReadingBookmarkToastView.kt b/app/src/main/java/com/quran/labs/androidquran/ui/readingbookmark/ReadingBookmarkToastView.kt index b84ad8d150..f6b1c6314e 100644 --- a/app/src/main/java/com/quran/labs/androidquran/ui/readingbookmark/ReadingBookmarkToastView.kt +++ b/app/src/main/java/com/quran/labs/androidquran/ui/readingbookmark/ReadingBookmarkToastView.kt @@ -80,7 +80,7 @@ private fun ReadingBookmarkToastContent( movedFromText = subtitle, body = body, onUndo = onUndo, - onDismiss = onDismiss.takeIf { isEducation }, + onDismiss = onDismiss, modifier = Modifier.padding(14.dp) ) } diff --git a/app/src/main/java/com/quran/labs/androidquran/ui/util/VolumeKeyNavigation.kt b/app/src/main/java/com/quran/labs/androidquran/ui/util/VolumeKeyNavigation.kt new file mode 100644 index 0000000000..d08cd6d287 --- /dev/null +++ b/app/src/main/java/com/quran/labs/androidquran/ui/util/VolumeKeyNavigation.kt @@ -0,0 +1,23 @@ +package com.quran.labs.androidquran.ui.util + +import android.view.KeyEvent + +object VolumeKeyNavigation { + + /** + * Returns how many positions the pager should move when [keyCode] is pressed with volume key + * navigation on, or 0 if [keyCode] is not a volume key. + * + * Pager positions run opposite to page numbers, so +1 is the previous page. By default volume + * down goes to the next page and volume up to the previous one; [swapped] reverses this (useful + * for single button page turners that send volume up). + */ + fun pagerOffset(keyCode: Int, swapped: Boolean): Int { + val offset = when (keyCode) { + KeyEvent.KEYCODE_VOLUME_DOWN -> -1 + KeyEvent.KEYCODE_VOLUME_UP -> 1 + else -> return 0 + } + return if (swapped) -offset else offset + } +} diff --git a/app/src/main/java/com/quran/labs/androidquran/util/QuranSettings.java b/app/src/main/java/com/quran/labs/androidquran/util/QuranSettings.java index f40d8bd90e..77ede4a0f3 100644 --- a/app/src/main/java/com/quran/labs/androidquran/util/QuranSettings.java +++ b/app/src/main/java/com/quran/labs/androidquran/util/QuranSettings.java @@ -71,6 +71,10 @@ public boolean navigateWithVolumeKeys() { return prefs.getBoolean(Constants.PREF_USE_VOLUME_KEY_NAV, false); } + public boolean shouldSwapVolumeKeys() { + return prefs.getBoolean(Constants.PREF_SWAP_VOLUME_KEYS, false); + } + public boolean shouldStream() { return prefs.getBoolean(Constants.PREF_PREFER_STREAMING, false); } diff --git a/app/src/main/java/com/quran/labs/androidquran/view/HighlightsDrawer.kt b/app/src/main/java/com/quran/labs/androidquran/view/HighlightsDrawer.kt index 133ef9fb64..972fc810c6 100644 --- a/app/src/main/java/com/quran/labs/androidquran/view/HighlightsDrawer.kt +++ b/app/src/main/java/com/quran/labs/androidquran/view/HighlightsDrawer.kt @@ -2,6 +2,7 @@ package com.quran.labs.androidquran.view import android.content.Context import android.graphics.Canvas +import android.graphics.Color import android.graphics.Paint import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter @@ -21,10 +22,12 @@ import com.quran.data.model.highlight.HighlightType.Mode.HIGHLIGHT import com.quran.data.model.highlight.HighlightType.Mode.UNDERLAY import com.quran.data.model.highlight.HighlightType.Mode.UNDERLINE import com.quran.labs.androidquran.ui.helpers.AyahHighlight +import com.quran.labs.androidquran.ui.helpers.AyahHighlight.SingleAyahHighlight import com.quran.labs.androidquran.ui.helpers.AyahHighlight.TransitionAyahHighlight import com.quran.page.common.data.AyahBounds import com.quran.page.common.data.AyahCoordinates import com.quran.page.common.data.PageCoordinates +import com.quran.page.common.data.coordinates.PageGlyphsCoords import com.quran.page.common.draw.ImageDrawHelper import java.util.SortedMap @@ -57,7 +60,8 @@ class HighlightsDrawer( val color = ContextCompat.getColor(context, colorResId) when (type.mode) { COLOR -> this.colorFilter = PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP) - UNDERLAY -> this.color = if (isNightMode) { + // at night an opaque colour is toned down; one with its own alpha keeps it + UNDERLAY -> this.color = if (isNightMode && Color.alpha(color) == 0xFF) { ColorUtils.setAlphaComponent(color, NIGHT_UNDERLAY_ALPHA) } else { color @@ -89,6 +93,7 @@ class HighlightsDrawer( override fun draw(pageCoordinates: PageCoordinates, canvas: Canvas, image: ImageView) { val highlightCoordinates = highlightCoordinates() ?: return val glyphsCoords = ayahCoordinates()?.glyphCoordinates + val wordGlyphsCoords = ayahCoordinates()?.wordGlyphCoordinates val ayahLineCoords = ayahCoordinates()?.ayahLineCoordinates val underlineRaiseRatio = ayahCoordinates()?.underlineRaiseRatio ?: 0f val currentHighlights = currentHighlights() ?: return @@ -103,11 +108,9 @@ class HighlightsDrawer( for (highlight in highlights) { if (alreadyHighlightedContains(highlightType, highlight)) continue - val isUnderline = highlightType.mode == UNDERLINE - val rangesToDraw = glyphsCoords?.takeIf { !highlightType.isTransitionAnimated } - ?.getBounds(highlight.key, !isUnderline, highlightType.mode == BACKGROUND) - ?: ayahLineCoords?.get(highlight.key)?.takeIf { isUnderline }?.map { it.bounds } - ?: highlightCoordinates[highlight]?.map { it.bounds } + val rangesToDraw = resolveBounds( + highlightType, highlight, glyphsCoords, wordGlyphsCoords, ayahLineCoords, highlightCoordinates + ) if (rangesToDraw != null && rangesToDraw.isNotEmpty()) { for (bounds in rangesToDraw) { @@ -155,6 +158,40 @@ class HighlightsDrawer( } } + private fun resolveBounds( + highlightType: HighlightType, + highlight: AyahHighlight, + glyphsCoords: PageGlyphsCoords?, + wordGlyphsCoords: PageGlyphsCoords?, + ayahLineCoords: Map>?, + highlightCoordinates: Map> + ): List? { + // Hiding and word highlights can use the word glyphs derived for databases without glyph + // types. Everything else, and every database with glyph types, keeps the bounds it always had. + // A transition ("1:1->1:2", as the audio highlight moves) is never a word. + if (glyphsCoords == null && wordGlyphsCoords != null && !highlight.isTransition()) { + if (highlightType.mode == HIDE) { + wordGlyphsCoords.getMaskBounds(highlight.key)?.let { return it } + } + if (highlight.key.count { it == ':' } == 2) { + val ayahKey = highlight.key.substringBeforeLast(':') + // a layout with one box per ayah and line has no word glyphs: its ayat are hidden, shown + // and marked whole + return if (wordGlyphsCoords.hasGlyphs(ayahKey)) { + wordGlyphsCoords.getBounds(highlight.key, true, false) + } else { + highlightCoordinates[SingleAyahHighlight(ayahKey)]?.map { it.bounds } + } + } + } + + val isUnderline = highlightType.mode == UNDERLINE + return glyphsCoords?.takeIf { !highlightType.isTransitionAnimated } + ?.getBounds(highlight.key, !isUnderline, highlightType.mode == BACKGROUND) + ?: ayahLineCoords?.get(highlight.key)?.takeIf { isUnderline }?.map { it.bounds } + ?: highlightCoordinates[highlight]?.map { it.bounds } + } + private fun clipOutRect(canvas: Canvas, rect: RectF) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { canvas.clipOutRect(rect) diff --git a/app/src/main/res/drawable/ic_progress_chart.xml b/app/src/main/res/drawable/ic_progress_chart.xml new file mode 100644 index 0000000000..7759dafc87 --- /dev/null +++ b/app/src/main/res/drawable/ic_progress_chart.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/app/src/main/res/layout-ar/index_sura_row.xml b/app/src/main/res/layout-ar/index_sura_row.xml index 1051fb37a9..202b95b661 100644 --- a/app/src/main/res/layout-ar/index_sura_row.xml +++ b/app/src/main/res/layout-ar/index_sura_row.xml @@ -82,4 +82,18 @@ android:textSize="14sp" tools:text="1" /> + + + diff --git a/app/src/main/res/layout/index_sura_row.xml b/app/src/main/res/layout/index_sura_row.xml index f5bc4e59ec..05907465bf 100644 --- a/app/src/main/res/layout/index_sura_row.xml +++ b/app/src/main/res/layout/index_sura_row.xml @@ -82,4 +82,18 @@ android:textSize="14sp" tools:text="1" /> + + + diff --git a/app/src/main/res/menu/quran_menu.xml b/app/src/main/res/menu/quran_menu.xml index 1efe1941de..f9813c1ac1 100644 --- a/app/src/main/res/menu/quran_menu.xml +++ b/app/src/main/res/menu/quran_menu.xml @@ -5,6 +5,11 @@ android:icon="@drawable/ic_not_favorite" android:title="@string/menu_bookmarks" app:showAsAction="ifRoom" /> + سمة التطبيق تصفح بمفاتيح الصوت استخدم مفاتيح الصوت للتصفح بين الصفحات + عكس اتجاه مفاتيح الصوت + زر رفع الصوت ينتقل إلى الصفحة التالية + زر رفع الصوت ينتقل إلى الصفحة السابقة إعدادات القراءة إعدادات التفسير والترجمة إعدادات العرض @@ -273,6 +276,7 @@ علامات موضع القراءة هذه علامة قراءة قابلة للنقل حفظ علامة القراءة يستبدل القديمة. لحفظ عدة آيات، اضغط مطولاً على آية وأضفها إلى مجموعة. + أيامها في التقدم نُقلت من %1$s إغلاق تحميل ملفات القرآن @@ -323,4 +327,7 @@ القادمة، هل ترغب في نقل البيانات على أية حال؟ "،" + + احفظ + إنهاء الحفظ diff --git a/app/src/main/res/values/preferences_keys.xml b/app/src/main/res/values/preferences_keys.xml index 99761267c6..1b8245bfb2 100644 --- a/app/src/main/res/values/preferences_keys.xml +++ b/app/src/main/res/values/preferences_keys.xml @@ -24,6 +24,7 @@ preferStreaming preferredDownloadAmount volumeKeyNavigation + swapVolumeKeys appLocation displayCategoryKey downloadCategoryKey diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0d2e65a2b5..0ef1fc04d7 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -159,6 +159,9 @@ App theme Volume key navigation Navigate between pages using volume keys + Swap volume keys + Volume up goes to the next page + Volume up goes to the previous page Reading Preferences Translation Preferences Display Settings @@ -368,6 +371,7 @@ This is a movable reading bookmark Saving a reading bookmark replaces your old one. To save multiple ayahs, long press an ayah and add it to a collection. + Its days in Progress Moved from %1$s Moved %1$s to %2$s @@ -435,4 +439,6 @@ Quran Downloads Quran Recitation Unable to rename this collection. It may no longer be available. + Memorize + Stop memorizing diff --git a/app/src/main/res/xml/quran_preferences.xml b/app/src/main/res/xml/quran_preferences.xml index 6380d4f15c..b56c69d260 100644 --- a/app/src/main/res/xml/quran_preferences.xml +++ b/app/src/main/res/xml/quran_preferences.xml @@ -103,6 +103,16 @@ android:summary="@string/prefs_volume_key_navigation_summary" android:title="@string/prefs_volume_key_navigation_title" app:iconSpaceReserved="false"/> + + + assertConsistent(source) + } + } + + @Test + fun `the newer Madani prints begin 25 pages at other ayat`() { + val classic = MadaniDataSource() + val newer = Madani1440DataSource() + val differing = (1..604).filter { page -> + classic.suraForPageArray[page - 1] != newer.suraForPageArray[page - 1] || + classic.ayahForPageArray[page - 1] != newer.ayahForPageArray[page - 1] + } + assertThat(differing).hasSize(25) + assertThat(newer.numberOfPages).isEqualTo(604) + assertThat(newer.pageForSuraArray).isEqualTo(classic.pageForSuraArray) + assertThat(newer.pageForJuzArray).isEqualTo(classic.pageForJuzArray) + + assertThat(firstAyah(madani1440, 121)).isEqualTo(SuraAyah(5, 78)) + assertThat(firstAyah(madani1440, 145)).isEqualTo(SuraAyah(6, 131)) + assertThat(firstAyah(madani1440, 600)).isEqualTo(SuraAyah(100, 6)) + assertThat(firstAyah(madani1440, 604)).isEqualTo(SuraAyah(112, 1)) + } + + @Test + fun `the Shemerly print has 521 pages`() { + assertThat(shemerly.numberOfPages).isEqualTo(521) + assertThat(firstAyah(shemerly, 3)).isEqualTo(SuraAyah(2, 5)) + // pages beginning with the end of an ayah from the page before + assertThat(firstAyah(shemerly, 305)).isEqualTo(SuraAyah(25, 73)) + assertThat(firstAyah(shemerly, 510)).isEqualTo(SuraAyah(89, 24)) + assertThat(firstAyah(shemerly, 438)).isEqualTo(SuraAyah(50, 34)) + assertThat(firstAyah(shemerly, 521)).isEqualTo(SuraAyah(112, 1)) + assertThat(shemerly.getPageFromSuraAyah(18, 1)).isEqualTo(242) + assertThat(shemerly.getPageFromSuraAyah(114, 6)).isEqualTo(521) + assertThat(shemerly.getStartingPageForJuz(25)).isEqualTo(403) + } + + @Test + fun `an ayah running on to the next page is on both`() { + assertThat(pagesOfAyah(shemerly, 25, 73)).containsExactly(304, 305) + assertThat(pagesOfAyah(shemerly, 25, 72)).containsExactly(304) + assertThat(pagesOfAyah(shemerly, 25, 74)).containsExactly(305) + assertThat(pagesOfAyah(shemerly, 114, 6)).containsExactly(521) + assertThat(pagesOfAyah(shemerly, 1, 1)).containsExactly(1) + // any ayah that begins a page might have begun on the page before + val madani = QuranInfo(MadaniDataSource()) + assertThat(pagesOfAyah(madani, 2, 6)).containsExactly(2, 3) + assertThat(pagesOfAyah(madani, 2, 7)).containsExactly(3) + } + + private fun firstAyah(quranInfo: QuranInfo, page: Int) = + SuraAyah(quranInfo.getSuraOnPage(page), quranInfo.getFirstAyahOnPage(page)) + + private fun assertConsistent(source: QuranDataSource) { + val pages = source.numberOfPages + val quranInfo = QuranInfo(source) + assertThat(source.suraForPageArray).hasLength(pages) + assertThat(source.ayahForPageArray).hasLength(pages) + assertThat(source.quarterStartByPage).hasLength(pages) + assertThat(source.pageForSuraArray).hasLength(114) + assertThat(source.pageForJuzArray).hasLength(30) + + // pages begin in order, at ayat that exist, each on its page or (running on) the page before + var previous = SuraAyah(1, 1) + for (page in 1..pages) { + val first = firstAyah(quranInfo, page) + assertThat(first).isAtLeast(previous) + assertThat(first.ayah).isAtMost(source.numberOfAyahsForSuraArray[first.sura - 1]) + assertThat(quranInfo.getPageFromSuraAyah(first.sura, first.ayah)).isEqualTo(page) + previous = first + } + // suras, quarters and juz begin on pages that have their first ayah + for (sura in 1..114) { + assertThat(source.pageForSuraArray[sura - 1]).isIn(pagesOfAyah(quranInfo, sura, 1)) + } + for ((page, quarter) in source.quarterStartByPage.withIndex().filter { it.value >= 0 }) { + val start = source.quartersArray[quarter] + assertThat(page + 1).isIn(pagesOfAyah(quranInfo, start.sura, start.ayah)) + } + for (juz in 0 until 30) { + val start = source.quartersArray[juz * 8] + assertThat(source.pageForJuzArray[juz]).isIn(pagesOfAyah(quranInfo, start.sura, start.ayah)) + } + assertThat(quranInfo.getVerseRangeForPage(pages).endingSura).isEqualTo(114) + } +} diff --git a/app/src/test/java/com/quran/data/page/provider/PageEditionsTest.kt b/app/src/test/java/com/quran/data/page/provider/PageEditionsTest.kt new file mode 100644 index 0000000000..7e0b3ad254 --- /dev/null +++ b/app/src/test/java/com/quran/data/page/provider/PageEditionsTest.kt @@ -0,0 +1,102 @@ +package com.quran.data.page.provider + +import com.google.common.truth.Truth.assertThat +import com.quran.data.page.provider.edition.Madani1421PageProvider +import com.quran.data.page.provider.edition.Madani1439LinesPageProvider +import com.quran.data.page.provider.edition.Madani1440PageProvider +import com.quran.data.page.provider.edition.Madani1441LinesPageProvider +import com.quran.data.page.provider.edition.ShemerlyPageProvider +import com.quran.data.page.provider.madani.MadaniPageProvider +import com.quran.data.page.provider.tajweed.TajweedPageProvider +import com.quran.data.source.DisplaySize +import com.quran.data.source.MushafType +import com.quran.data.source.PageContentType +import com.quran.data.source.PageProvider +import org.junit.Test + +/** The page types of quran.com's Page Type (experimental) list, as its own app downloads them. */ +class PageEditionsTest { + + private class Edition( + val key: String, + val provider: PageProvider, + val folder: String, + val width: String, + val version: Int, + val directory: String, + val mushafType: MushafType, + val pages: Int, + ) + + private val editions = listOf( + Edition(TajweedPageProvider.KEY, TajweedPageProvider(), "tajweed", "1280", 7, "tajweed", MushafType.MADANI_1405, 604), + Edition(Madani1421PageProvider.KEY, Madani1421PageProvider(), "madani_1421", "1120", 2, "new_madani", MushafType.MADANI_1440, 604), + Edition(Madani1440PageProvider.KEY, Madani1440PageProvider(), "madani_1440", "1352", 4, "new_madani", MushafType.MADANI_1440, 604), + Edition(Madani1439LinesPageProvider.KEY, Madani1439LinesPageProvider(), "madani_1439", "1080", 1, "new_madani", MushafType.MADANI_1440, 604), + Edition(Madani1441LinesPageProvider.KEY, Madani1441LinesPageProvider(), "madani_1441", "1440", 1, "new_madani", MushafType.MADANI_1440, 604), + Edition(ShemerlyPageProvider.KEY, ShemerlyPageProvider(), "shemerly", "1200", 1, "shemerly", MushafType.SHEMERLY, 521), + ) + + @Test + fun `each edition downloads from its folder on files quran app`() { + editions.forEach { edition -> + val provider = edition.provider + val base = "https://files.quran.app/hafs/${edition.folder}" + assertThat(provider.getImagesZipBaseUrl()).isEqualTo("$base/zips/") + assertThat(provider.getAyahInfoBaseUrl()).isEqualTo("$base/databases/ayahinfo/") + assertThat(provider.getPatchBaseUrl()).isEqualTo("$base/patches/v") + assertThat(provider.getImageVersion()).isEqualTo(edition.version) + } + } + + @Test + fun `each edition has a single width`() { + editions.forEach { edition -> + listOf(DisplaySize(720, 1600), DisplaySize(1440, 3200), DisplaySize(2560, 1600)).forEach { size -> + val calculator = edition.provider.getPageSizeCalculator(size) + calculator.setOverrideParameter("1920") + assertThat(calculator.getWidthParameter()).isEqualTo(edition.width) + assertThat(calculator.getTabletWidthParameter()).isEqualTo(edition.width) + } + } + } + + @Test + fun `each edition keeps its files apart from the Madani ones`() { + editions.forEach { edition -> + assertThat(edition.provider.getImagesDirectoryName()).isEqualTo(edition.directory) + // where the images zip puts its own databases folder + assertThat(edition.provider.getAyahInfoDirectoryName()).isEqualTo("${edition.directory}/databases") + } + // editions sharing a directory differ by width + editions.groupBy { it.directory }.values.forEach { shared -> + assertThat(shared.map { it.width }.toSet()).hasSize(shared.size) + } + } + + @Test + fun `each edition has its pages and the Madani reciters`() { + val madaniQaris = MadaniPageProvider().getQaris().map { it.id } + editions.forEach { edition -> + assertThat(edition.provider.mushafType()).isEqualTo(edition.mushafType) + assertThat(edition.provider.getDataSource().numberOfPages).isEqualTo(edition.pages) + // the memorize feature's hint voices among them + assertThat(edition.provider.getQaris().map { it.id }).isEqualTo(madaniQaris) + } + } + + @Test + fun `only the editions named lines are drawn line by line`() { + val byKey = editions.associateBy { it.key } + editions.forEach { edition -> + val content = edition.provider.getPageContentType() + // the checks for missing page images skip these types by their name + assertThat(content is PageContentType.Line).isEqualTo(edition.key.endsWith("lines")) + if (content is PageContentType.Line) { + val fallback = byKey.getValue(edition.provider.getFallbackPageType()!!) + assertThat(fallback.provider.getPageContentType()).isEqualTo(PageContentType.Image) + assertThat(fallback.mushafType).isEqualTo(edition.mushafType) + } + } + } +} diff --git a/app/src/test/java/com/quran/labs/androidquran/base/TestApplication.kt b/app/src/test/java/com/quran/labs/androidquran/base/TestApplication.kt index b5d2fd4fb8..e56a456ac4 100644 --- a/app/src/test/java/com/quran/labs/androidquran/base/TestApplication.kt +++ b/app/src/test/java/com/quran/labs/androidquran/base/TestApplication.kt @@ -16,4 +16,7 @@ class TestApplication : QuranApplication() { override fun initializeWorkManager() { } + + override fun startProgress() { + } } diff --git a/app/src/test/java/com/quran/labs/androidquran/data/AyahInfoDatabaseHandlerWordGlyphsTest.kt b/app/src/test/java/com/quran/labs/androidquran/data/AyahInfoDatabaseHandlerWordGlyphsTest.kt new file mode 100644 index 0000000000..4bba8862d8 --- /dev/null +++ b/app/src/test/java/com/quran/labs/androidquran/data/AyahInfoDatabaseHandlerWordGlyphsTest.kt @@ -0,0 +1,158 @@ +package com.quran.labs.androidquran.data + +import android.database.sqlite.SQLiteDatabase +import android.graphics.RectF +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.quran.data.model.AyahGlyph.PauseGlyph +import com.quran.data.model.AyahGlyph.WordGlyph +import com.quran.data.model.SuraAyah +import com.quran.labs.androidquran.base.TestApplication +import com.quran.labs.androidquran.fakes.FakeQuranFileUtils +import com.quran.page.common.data.coordinates.GlyphSize +import com.quran.page.common.data.coordinates.GlyphTypeResolver +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +@Config(application = TestApplication::class, sdk = [33]) +@RunWith(RobolectricTestRunner::class) +class AyahInfoDatabaseHandlerWordGlyphsTest { + + private val quranFileUtils = FakeQuranFileUtils.create(ApplicationProvider.getApplicationContext()) + + // 1:1 is entirely on page 1: hizb marker, two words, a waqf mark, a word and the ayah end. + // 1:2 starts on page 1 (two words) and continues on page 2 (one word and the ayah end). + private val types = mapOf(SuraAyah(1, 1) to "hwwpwe", SuraAyah(1, 2) to "wwwe") + + private val resolver = object : GlyphTypeResolver { + override fun glyphTypes(sura: Int, ayah: Int, glyphs: List): String? = types[SuraAyah(sura, ayah)] + } + + @Before + fun setUp() { + val directory = quranFileUtils.quranAyahDatabaseDirectory + directory.mkdirs() + val file = File(directory, DATABASE) + file.delete() + SQLiteDatabase.openOrCreateDatabase(file, null).use { db -> + db.execSQL( + "CREATE TABLE glyphs(glyph_id int, page_number int, line_number int, sura_number int, " + + "ayah_number int, position int, min_x int, max_x int, min_y int, max_y int)" + ) + var id = 0 + fun glyph(page: Int, line: Int, ayah: Int, position: Int, minX: Int, maxX: Int, minY: Int = 0) { + db.execSQL( + "INSERT INTO glyphs VALUES (${id++}, $page, $line, 1, $ayah, $position, $minX, $maxX, " + + "$minY, ${minY + 50})" + ) + } + // page 1, line 1 (right to left) + glyph(1, 1, 1, 1, 900, 950) + glyph(1, 1, 1, 2, 800, 880) + glyph(1, 1, 1, 3, 650, 780) + glyph(1, 1, 1, 4, 640, 645, minY = 5) // waqf mark + glyph(1, 1, 1, 5, 500, 630) + glyph(1, 1, 1, 6, 420, 480) + // page 1, line 2 + glyph(1, 2, 2, 1, 800, 950, minY = 60) + glyph(1, 2, 2, 2, 600, 780, minY = 60) + // page 2, line 1 + glyph(2, 1, 2, 3, 700, 950) + glyph(2, 1, 2, 4, 620, 680) + } + } + + @Test + fun `derives word glyphs when the database has no glyph types`() { + val coordinates = handler(resolver).getVersesBoundsForPage(1) + + assertThat(coordinates.glyphCoordinates).isNull() + val glyphs = coordinates.wordGlyphCoordinates!!.glyphsByAyah[SuraAyah(1, 1)]!!.map { it.glyph } + assertThat(glyphs.filterIsInstance().map { it.position to it.wordPosition }) + .containsExactly(2 to 1, 3 to 2, 5 to 3).inOrder() + assertThat(glyphs.filterIsInstance().map { it.position }).containsExactly(4) + } + + @Test + fun `numbers words of an ayah continuing from the previous page by their position in the ayah`() { + val coordinates = handler(resolver).getVersesBoundsForPage(2) + + val words = coordinates.wordGlyphCoordinates!!.glyphsByAyah[SuraAyah(1, 2)]!! + .map { it.glyph } + .filterIsInstance() + assertThat(words.map { it.wordPosition }).containsExactly(3) + } + + @Test + fun `masks a word together with the waqf mark that follows it`() { + val glyphs = handler(resolver).getVersesBoundsForPage(1).wordGlyphCoordinates!! + + val bounds = glyphs.getMaskBounds("1:1:2")!! + + assertThat(bounds).hasSize(1) + // the word (650..780) and its waqf mark (640..645), expanded to the midpoints with neighbours + assertThat(bounds[0].right).isEqualTo(790f) + assertThat(bounds[0].left).isEqualTo(635f) + } + + @Test + fun `masking an ayah leaves the hizb and ayah end markers visible`() { + val glyphs = handler(resolver).getVersesBoundsForPage(1).wordGlyphCoordinates!! + + val bounds = glyphs.getMaskBounds("1:1")!! + + assertThat(bounds).hasSize(1) + val mask: RectF = bounds[0] + assertThat(mask.right).isLessThan(900f) // hizb marker starts at 900 + assertThat(mask.left).isGreaterThan(480f) // ayah end marker ends at 480 + } + + @Test + fun `ignores ayat whose glyph count doesn't match the resolved types`() { + val wrongLayout = object : GlyphTypeResolver { + override fun glyphTypes(sura: Int, ayah: Int, glyphs: List): String? = + if (ayah == 1) "wwe" else types[SuraAyah(sura, ayah)] + } + + val glyphs = handler(wrongLayout, name = "ayahinfo_mismatch.db").getVersesBoundsForPage(1) + .wordGlyphCoordinates!! + + assertThat(glyphs.glyphsByAyah[SuraAyah(1, 1)]).isNull() + assertThat(glyphs.glyphsByAyah[SuraAyah(1, 2)]).isNotNull() + } + + @Test + fun `gives the resolver the sizes of each ayah's glyphs in this layout`() { + val seen = mutableMapOf>() + val recording = object : GlyphTypeResolver { + override fun glyphTypes(sura: Int, ayah: Int, glyphs: List): String? { + seen[SuraAyah(sura, ayah)] = glyphs + return types[SuraAyah(sura, ayah)] + } + } + + handler(recording, name = "ayahinfo_sizes.db").getVersesBoundsForPage(1) + + assertThat(seen[SuraAyah(1, 1)]).containsExactly( + GlyphSize(50, 50), GlyphSize(80, 50), GlyphSize(130, 50), GlyphSize(5, 50), GlyphSize(130, 50), GlyphSize(60, 50), + ).inOrder() + // all of 1:2, including its glyphs on the next page + assertThat(seen[SuraAyah(1, 2)]).hasSize(4) + } + + private fun handler(resolver: GlyphTypeResolver, name: String = DATABASE): AyahInfoDatabaseHandler { + if (name != DATABASE) { + File(quranFileUtils.quranAyahDatabaseDirectory, DATABASE) + .copyTo(File(quranFileUtils.quranAyahDatabaseDirectory, name), overwrite = true) + } + return AyahInfoDatabaseHandler.getAyahInfoDatabaseHandler(name, quranFileUtils, resolver)!! + } + + companion object { + private const val DATABASE = "ayahinfo_wordglyphs_test.db" + } +} diff --git a/app/src/test/java/com/quran/labs/androidquran/feature/reading/presenter/recitation/PagesOnScreenTest.kt b/app/src/test/java/com/quran/labs/androidquran/feature/reading/presenter/recitation/PagesOnScreenTest.kt new file mode 100644 index 0000000000..03165e4a6d --- /dev/null +++ b/app/src/test/java/com/quran/labs/androidquran/feature/reading/presenter/recitation/PagesOnScreenTest.kt @@ -0,0 +1,37 @@ +package com.quran.labs.androidquran.feature.reading.presenter.recitation + +import com.google.common.truth.Truth.assertThat +import com.quran.data.core.QuranInfo +import com.quran.labs.androidquran.feature.reading.presenter.recitation.PagerActivityRecitationPresenter.Companion.pagesOnScreen +import com.quran.labs.androidquran.pages.data.madani.MadaniDataSource +import org.junit.Test + +class PagesOnScreenTest { + + private val quranInfo = QuranInfo(MadaniDataSource()) + + @Test + fun `one page`() { + assertThat(pagesOnScreen(1, isDualPageVisible = false, numberOfPages = 604)).containsExactly(1) + assertThat(pagesOnScreen(604, isDualPageVisible = false, numberOfPages = 604)).containsExactly(604) + } + + @Test + fun `a pair shows the current page and the next`() { + // what PagerActivity's currentPage gives for the first and the last pair (TabletFragment shows + // that page and the one after it) + val first = quranInfo.getPageFromPosition(quranInfo.numberOfPagesConsideringSkipped / 2 - 1, true) + val last = quranInfo.getPageFromPosition(0, true) + assertThat(first).isEqualTo(1) + assertThat(last).isEqualTo(603) + + assertThat(pagesOnScreen(first, isDualPageVisible = true, numberOfPages = 604)).containsExactly(1, 2).inOrder() + assertThat(pagesOnScreen(301, isDualPageVisible = true, numberOfPages = 604)).containsExactly(301, 302).inOrder() + assertThat(pagesOnScreen(last, isDualPageVisible = true, numberOfPages = 604)).containsExactly(603, 604).inOrder() + } + + @Test + fun `the last pair of an odd number of pages has one page`() { + assertThat(pagesOnScreen(521, isDualPageVisible = true, numberOfPages = 521)).containsExactly(521) + } +} diff --git a/app/src/test/java/com/quran/labs/androidquran/model/bookmark/BookmarkImportExportModelTest.kt b/app/src/test/java/com/quran/labs/androidquran/model/bookmark/BookmarkImportExportModelTest.kt index e69b3c7382..693e0bbf54 100644 --- a/app/src/test/java/com/quran/labs/androidquran/model/bookmark/BookmarkImportExportModelTest.kt +++ b/app/src/test/java/com/quran/labs/androidquran/model/bookmark/BookmarkImportExportModelTest.kt @@ -25,6 +25,7 @@ import com.quran.labs.androidquran.fakes.FakeReadingBookmarksDao import com.quran.labs.androidquran.fakes.FakeRecentPagesDao import com.quran.labs.androidquran.pages.data.madani.MadaniDataSource import com.quran.mobile.bookmark.importdata.BookmarkBackupImportNormalizer +import com.quran.mobile.bookmark.importdata.LocalReadingBookmarkImporter import com.quran.mobile.bookmark.importdata.MobileSyncImportData import com.quran.mobile.bookmark.importdata.MobileSyncImportReadingBookmark import com.quran.mobile.bookmark.importdata.MobileSyncImportResult @@ -58,6 +59,7 @@ class BookmarkImportExportModelTest { private lateinit var quranInfo: QuranInfo private lateinit var mobileSyncImporter: FakeMobileSyncImporter private lateinit var bookmarkImportExportModel: BookmarkImportExportModel + private val locallyImported = mutableListOf() @Before fun setUp() { @@ -84,7 +86,8 @@ class BookmarkImportExportModelTest { pageMapper, DefaultMobileSyncTimestampProvider() ), - mobileSyncImporter + mobileSyncImporter, + LocalReadingBookmarkImporter { bookmarks, _ -> locallyImported += bookmarks } ) } @@ -498,6 +501,47 @@ class BookmarkImportExportModelTest { .inOrder() } + @Test + fun testExportKeepsReadingBookmarksKeptOnTheDeviceApart() { + readingBookmarksDao.setReadingBookmark( + PageReadingBookmark(ReadingBookmarkType.ORANGE, 12, Instant.fromEpochSeconds(1000)) + ) + readingBookmarksDao.setReadingBookmark( + PageReadingBookmark(ReadingBookmarkType.GREEN, 30, Instant.fromEpochSeconds(2000), name = "Al-Kahf") + ) + + val testObserver = TestObserver() + bookmarkImportExportModel.exportBookmarksObservable() + .subscribe(testObserver) + BaseTestExtension.awaitTerminalEvent(testObserver) + testObserver.assertNoErrors() + + val exportedData = BookmarkJsonModel().fromJson(backupFile().source().buffer()) + // older versions read readingBookmarks, and fail on a slot they don't know + assertThat(exportedData.readingBookmarks.map { it.slot }).containsExactly(ReadingBookmarkType.ORANGE) + assertThat(exportedData.localReadingBookmarks).containsExactly( + BackupReadingBookmark( + slot = ReadingBookmarkType.GREEN, + type = BackupReadingBookmark.TYPE_PAGE, + page = 30, + timestamp = Instant.fromEpochSeconds(2000), + name = "Al-Kahf" + ) + ) + } + + @Test + fun testImportHandsReadingBookmarksKeptOnTheDeviceToTheirImporter() { + val green = BackupReadingBookmark( + slot = ReadingBookmarkType.GREEN, + type = BackupReadingBookmark.TYPE_PAGE, + page = 30, + timestamp = Instant.fromEpochSeconds(2000) + ) + importData(BookmarkData(localReadingBookmarks = listOf(green))) + assertThat(locallyImported).containsExactly(green) + } + @Test fun testImportReadingBookmark() { importData( diff --git a/app/src/test/java/com/quran/labs/androidquran/presenter/QuranImportPresenterTest.kt b/app/src/test/java/com/quran/labs/androidquran/presenter/QuranImportPresenterTest.kt index 1abf56ea2c..629adf479b 100644 --- a/app/src/test/java/com/quran/labs/androidquran/presenter/QuranImportPresenterTest.kt +++ b/app/src/test/java/com/quran/labs/androidquran/presenter/QuranImportPresenterTest.kt @@ -16,6 +16,7 @@ import com.quran.labs.androidquran.model.bookmark.BookmarkImportExportModel import com.quran.labs.androidquran.model.bookmark.BookmarkJsonModel import com.quran.labs.awaitTerminalEvent import com.quran.mobile.bookmark.importdata.BookmarkBackupImportNormalizer +import com.quran.mobile.bookmark.importdata.LocalReadingBookmarkImporter import com.quran.mobile.bookmark.importdata.MobileSyncImportData import com.quran.mobile.bookmark.importdata.MobileSyncImportResult import com.quran.mobile.bookmark.importdata.MobileSyncImporter @@ -61,7 +62,8 @@ class QuranImportPresenterTest { pageMapper, DefaultMobileSyncTimestampProvider() ), - FakeMobileSyncImporter() + FakeMobileSyncImporter(), + LocalReadingBookmarkImporter { _, _ -> } ) } diff --git a/app/src/test/java/com/quran/labs/androidquran/ui/helpers/BookmarkUIConverterTest.kt b/app/src/test/java/com/quran/labs/androidquran/ui/helpers/BookmarkUIConverterTest.kt index 99025f2336..2905e90653 100644 --- a/app/src/test/java/com/quran/labs/androidquran/ui/helpers/BookmarkUIConverterTest.kt +++ b/app/src/test/java/com/quran/labs/androidquran/ui/helpers/BookmarkUIConverterTest.kt @@ -273,6 +273,6 @@ class BookmarkUIConverterTest { factory.fromReadingBookmark(context, PageReadingBookmark(slot, 42, timestamp)) .imageContentDescription } - ).containsExactly("أزرق مخضر", "برتقالي", "أحمر").inOrder() + ).containsExactly("أزرق مخضر", "برتقالي", "أحمر", "أخضر", "أزرق", "بنفسجي", "بني", "رمادي").inOrder() } } diff --git a/app/src/test/java/com/quran/labs/androidquran/ui/helpers/QuranListAdapterTest.kt b/app/src/test/java/com/quran/labs/androidquran/ui/helpers/QuranListAdapterTest.kt new file mode 100644 index 0000000000..469fa7f0db --- /dev/null +++ b/app/src/test/java/com/quran/labs/androidquran/ui/helpers/QuranListAdapterTest.kt @@ -0,0 +1,54 @@ +package com.quran.labs.androidquran.ui.helpers + +import android.content.Context +import android.view.ContextThemeWrapper +import android.view.View +import android.widget.FrameLayout +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.quran.data.core.QuranInfo +import com.quran.data.model.bookmark.PageReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.labs.androidquran.R +import com.quran.labs.androidquran.base.TestApplication +import com.quran.labs.androidquran.data.QuranDisplayData +import com.quran.labs.androidquran.pages.data.madani.MadaniDataSource +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import kotlin.time.Instant +import androidx.appcompat.R as AppCompatR + +/** The list rows inflate in every layout variant (the Arabic one has its own). */ +@RunWith(RobolectricTestRunner::class) +@Config(application = TestApplication::class, sdk = [33]) +class QuranListAdapterTest { + + private fun readingBookmarkRow(): View { + // the rows are inflated in an activity, with its (AppCompat) theme + val context = ContextThemeWrapper(ApplicationProvider.getApplicationContext(), AppCompatR.style.Theme_AppCompat_DayNight) + val quranInfo = QuranInfo(MadaniDataSource()) + val row = QuranRowFactory(quranInfo, QuranDisplayData(quranInfo)) + .fromReadingBookmark(context, PageReadingBookmark(ReadingBookmarkType.TEAL, 42, Instant.fromEpochSeconds(0))) + val recyclerView = RecyclerView(context).apply { layoutManager = LinearLayoutManager(context) } + val adapter = QuranListAdapter(context, recyclerView, arrayOf(row), true).apply { setShowProgress(true) } + val parent = FrameLayout(context) + val holder = adapter.onCreateViewHolder(parent, adapter.getItemViewType(0)) + adapter.onBindViewHolder(holder, 0) + return holder.itemView + } + + @Test + fun aReadingBookmarkRowHasItsProgressButton() { + assertThat(readingBookmarkRow().findViewById(R.id.progressButton).visibility).isEqualTo(View.VISIBLE) + } + + @Test + @Config(qualifiers = "ar") + fun aReadingBookmarkRowHasItsProgressButtonInArabic() { + assertThat(readingBookmarkRow().findViewById(R.id.progressButton).visibility).isEqualTo(View.VISIBLE) + } +} diff --git a/app/src/test/java/com/quran/labs/androidquran/ui/util/VolumeKeyNavigationTest.kt b/app/src/test/java/com/quran/labs/androidquran/ui/util/VolumeKeyNavigationTest.kt new file mode 100644 index 0000000000..01c95724c4 --- /dev/null +++ b/app/src/test/java/com/quran/labs/androidquran/ui/util/VolumeKeyNavigationTest.kt @@ -0,0 +1,46 @@ +package com.quran.labs.androidquran.ui.util + +import android.view.KeyEvent +import com.google.common.truth.Truth.assertThat +import com.quran.data.core.QuranInfo +import com.quran.labs.androidquran.pages.data.madani.MadaniDataSource +import org.junit.Test + +class VolumeKeyNavigationTest { + + private val quranInfo = QuranInfo(MadaniDataSource()) + + /** The page shown after pressing [keyCode] on [page], mapped through the real pager positions. */ + private fun pageAfterPressing(keyCode: Int, swapped: Boolean, page: Int = 50): Int { + val position = quranInfo.getPositionFromPage(page, false) + val offset = VolumeKeyNavigation.pagerOffset(keyCode, swapped) + return quranInfo.getPageFromPosition(position + offset, false) + } + + @Test + fun `volume down goes to the next page by default`() { + assertThat(pageAfterPressing(KeyEvent.KEYCODE_VOLUME_DOWN, swapped = false)).isEqualTo(51) + } + + @Test + fun `volume up goes to the previous page by default`() { + assertThat(pageAfterPressing(KeyEvent.KEYCODE_VOLUME_UP, swapped = false)).isEqualTo(49) + } + + @Test + fun `volume up goes to the next page when swapped`() { + assertThat(pageAfterPressing(KeyEvent.KEYCODE_VOLUME_UP, swapped = true)).isEqualTo(51) + } + + @Test + fun `volume down goes to the previous page when swapped`() { + assertThat(pageAfterPressing(KeyEvent.KEYCODE_VOLUME_DOWN, swapped = true)).isEqualTo(49) + } + + @Test + fun `other keys do not move the pager`() { + assertThat(VolumeKeyNavigation.pagerOffset(KeyEvent.KEYCODE_PAGE_DOWN, swapped = false)).isEqualTo(0) + assertThat(VolumeKeyNavigation.pagerOffset(KeyEvent.KEYCODE_PAGE_DOWN, swapped = true)).isEqualTo(0) + assertThat(VolumeKeyNavigation.pagerOffset(KeyEvent.KEYCODE_VOLUME_MUTE, swapped = true)).isEqualTo(0) + } +} diff --git a/app/src/test/java/com/quran/labs/androidquran/view/HighlightsDrawerTest.kt b/app/src/test/java/com/quran/labs/androidquran/view/HighlightsDrawerTest.kt new file mode 100644 index 0000000000..65cf34391b --- /dev/null +++ b/app/src/test/java/com/quran/labs/androidquran/view/HighlightsDrawerTest.kt @@ -0,0 +1,160 @@ +package com.quran.labs.androidquran.view + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.RectF +import android.widget.ImageView +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.quran.data.model.AyahGlyph.AyahEndGlyph +import com.quran.data.model.AyahGlyph.WordGlyph +import com.quran.data.model.SuraAyah +import com.quran.data.model.highlight.HighlightType +import com.quran.labs.androidquran.R +import com.quran.labs.androidquran.base.TestApplication +import com.quran.labs.androidquran.ui.helpers.AyahHighlight +import com.quran.labs.androidquran.ui.helpers.AyahHighlight.SingleAyahHighlight +import com.quran.labs.androidquran.ui.helpers.AyahHighlight.TransitionAyahHighlight +import com.quran.labs.androidquran.ui.helpers.HighlightTypes +import com.quran.page.common.data.AyahBounds +import com.quran.page.common.data.AyahCoordinates +import com.quran.page.common.data.PageCoordinates +import com.quran.page.common.data.coordinates.GlyphCoords +import com.quran.page.common.data.coordinates.PageGlyphsCoords +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.util.SortedMap +import java.util.TreeMap + +@Config(application = TestApplication::class, sdk = [33]) +@RunWith(RobolectricTestRunner::class) +class HighlightsDrawerTest { + + private val first = SuraAyah(1, 1) + private val second = SuraAyah(1, 2) + + // a page without glyph types, so its word glyphs are derived (as on Madani and Tajweed pages) + private val ayahCoordinates = AyahCoordinates( + page = 1, + ayahCoordinates = emptyMap(), + glyphCoordinates = null, + wordGlyphCoordinates = PageGlyphsCoords( + 1, + listOf( + GlyphCoords(WordGlyph(first, 1, 1), 1, RectF(800f, 0f, 900f, 50f)), + GlyphCoords(AyahEndGlyph(first, 2), 1, RectF(750f, 0f, 790f, 50f)), + GlyphCoords(WordGlyph(second, 1, 1), 1, RectF(600f, 0f, 740f, 50f)), + GlyphCoords(AyahEndGlyph(second, 2), 1, RectF(550f, 0f, 590f, 50f)), + ) + ) + ) + + @Test + fun `audio moving to the next ayah draws its transition`() { + // while the audio highlight floats from 1:1 to 1:2, its key is "1:1->1:2" (two colons) + val transition = TransitionAyahHighlight(SingleAyahHighlight(first.sura, first.ayah), SingleAyahHighlight(second.sura, second.ayah)) + val highlights: SortedMap> = TreeMap() + highlights[HighlightTypes.AUDIO] = setOf(transition) + val canvas = RecordingCanvas() + val drawer = HighlightsDrawer( + { ayahCoordinates }, + { mapOf(transition to listOf(AyahBounds(1, 1, 600, 0, 900, 50))) }, + { highlights }, + {} + ) + + drawer.draw( + PageCoordinates(1, RectF(0f, 0f, 1000f, 100f), emptyList(), emptyList()), + canvas, + ImageView(ApplicationProvider.getApplicationContext()) + ) + + // drawn with the transition's own (animated) bounds + assertThat(canvas.rects).containsExactly(RectF(600f, 0f, 900f, 50f)) + } + + @Test + fun `at night an opaque background is toned down and one with its own alpha keeps it`() { + // #ff212529 and #1f000000 + val opaque = HighlightType(9001, R.color.title_color, HighlightType.Mode.UNDERLAY) + val light = HighlightType(9002, R.color.ripple_dark, HighlightType.Mode.UNDERLAY) + val highlights: SortedMap> = TreeMap() + highlights[opaque] = setOf(SingleAyahHighlight(first.sura, first.ayah, 1)) + highlights[light] = setOf(SingleAyahHighlight(second.sura, second.ayah, 1)) + val canvas = RecordingCanvas() + val drawer = HighlightsDrawer({ ayahCoordinates }, { emptyMap() }, { highlights }, {}, isNightMode = { true }) + + drawer.draw( + PageCoordinates(1, RectF(0f, 0f, 1000f, 100f), emptyList(), emptyList()), + canvas, + ImageView(ApplicationProvider.getApplicationContext()) + ) + + assertThat(canvas.alphas).containsExactly(0x66, 0x1F).inOrder() + } + + // a layout with one box per ayah and line (the newer Madani prints, Shemerly): no word glyphs + private val ayahLines = listOf(AyahBounds(1, 1, 600, 0, 900, 50), AyahBounds(2, 2, 700, 50, 1000, 100)) + private val ayahLevel = AyahCoordinates( + page = 1, + ayahCoordinates = mapOf("1:1" to ayahLines), + glyphCoordinates = null, + wordGlyphCoordinates = PageGlyphsCoords(1, emptyList()) + ) + + @Test + fun `a word of an ayah without word glyphs is hidden with its whole ayah`() { + val canvas = draw(ayahLevel, HIDE_TYPE, SingleAyahHighlight(1, 1, 2)) + assertThat(canvas.clipped).containsExactly(RectF(600f, 0f, 900f, 50f), RectF(700f, 50f, 1000f, 100f)) + } + + @Test + fun `a word of an ayah without word glyphs is marked on its whole ayah`() { + val canvas = draw(ayahLevel, UNDERLAY_TYPE, SingleAyahHighlight(1, 1, 2)) + assertThat(canvas.rects).containsExactly(RectF(600f, 0f, 900f, 50f), RectF(700f, 50f, 1000f, 100f)) + } + + @Test + fun `a word of an ayah with word glyphs is marked alone`() { + val canvas = draw(ayahCoordinates, UNDERLAY_TYPE, SingleAyahHighlight(1, 2, 1)) + assertThat(canvas.rects).hasSize(1) + assertThat(canvas.rects.single().left).isAtLeast(590f) + assertThat(canvas.rects.single().right).isAtMost(750f) + } + + private fun draw(coordinates: AyahCoordinates, type: HighlightType, highlight: AyahHighlight): RecordingCanvas { + val highlights: SortedMap> = TreeMap() + highlights[type] = setOf(highlight) + val boundsByAyah = coordinates.ayahCoordinates.mapKeys { SingleAyahHighlight(it.key) as AyahHighlight } + val canvas = RecordingCanvas() + HighlightsDrawer({ coordinates }, { boundsByAyah }, { highlights }, {}).draw( + PageCoordinates(1, RectF(0f, 0f, 1000f, 100f), emptyList(), emptyList()), + canvas, + ImageView(ApplicationProvider.getApplicationContext()) + ) + return canvas + } + + private class RecordingCanvas : Canvas(Bitmap.createBitmap(1000, 100, Bitmap.Config.ARGB_8888)) { + val rects = mutableListOf() + val clipped = mutableListOf() + val alphas = mutableListOf() + + override fun drawRect(rect: RectF, paint: android.graphics.Paint) { + rects += RectF(rect) + alphas += android.graphics.Color.alpha(paint.color) + } + + override fun clipOutRect(rect: RectF): Boolean { + clipped += RectF(rect) + return true + } + } + + private companion object { + val HIDE_TYPE = HighlightType(1001, android.R.color.black, HighlightType.Mode.HIDE) + val UNDERLAY_TYPE = HighlightType(1002, android.R.color.white, HighlightType.Mode.UNDERLAY) + } +} diff --git a/app/src/test/kotlin/com/quran/labs/androidquran/feature/reading/presenter/ReadingBookmarkPresenterTest.kt b/app/src/test/kotlin/com/quran/labs/androidquran/feature/reading/presenter/ReadingBookmarkPresenterTest.kt index f3d88fb93f..5d83f17c5a 100644 --- a/app/src/test/kotlin/com/quran/labs/androidquran/feature/reading/presenter/ReadingBookmarkPresenterTest.kt +++ b/app/src/test/kotlin/com/quran/labs/androidquran/feature/reading/presenter/ReadingBookmarkPresenterTest.kt @@ -366,6 +366,68 @@ class ReadingBookmarkPresenterTest { assertThat(change.previous).isNull() } + @Test + fun `the toast goes away by itself, after longer the first time`() = runTest { + val readingBookmarksDao = FakeReadingBookmarksDao() + val screen = RecordingScreen() + val presenter = presenter(readingBookmarksDao) + + presenter.bind(flowOf(42), screen) + testDispatcher.scheduler.advanceUntilIdle() + // the first placement explains that pins move: 20 seconds + presenter.placeReadingBookmark(ReadingBookmarkType.ORANGE, ReadingBookmarkTarget.Page(42)) + waitForRealDispatch() + testDispatcher.scheduler.advanceTimeBy(19_900) + testDispatcher.scheduler.runCurrent() + assertThat(screen.dismissCount).isEqualTo(0) + testDispatcher.scheduler.advanceTimeBy(200) + testDispatcher.scheduler.runCurrent() + assertThat(screen.dismissCount).isEqualTo(1) + + // later ones: 10 seconds + presenter.placeReadingBookmark(ReadingBookmarkType.ORANGE, ReadingBookmarkTarget.Page(43)) + testDispatcher.scheduler.advanceTimeBy(9_900) + testDispatcher.scheduler.runCurrent() + assertThat(screen.dismissCount).isEqualTo(1) + testDispatcher.scheduler.advanceTimeBy(200) + testDispatcher.scheduler.runCurrent() + assertThat(screen.dismissCount).isEqualTo(2) + } + + @Test + fun `ok takes the toast down at once`() = runTest { + val readingBookmarksDao = FakeReadingBookmarksDao(pageBookmark(10, ReadingBookmarkType.TEAL)) + val screen = RecordingScreen() + val presenter = presenter(readingBookmarksDao) + + presenter.bind(flowOf(42), screen) + testDispatcher.scheduler.advanceUntilIdle() + presenter.placeReadingBookmark(ReadingBookmarkType.TEAL, ReadingBookmarkTarget.Page(42)) + screen.dismissActions.last().invoke() + assertThat(screen.dismissCount).isEqualTo(1) + + // and its timeout is gone with it + testDispatcher.scheduler.advanceTimeBy(60_000) + testDispatcher.scheduler.runCurrent() + assertThat(screen.dismissCount).isEqualTo(1) + waitForRealDispatch() + assertThat(readingBookmarksDao.readingBookmarks()).containsExactly(pageBookmark(42, ReadingBookmarkType.TEAL)) + } + + @Test + fun `leaving the screen takes the toast down`() = runTest { + val readingBookmarksDao = FakeReadingBookmarksDao(pageBookmark(10, ReadingBookmarkType.TEAL)) + val screen = RecordingScreen() + val presenter = presenter(readingBookmarksDao) + + presenter.bind(flowOf(42), screen) + testDispatcher.scheduler.advanceUntilIdle() + presenter.placeReadingBookmark(ReadingBookmarkType.TEAL, ReadingBookmarkTarget.Page(42)) + // e.g. the screen turns off before the toast times out: when it comes back, no toast is stuck + presenter.unbind(screen) + assertThat(screen.dismissCount).isEqualTo(1) + } + private class RecordingScreen : ReadingBookmarkPresenter.Screen { val pageBookmarkStates = mutableListOf() val changes = mutableListOf() diff --git a/common/bookmark/src/main/java/com/quran/mobile/bookmark/importdata/BookmarkBackupImportNormalizer.kt b/common/bookmark/src/main/java/com/quran/mobile/bookmark/importdata/BookmarkBackupImportNormalizer.kt index bbb620a716..8aece7a105 100644 --- a/common/bookmark/src/main/java/com/quran/mobile/bookmark/importdata/BookmarkBackupImportNormalizer.kt +++ b/common/bookmark/src/main/java/com/quran/mobile/bookmark/importdata/BookmarkBackupImportNormalizer.kt @@ -107,7 +107,8 @@ class BookmarkBackupImportNormalizer @Inject constructor( readingBookmarks: List, pageType: String? ): List { - return readingBookmarks.mapNotNull { readingBookmark -> + // only the synced slots go to mobile-sync (the others are in BookmarkData.localReadingBookmarks) + return readingBookmarks.filter { it.slot.synced }.mapNotNull { readingBookmark -> when (readingBookmark.type) { BackupReadingBookmark.TYPE_AYAH -> { val sura = readingBookmark.sura @@ -150,6 +151,7 @@ class BookmarkBackupImportNormalizer @Inject constructor( ReadingBookmarkType.TEAL -> ReadingBookmarkSlot.TEAL ReadingBookmarkType.ORANGE -> ReadingBookmarkSlot.ORANGE ReadingBookmarkType.RED -> ReadingBookmarkSlot.RED + else -> error("$this is kept on the device, not by mobile-sync") } } diff --git a/common/bookmark/src/main/java/com/quran/mobile/bookmark/importdata/LocalReadingBookmarkImporter.kt b/common/bookmark/src/main/java/com/quran/mobile/bookmark/importdata/LocalReadingBookmarkImporter.kt new file mode 100644 index 0000000000..96b560b559 --- /dev/null +++ b/common/bookmark/src/main/java/com/quran/mobile/bookmark/importdata/LocalReadingBookmarkImporter.kt @@ -0,0 +1,45 @@ +package com.quran.mobile.bookmark.importdata + +import com.quran.data.dao.ReadingBookmarkSlotSettings +import com.quran.data.model.SuraAyah +import com.quran.data.model.bookmark.BackupReadingBookmark +import com.quran.mobile.bookmark.model.LocalReadingBookmarks +import com.quran.mobile.bookmark.model.ReadingBookmarkPageMapper +import com.quran.data.di.AppScope +import dev.zacsweers.metro.ContributesBinding +import dev.zacsweers.metro.Inject + +/** Restores a backup's reading bookmarks kept on the device only, and turns their slots on. */ +fun interface LocalReadingBookmarkImporter { + suspend fun import(bookmarks: List, sourcePageType: String?) +} + +@ContributesBinding(AppScope::class) +class LocalReadingBookmarkImporterImpl @Inject constructor( + private val localBookmarks: LocalReadingBookmarks, + private val slotSettings: ReadingBookmarkSlotSettings, + private val pageMapper: ReadingBookmarkPageMapper, +) : LocalReadingBookmarkImporter { + override suspend fun import(bookmarks: List, sourcePageType: String?) { + val pageType = pageMapper.currentPageType() + bookmarks.filterNot { it.slot.synced }.forEach { bookmark -> + val atMs = bookmark.timestamp.toEpochMilliseconds() + val sura = bookmark.sura + val ayah = bookmark.ayah + val page = bookmark.page + when { + bookmark.type == BackupReadingBookmark.TYPE_AYAH && sura != null && ayah != null && + pageMapper.isValidSuraAyah(sura, ayah) -> + localBookmarks.setAyah(bookmark.slot, SuraAyah(sura, ayah), atMs) + bookmark.type == BackupReadingBookmark.TYPE_PAGE && page != null -> { + val first = pageMapper.sourcePageToSuraAyah(page, sourcePageType) + val pageHere = if (sourcePageType == pageType) page else pageMapper.suraAyahToPage(first.sura, first.ayah, pageType) + localBookmarks.setPage(bookmark.slot, pageHere, pageType, atMs) + } + else -> return@forEach + } + bookmark.name?.let { localBookmarks.rename(bookmark.slot, it, atMs) } + slotSettings.setEnabled(bookmark.slot, true) + } + } +} diff --git a/common/bookmark/src/main/java/com/quran/mobile/bookmark/model/LocalReadingBookmarks.kt b/common/bookmark/src/main/java/com/quran/mobile/bookmark/model/LocalReadingBookmarks.kt new file mode 100644 index 0000000000..cbb3ecb287 --- /dev/null +++ b/common/bookmark/src/main/java/com/quran/mobile/bookmark/model/LocalReadingBookmarks.kt @@ -0,0 +1,99 @@ +package com.quran.mobile.bookmark.model + +import app.cash.sqldelight.coroutines.asFlow +import app.cash.sqldelight.coroutines.mapToList +import com.quran.data.di.AppScope +import com.quran.data.model.SuraAyah +import com.quran.data.model.bookmark.AyahReadingBookmark +import com.quran.data.model.bookmark.EmptyReadingBookmark +import com.quran.data.model.bookmark.PageReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.labs.androidquran.BookmarksDatabase +import com.quran.mobile.bookmark.Local_reading_bookmark +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.withContext +import kotlin.time.Instant + +/** + * The reading bookmarks past mobile-sync's three slots, kept in the bookmarks database on this + * device. A page bookmark keeps its page type and first ayah too, so it is shown on the page with + * that ayah in another page type, as mobile-sync maps its own. + */ +@SingleIn(AppScope::class) +class LocalReadingBookmarks @Inject constructor( + database: BookmarksDatabase, + private val pageMapper: ReadingBookmarkPageMapper, +) { + private val queries = database.localReadingBookmarkQueries + + fun rowsFlow(): Flow> = + queries.localReadingBookmarks().asFlow().mapToList(Dispatchers.IO) + + suspend fun rows(): List = withContext(Dispatchers.IO) { + queries.localReadingBookmarks().executeAsList() + } + + /** [rows] as bookmarks of [pageType], for the [enabled] slots, in slot order. */ + fun toReadingBookmarks( + rows: List, + enabled: Set, + pageType: String, + ): List { + val bySlot = rows.associateBy { it.slot } + return ReadingBookmarkType.entries.filter { !it.synced && it in enabled }.map { slot -> + val row = bySlot[slot.name] + val timestamp = Instant.fromEpochMilliseconds(row?.updated_at ?: 0L) + val sura = row?.sura?.toInt() + val ayah = row?.ayah?.toInt() + when { + row == null || sura == null || ayah == null -> EmptyReadingBookmark(slot, timestamp, row?.name) + row.page != null -> PageReadingBookmark(slot, pageOf(row, pageType), timestamp, row.name) + else -> AyahReadingBookmark(slot, sura, ayah, timestamp, row.name) + } + } + } + + suspend fun setPage(slot: ReadingBookmarkType, page: Int, pageType: String, atMs: Long) { + val first = pageMapper.sourcePageToSuraAyah(page, pageType) + write(slot, atMs) { queries.setLocalPosition(first.sura.toLong(), first.ayah.toLong(), page.toLong(), pageType, atMs, slot.name) } + } + + suspend fun setAyah(slot: ReadingBookmarkType, suraAyah: SuraAyah, atMs: Long) { + write(slot, atMs) { queries.setLocalPosition(suraAyah.sura.toLong(), suraAyah.ayah.toLong(), null, null, atMs, slot.name) } + } + + suspend fun clear(slot: ReadingBookmarkType, atMs: Long): ReadingBookmark { + write(slot, atMs) { queries.setLocalPosition(null, null, null, null, atMs, slot.name) } + val name = rows().firstOrNull { it.slot == slot.name }?.name + return EmptyReadingBookmark(slot, Instant.fromEpochMilliseconds(atMs), name) + } + + suspend fun rename(slot: ReadingBookmarkType, name: String?, atMs: Long) { + write(slot, atMs) { queries.renameLocalReadingBookmark(name?.takeIf { it.isNotBlank() }, slot.name) } + } + + /** Whether [slot] is a page bookmark on [page] of [pageType]. */ + suspend fun isOnPage(slot: ReadingBookmarkType, page: Int, pageType: String): Boolean { + val row = rows().firstOrNull { it.slot == slot.name } ?: return false + return row.page != null && row.sura != null && pageOf(row, pageType) == page + } + + private fun pageOf(row: Local_reading_bookmark, pageType: String): Int { + val page = row.page!!.toInt() + return if (row.page_type == pageType) page else pageMapper.suraAyahToPage(row.sura!!.toInt(), row.ayah!!.toInt(), pageType) + } + + private suspend fun write(slot: ReadingBookmarkType, atMs: Long, block: () -> Unit) { + require(!slot.synced) { "$slot is kept by mobile-sync" } + withContext(Dispatchers.IO) { + queries.transaction { + queries.ensureLocalReadingBookmark(slot.name, atMs) + block() + } + } + } +} diff --git a/common/bookmark/src/main/java/com/quran/mobile/bookmark/model/ReadingBookmarkSlotSettingsImpl.kt b/common/bookmark/src/main/java/com/quran/mobile/bookmark/model/ReadingBookmarkSlotSettingsImpl.kt new file mode 100644 index 0000000000..722bf730a4 --- /dev/null +++ b/common/bookmark/src/main/java/com/quran/mobile/bookmark/model/ReadingBookmarkSlotSettingsImpl.kt @@ -0,0 +1,87 @@ +package com.quran.mobile.bookmark.model + +import app.cash.sqldelight.coroutines.asFlow +import app.cash.sqldelight.coroutines.mapToList +import com.quran.data.dao.ReadingBookmarkSlotSettings +import com.quran.data.di.AppScope +import com.quran.data.model.bookmark.ReadingBookmarkPurpose +import com.quran.data.model.bookmark.ReadingBookmarkSlotSetting +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.labs.androidquran.BookmarksDatabase +import com.quran.mobile.bookmark.Reading_bookmark_setting +import dev.zacsweers.metro.ContributesBinding +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.withContext + +/** + * Reading bookmark slot settings, kept in the bookmarks database. By default the three synced + * slots are on and for reading, teal with a 30-day cycle; the others are off. + */ +@SingleIn(AppScope::class) +@ContributesBinding(AppScope::class) +class ReadingBookmarkSlotSettingsImpl @Inject constructor(database: BookmarksDatabase) : ReadingBookmarkSlotSettings { + private val queries = database.localReadingBookmarkQueries + + override fun settingsFlow(): Flow> { + return queries.slotSettings().asFlow().mapToList(Dispatchers.IO).map { merge(it) }.distinctUntilChanged() + } + + override suspend fun settings(): List = withContext(Dispatchers.IO) { + merge(queries.slotSettings().executeAsList()) + } + + override suspend fun setEnabled(slot: ReadingBookmarkType, enabled: Boolean) { + // the synced slots are always offered + if (slot.synced) return + update(slot) { it.copy(enabled = enabled) } + } + + override suspend fun setPurpose(slot: ReadingBookmarkType, purpose: ReadingBookmarkPurpose) { + update(slot) { it.copy(purpose = purpose) } + } + + override suspend fun setTargetDays(slot: ReadingBookmarkType, days: Int) { + update(slot) { it.copy(targetDays = days.coerceIn(0, MAX_TARGET_DAYS)) } + } + + private suspend fun update(slot: ReadingBookmarkType, change: (ReadingBookmarkSlotSetting) -> ReadingBookmarkSlotSetting) { + withContext(Dispatchers.IO) { + queries.transaction { + val current = merge(queries.slotSettings().executeAsList()).first { it.slot == slot } + val updated = change(current) + queries.setSlotSetting( + slot.name, if (updated.enabled) 1L else 0L, updated.purpose.name, updated.targetDays.toLong() + ) + } + } + } + + companion object { + const val MAX_TARGET_DAYS = 366 + + fun defaultSetting(slot: ReadingBookmarkType): ReadingBookmarkSlotSetting = ReadingBookmarkSlotSetting( + slot = slot, + enabled = slot.synced, + purpose = ReadingBookmarkPurpose.READING, + targetDays = if (slot == ReadingBookmarkType.TEAL) ReadingBookmarkSlotSetting.DEFAULT_TARGET_DAYS else 0, + ) + + private fun merge(rows: List): List { + val bySlot = rows.associateBy { it.slot } + return ReadingBookmarkType.entries.map { slot -> + val row = bySlot[slot.name] ?: return@map defaultSetting(slot) + ReadingBookmarkSlotSetting( + slot = slot, + enabled = slot.synced || row.enabled != 0L, + purpose = ReadingBookmarkPurpose.entries.firstOrNull { it.name == row.purpose } ?: ReadingBookmarkPurpose.READING, + targetDays = row.target_days.toInt(), + ) + } + } + } +} diff --git a/common/bookmark/src/main/java/com/quran/mobile/bookmark/model/ReadingBookmarksDaoImpl.kt b/common/bookmark/src/main/java/com/quran/mobile/bookmark/model/ReadingBookmarksDaoImpl.kt index 734f3e4bd2..48a8639963 100644 --- a/common/bookmark/src/main/java/com/quran/mobile/bookmark/model/ReadingBookmarksDaoImpl.kt +++ b/common/bookmark/src/main/java/com/quran/mobile/bookmark/model/ReadingBookmarksDaoImpl.kt @@ -1,5 +1,6 @@ package com.quran.mobile.bookmark.model +import com.quran.data.dao.ReadingBookmarkSlotSettings import com.quran.data.dao.ReadingBookmarksDao import com.quran.data.di.AppScope import com.quran.data.model.SuraAyah @@ -7,21 +8,23 @@ import com.quran.data.model.bookmark.AyahReadingBookmark import com.quran.data.model.bookmark.EmptyReadingBookmark import com.quran.data.model.bookmark.PageReadingBookmark import com.quran.data.model.bookmark.ReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmarkSlotSetting import com.quran.data.model.bookmark.ReadingBookmarkType import com.quran.mobile.bookmark.time.MobileSyncTimestampProvider import com.quran.shared.persistence.model.Mushaf import com.quran.shared.persistence.model.ReadingBookmarkSlot import com.quran.shared.persistence.repository.readingbookmark.repository.ReadingBookmarksRepository import com.quran.shared.persistence.util.PlatformDateTime +import com.quran.shared.persistence.util.fromPlatform import dev.zacsweers.metro.Inject import dev.zacsweers.metro.SingleIn import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOn -import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import com.quran.shared.persistence.model.AyahReadingBookmark as SyncAyahReadingBookmark import com.quran.shared.persistence.model.EmptyReadingBookmark as SyncEmptyReadingBookmark @@ -29,7 +32,9 @@ import com.quran.shared.persistence.model.PageReadingBookmark as SyncPageReading import com.quran.shared.persistence.model.ReadingBookmark as SyncReadingBookmark /** - * Reading bookmark DAO backed by mobile-sync persistence. + * Reading bookmark DAO backed by mobile-sync persistence for the synced slots, and by + * [LocalReadingBookmarks] for the slots kept on the device (offered once turned on, see + * [ReadingBookmarkSlotSettings]). * * Page bookmarks are set and read in the current page type's mobile-sync [Mushaf], which maps them * between mushafs, so their pages pass through unchanged. @@ -37,12 +42,16 @@ import com.quran.shared.persistence.model.ReadingBookmark as SyncReadingBookmark * @param pageMapper resolves the current page type and its [Mushaf]. * @param readingBookmarksRepository mobile-sync repository that owns persisted reading bookmark rows. * @param timestampProvider provides the timestamp assigned to locally written bookmarks. + * @param localBookmarks keeps the slots that don't sync. + * @param slotSettings which of those are on. */ @SingleIn(AppScope::class) class ReadingBookmarksDaoImpl @Inject constructor( private val pageMapper: ReadingBookmarkPageMapper, private val readingBookmarksRepository: ReadingBookmarksRepository, - private val timestampProvider: MobileSyncTimestampProvider + private val timestampProvider: MobileSyncTimestampProvider, + private val localBookmarks: LocalReadingBookmarks, + private val slotSettings: ReadingBookmarkSlotSettings, ) : ReadingBookmarksDao { @OptIn(ExperimentalCoroutinesApi::class) override fun readingBookmarksFlow(): Flow> { @@ -50,8 +59,14 @@ class ReadingBookmarksDaoImpl @Inject constructor( // previously cached null. The IO dispatcher preserves the old off-main mapping behavior. return pageMapper.pageTypeFlow() .flatMapLatest { pageType -> - readingBookmarksRepository.getReadingBookmarksFlow(pageMapper.mushafFor(pageType)) - .map { bookmarks -> bookmarks.map { toReadingBookmark(it) } } + combine( + readingBookmarksRepository.getReadingBookmarksFlow(pageMapper.mushafFor(pageType)), + localBookmarks.rowsFlow(), + slotSettings.settingsFlow(), + ) { synced, local, settings -> + synced.map { toReadingBookmark(it) } + + localBookmarks.toReadingBookmarks(local, settings.enabledSlots(), pageType) + } } .distinctUntilChanged() .flowOn(Dispatchers.IO) @@ -59,12 +74,18 @@ class ReadingBookmarksDaoImpl @Inject constructor( override suspend fun readingBookmarks(): List { return withContext(Dispatchers.IO) { - readingBookmarksRepository.getReadingBookmarks(currentMushaf()) - .map { toReadingBookmark(it) } + val synced = readingBookmarksRepository.getReadingBookmarks(currentMushaf()).map { toReadingBookmark(it) } + synced + localBookmarks.toReadingBookmarks( + localBookmarks.rows(), slotSettings.settings().enabledSlots(), pageMapper.currentPageType() + ) } } override suspend fun setPageReadingBookmark(slot: ReadingBookmarkType, page: Int): Boolean { + if (!slot.synced) { + localBookmarks.setPage(slot, page, pageMapper.currentPageType(), timestampProvider.nowEpochMillis()) + return true + } val timestamp = timestampProvider.now() return withContext(Dispatchers.IO) { setPageReadingBookmark(slot, page, currentMushaf(), timestamp) @@ -91,6 +112,10 @@ class ReadingBookmarksDaoImpl @Inject constructor( } override suspend fun setAyahReadingBookmark(slot: ReadingBookmarkType, suraAyah: SuraAyah): Boolean { + if (!slot.synced) { + localBookmarks.setAyah(slot, suraAyah, timestampProvider.nowEpochMillis()) + return true + } val timestamp = timestampProvider.now() val set = withContext(Dispatchers.IO) { readingBookmarksRepository.setAyahReadingBookmark(slot.toSyncSlot(), suraAyah.sura, suraAyah.ayah, timestamp) @@ -100,6 +125,7 @@ class ReadingBookmarksDaoImpl @Inject constructor( } override suspend fun clearReadingBookmark(slot: ReadingBookmarkType): ReadingBookmark { + if (!slot.synced) return localBookmarks.clear(slot, timestampProvider.nowEpochMillis()) val cleared = withContext(Dispatchers.IO) { readingBookmarksRepository.clearReadingBookmark(slot.toSyncSlot()) } @@ -107,12 +133,14 @@ class ReadingBookmarksDaoImpl @Inject constructor( } override suspend fun renameReadingBookmark(slot: ReadingBookmarkType, name: String?) { + if (!slot.synced) return localBookmarks.rename(slot, name, timestampProvider.nowEpochMillis()) withContext(Dispatchers.IO) { readingBookmarksRepository.renameReadingBookmark(slot.toSyncSlot(), name, currentMushaf()) } } override suspend fun isPageReadingBookmark(slot: ReadingBookmarkType, page: Int): Boolean { + if (!slot.synced) return localBookmarks.isOnPage(slot, page, pageMapper.currentPageType()) return withContext(Dispatchers.IO) { isPageReadingBookmark(slot, page, currentMushaf()) } @@ -126,6 +154,14 @@ class ReadingBookmarksDaoImpl @Inject constructor( } override suspend fun togglePageReadingBookmark(slot: ReadingBookmarkType, page: Int): Boolean { + if (!slot.synced) { + return if (isPageReadingBookmark(slot, page)) { + clearReadingBookmark(slot) + false + } else { + setPageReadingBookmark(slot, page) + } + } val timestamp = timestampProvider.now() return withContext(Dispatchers.IO) { val mushaf = currentMushaf() @@ -173,6 +209,19 @@ class ReadingBookmarksDaoImpl @Inject constructor( val mushaf = currentMushaf() var allSet = true added.forEach { readingBookmark -> + if (!readingBookmark.slot.synced) { + when (readingBookmark) { + is AyahReadingBookmark -> localBookmarks.setAyah( + readingBookmark.slot, readingBookmark.asSuraAyah(), timestamp.fromPlatform().toEpochMilliseconds() + ) + is PageReadingBookmark -> localBookmarks.setPage( + readingBookmark.slot, readingBookmark.page, pageMapper.currentPageType(), + timestamp.fromPlatform().toEpochMilliseconds() + ) + is EmptyReadingBookmark -> {} + } + return@forEach + } when (readingBookmark) { is AyahReadingBookmark -> readingBookmarksRepository.setAyahReadingBookmark( @@ -191,7 +240,11 @@ class ReadingBookmarksDaoImpl @Inject constructor( } removed.forEach { readingBookmark -> - readingBookmarksRepository.clearReadingBookmark(readingBookmark.slot.toSyncSlot()) + if (readingBookmark.slot.synced) { + readingBookmarksRepository.clearReadingBookmark(readingBookmark.slot.toSyncSlot()) + } else { + localBookmarks.clear(readingBookmark.slot, timestamp.fromPlatform().toEpochMilliseconds()) + } } allSet } @@ -210,5 +263,9 @@ class ReadingBookmarksDaoImpl @Inject constructor( ReadingBookmarkType.TEAL -> ReadingBookmarkSlot.TEAL ReadingBookmarkType.ORANGE -> ReadingBookmarkSlot.ORANGE ReadingBookmarkType.RED -> ReadingBookmarkSlot.RED + else -> error("$this is kept on the device, not by mobile-sync") } + + private fun List.enabledSlots(): Set = + filter { it.enabled }.mapTo(HashSet()) { it.slot } } diff --git a/common/bookmark/src/main/sqldelight/com/quran/mobile/bookmark/LocalReadingBookmark.sq b/common/bookmark/src/main/sqldelight/com/quran/mobile/bookmark/LocalReadingBookmark.sq new file mode 100644 index 0000000000..1b618015df --- /dev/null +++ b/common/bookmark/src/main/sqldelight/com/quran/mobile/bookmark/LocalReadingBookmark.sq @@ -0,0 +1,41 @@ +-- The reading bookmarks kept on this device only: the slots past mobile-sync's three. +CREATE TABLE IF NOT EXISTS local_reading_bookmark( + -- ReadingBookmarkType's name + slot TEXT NOT NULL PRIMARY KEY, + name TEXT, + -- an ayah bookmark has its sura and ayah; a page bookmark also has its page in page_type + sura INTEGER, + ayah INTEGER, + page INTEGER, + page_type TEXT, + updated_at INTEGER NOT NULL +); + +-- How the user set up each reading bookmark slot, synced or not (a slot without a row has the +-- defaults in ReadingBookmarkSlotSettingsImpl). +CREATE TABLE IF NOT EXISTS reading_bookmark_setting( + slot TEXT NOT NULL PRIMARY KEY, + enabled INTEGER NOT NULL, + -- ReadingBookmarkPurpose's name + purpose TEXT NOT NULL, + -- days to read the Quran in; 0 for no deadline + target_days INTEGER NOT NULL +); + +localReadingBookmarks: +SELECT * FROM local_reading_bookmark; + +ensureLocalReadingBookmark: +INSERT OR IGNORE INTO local_reading_bookmark(slot, updated_at) VALUES (?, ?); + +setLocalPosition: +UPDATE local_reading_bookmark SET sura = ?, ayah = ?, page = ?, page_type = ?, updated_at = ? WHERE slot = ?; + +renameLocalReadingBookmark: +UPDATE local_reading_bookmark SET name = ? WHERE slot = ?; + +slotSettings: +SELECT * FROM reading_bookmark_setting; + +setSlotSetting: +INSERT OR REPLACE INTO reading_bookmark_setting(slot, enabled, purpose, target_days) VALUES (?, ?, ?, ?); diff --git a/common/bookmark/src/main/sqldelight/com/quran/mobile/bookmark/migrations/4.sqm b/common/bookmark/src/main/sqldelight/com/quran/mobile/bookmark/migrations/4.sqm new file mode 100644 index 0000000000..7830cc4fb3 --- /dev/null +++ b/common/bookmark/src/main/sqldelight/com/quran/mobile/bookmark/migrations/4.sqm @@ -0,0 +1,17 @@ +-- reading bookmarks kept on this device only, and how each reading bookmark slot is set up +CREATE TABLE IF NOT EXISTS local_reading_bookmark( + slot TEXT NOT NULL PRIMARY KEY, + name TEXT, + sura INTEGER, + ayah INTEGER, + page INTEGER, + page_type TEXT, + updated_at INTEGER NOT NULL +); + +CREATE TABLE IF NOT EXISTS reading_bookmark_setting( + slot TEXT NOT NULL PRIMARY KEY, + enabled INTEGER NOT NULL, + purpose TEXT NOT NULL, + target_days INTEGER NOT NULL +); diff --git a/common/bookmark/src/test/kotlin/com/quran/mobile/bookmark/db/InMemoryMobileSyncDatabase.kt b/common/bookmark/src/test/kotlin/com/quran/mobile/bookmark/db/InMemoryMobileSyncDatabase.kt index 0994688cd5..24fba9afe7 100644 --- a/common/bookmark/src/test/kotlin/com/quran/mobile/bookmark/db/InMemoryMobileSyncDatabase.kt +++ b/common/bookmark/src/test/kotlin/com/quran/mobile/bookmark/db/InMemoryMobileSyncDatabase.kt @@ -1,6 +1,12 @@ package com.quran.mobile.bookmark.db +import android.content.Context +import app.cash.sqldelight.adapter.primitive.IntColumnAdapter +import app.cash.sqldelight.driver.android.AndroidSqliteDriver import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver +import com.quran.labs.androidquran.BookmarksDatabase +import com.quran.mobile.bookmark.Bookmarks +import com.quran.mobile.bookmark.Last_pages import com.quran.shared.persistence.MobileSyncDatabase import com.quran.shared.persistence.MobileSyncSchema import java.util.Properties @@ -17,3 +23,16 @@ internal fun inMemoryMobileSyncDatabase(): MobileSyncDatabase { ) return MobileSyncDatabase(driver) } + +/** + * A fresh in-memory bookmarks database (bookmarks.db), opened through Robolectric's SQLite as the + * Android driver opens it (JDBC drivers don't always register in Robolectric's class loaders). + */ +internal fun inMemoryBookmarksDatabase(context: Context): BookmarksDatabase { + val driver = AndroidSqliteDriver(BookmarksDatabase.Schema, context, name = null) + return BookmarksDatabase( + driver, + Bookmarks.Adapter(IntColumnAdapter, IntColumnAdapter, IntColumnAdapter), + Last_pages.Adapter(IntColumnAdapter) + ) +} diff --git a/common/bookmark/src/test/kotlin/com/quran/mobile/bookmark/model/ReadingBookmarksDaoImplTest.kt b/common/bookmark/src/test/kotlin/com/quran/mobile/bookmark/model/ReadingBookmarksDaoImplTest.kt index 97fb9a46a7..472811c826 100644 --- a/common/bookmark/src/test/kotlin/com/quran/mobile/bookmark/model/ReadingBookmarksDaoImplTest.kt +++ b/common/bookmark/src/test/kotlin/com/quran/mobile/bookmark/model/ReadingBookmarksDaoImplTest.kt @@ -14,6 +14,8 @@ import com.quran.data.model.bookmark.ReadingBookmark import com.quran.data.model.bookmark.ReadingBookmarkType import com.quran.data.source.MushafType import com.quran.labs.androidquran.pages.data.madani.MadaniDataSource +import com.quran.labs.androidquran.BookmarksDatabase +import com.quran.mobile.bookmark.db.inMemoryBookmarksDatabase import com.quran.mobile.bookmark.di.MobileSyncDatabase import com.quran.mobile.bookmark.time.FakeMobileSyncTimestampProvider import com.quran.shared.persistence.model.AyahReadingBookmark as SyncAyahReadingBookmark @@ -43,6 +45,8 @@ class ReadingBookmarksDaoImplTest { private lateinit var dao: ReadingBookmarksDaoImpl private lateinit var settings: FakeSettings private lateinit var timestampProvider: FakeMobileSyncTimestampProvider + private lateinit var bookmarksDatabase: BookmarksDatabase + private lateinit var slotSettings: ReadingBookmarkSlotSettingsImpl @Before fun setup() { @@ -67,10 +71,14 @@ class ReadingBookmarksDaoImplTest { ), fallbackPageType = "madani" ) + bookmarksDatabase = inMemoryBookmarksDatabase(context) + slotSettings = ReadingBookmarkSlotSettingsImpl(bookmarksDatabase) dao = ReadingBookmarksDaoImpl( pageMapper = pageMapper, readingBookmarksRepository = renameSpy, - timestampProvider = timestampProvider + timestampProvider = timestampProvider, + localBookmarks = LocalReadingBookmarks(bookmarksDatabase, pageMapper), + slotSettings = slotSettings, ) } @@ -79,6 +87,84 @@ class ReadingBookmarksDaoImplTest { assertThat(dao.readingBookmarks()).isEmpty() } + @Test + fun `a slot kept on the device is listed only once it is turned on`() = runTest { + assertThat(dao.readingBookmarks()).isEmpty() + + slotSettings.setEnabled(ReadingBookmarkType.GREEN, true) + + val listed = dao.readingBookmarks().single() + assertThat(listed).isInstanceOf(EmptyReadingBookmark::class.java) + assertThat(listed.slot).isEqualTo(ReadingBookmarkType.GREEN) + } + + @Test + fun `a page bookmark kept on the device is placed, renamed and cleared without mobile-sync`() = runTest { + slotSettings.setEnabled(ReadingBookmarkType.GREEN, true) + + assertThat(dao.setPageReadingBookmark(ReadingBookmarkType.GREEN, 262)).isTrue() + dao.renameReadingBookmark(ReadingBookmarkType.GREEN, "Khatma") + + val bookmark = dao.readingBookmarks().single() as PageReadingBookmark + assertThat(bookmark.slot).isEqualTo(ReadingBookmarkType.GREEN) + assertThat(bookmark.page).isEqualTo(262) + assertThat(bookmark.name).isEqualTo("Khatma") + assertThat(dao.isPageReadingBookmark(ReadingBookmarkType.GREEN, 262)).isTrue() + assertThat(repository.getReadingBookmarks(Mushaf.MADANI_1405)).isEmpty() + + val cleared = dao.clearReadingBookmark(ReadingBookmarkType.GREEN) + assertThat(cleared).isInstanceOf(EmptyReadingBookmark::class.java) + assertThat(cleared.name).isEqualTo("Khatma") + assertThat(dao.readingBookmarks().single()).isInstanceOf(EmptyReadingBookmark::class.java) + } + + @Test + fun `an ayah bookmark kept on the device is listed with the synced ones`() = runTest { + slotSettings.setEnabled(ReadingBookmarkType.BLUE, true) + dao.setPageReadingBookmark(ReadingBookmarkType.TEAL, 42) + dao.setAyahReadingBookmark(ReadingBookmarkType.BLUE, SuraAyah(18, 1)) + + dao.readingBookmarksFlow().test { + val bookmarks = awaitItem() + assertThat(bookmarks.map { it.slot }).containsExactly(ReadingBookmarkType.TEAL, ReadingBookmarkType.BLUE).inOrder() + assertThat((bookmarks[1] as AyahReadingBookmark).asSuraAyah()).isEqualTo(SuraAyah(18, 1)) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `a slot turned off is no longer listed but keeps its place`() = runTest { + slotSettings.setEnabled(ReadingBookmarkType.PURPLE, true) + dao.setPageReadingBookmark(ReadingBookmarkType.PURPLE, 100) + + slotSettings.setEnabled(ReadingBookmarkType.PURPLE, false) + assertThat(dao.readingBookmarks()).isEmpty() + + slotSettings.setEnabled(ReadingBookmarkType.PURPLE, true) + assertThat((dao.readingBookmarks().single() as PageReadingBookmark).page).isEqualTo(100) + } + + @Test + fun `toggling a page bookmark kept on the device`() = runTest { + slotSettings.setEnabled(ReadingBookmarkType.GREY, true) + assertThat(dao.togglePageReadingBookmark(ReadingBookmarkType.GREY, 7)).isTrue() + assertThat(dao.togglePageReadingBookmark(ReadingBookmarkType.GREY, 7)).isFalse() + assertThat(dao.readingBookmarks().single()).isInstanceOf(EmptyReadingBookmark::class.java) + } + + @Test + fun `the slot settings default to the synced slots on, for reading, teal in 30 days`() = runTest { + val settings = slotSettings.settings() + assertThat(settings.filter { it.enabled }.map { it.slot }) + .containsExactly(ReadingBookmarkType.TEAL, ReadingBookmarkType.ORANGE, ReadingBookmarkType.RED).inOrder() + assertThat(settings.first().targetDays).isEqualTo(30) + assertThat(settings.drop(1).map { it.targetDays }.distinct()).containsExactly(0) + + // the synced slots can't be turned off + slotSettings.setEnabled(ReadingBookmarkType.RED, false) + assertThat(slotSettings.settings().single { it.slot == ReadingBookmarkType.RED }.enabled).isTrue() + } + @Test fun `set page reading bookmark stores mobile sync page reading bookmark`() = runTest { dao.setPageReadingBookmark(ReadingBookmarkType.ORANGE, 42) diff --git a/common/data/src/main/java/com/quran/data/dao/ReadingBookmarkSlotSettings.kt b/common/data/src/main/java/com/quran/data/dao/ReadingBookmarkSlotSettings.kt new file mode 100644 index 0000000000..19d36817d7 --- /dev/null +++ b/common/data/src/main/java/com/quran/data/dao/ReadingBookmarkSlotSettings.kt @@ -0,0 +1,16 @@ +package com.quran.data.dao + +import com.quran.data.model.bookmark.ReadingBookmarkPurpose +import com.quran.data.model.bookmark.ReadingBookmarkSlotSetting +import com.quran.data.model.bookmark.ReadingBookmarkType +import kotlinx.coroutines.flow.Flow + +/** Which reading bookmark slots are on, and what each is for. Kept on the device. */ +interface ReadingBookmarkSlotSettings { + /** Every slot's setting, in slot order. */ + fun settingsFlow(): Flow> + suspend fun settings(): List + suspend fun setEnabled(slot: ReadingBookmarkType, enabled: Boolean) + suspend fun setPurpose(slot: ReadingBookmarkType, purpose: ReadingBookmarkPurpose) + suspend fun setTargetDays(slot: ReadingBookmarkType, days: Int) +} diff --git a/common/data/src/main/java/com/quran/data/model/bookmark/BookmarkData.kt b/common/data/src/main/java/com/quran/data/model/bookmark/BookmarkData.kt index e4aee737bd..a27eb131a7 100644 --- a/common/data/src/main/java/com/quran/data/model/bookmark/BookmarkData.kt +++ b/common/data/src/main/java/com/quran/data/model/bookmark/BookmarkData.kt @@ -7,8 +7,11 @@ data class BookmarkData @JvmOverloads constructor( val tags: List = emptyList(), val bookmarks: List = emptyList(), val recentPages: List = emptyList(), + /** The synced reading bookmarks (older versions read only these three slots). */ val readingBookmarks: List = emptyList(), - val pageType: String? = null + val pageType: String? = null, + /** The reading bookmarks kept on the device only, which older versions skip. */ + val localReadingBookmarks: List = emptyList(), ) { fun getCommaSeparatedNames() = @@ -25,7 +28,7 @@ data class BookmarkData @JvmOverloads constructor( .reduceOrNull { acc, bookmark -> "$acc$bookmark" } fun getReadingBookmarksByLine() = - readingBookmarks + (readingBookmarks + localReadingBookmarks) .map { "${it.getCommaSeparatedValues()} \n" } .reduceOrNull { acc, readingBookmark -> "$acc$readingBookmark" } } diff --git a/common/data/src/main/java/com/quran/data/model/bookmark/ReadingBookmarkPurpose.kt b/common/data/src/main/java/com/quran/data/model/bookmark/ReadingBookmarkPurpose.kt new file mode 100644 index 0000000000..736cc0838c --- /dev/null +++ b/common/data/src/main/java/com/quran/data/model/bookmark/ReadingBookmarkPurpose.kt @@ -0,0 +1,9 @@ +package com.quran.data.model.bookmark + +/** What a reading bookmark is used for; set in Settings. */ +enum class ReadingBookmarkPurpose { + /** Reading through the Quran: its cycles, pace and daily reminder are shown in Progress. */ + READING, + MEMORIZATION, + REVIEW, +} diff --git a/common/data/src/main/java/com/quran/data/model/bookmark/ReadingBookmarkSlotSetting.kt b/common/data/src/main/java/com/quran/data/model/bookmark/ReadingBookmarkSlotSetting.kt new file mode 100644 index 0000000000..d55be1d737 --- /dev/null +++ b/common/data/src/main/java/com/quran/data/model/bookmark/ReadingBookmarkSlotSetting.kt @@ -0,0 +1,19 @@ +package com.quran.data.model.bookmark + +/** + * How the user set up one reading bookmark slot. + * + * @param enabled whether the slot is offered (the three synced ones always are). + * @param targetDays days to read the Quran in, for a [ReadingBookmarkPurpose.READING] bookmark; 0 for + * no deadline. + */ +data class ReadingBookmarkSlotSetting( + val slot: ReadingBookmarkType, + val enabled: Boolean, + val purpose: ReadingBookmarkPurpose = ReadingBookmarkPurpose.READING, + val targetDays: Int = DEFAULT_TARGET_DAYS, +) { + companion object { + const val DEFAULT_TARGET_DAYS = 30 + } +} diff --git a/common/data/src/main/java/com/quran/data/model/bookmark/ReadingBookmarkType.kt b/common/data/src/main/java/com/quran/data/model/bookmark/ReadingBookmarkType.kt index 3ebbea4fa4..f09fc8387e 100644 --- a/common/data/src/main/java/com/quran/data/model/bookmark/ReadingBookmarkType.kt +++ b/common/data/src/main/java/com/quran/data/model/bookmark/ReadingBookmarkType.kt @@ -1,6 +1,16 @@ package com.quran.data.model.bookmark -/** Reading bookmark colors, in mobile-sync slot order (1, 2, and 3). */ -enum class ReadingBookmarkType { - TEAL, ORANGE, RED +import com.squareup.moshi.JsonClass + +/** + * Reading bookmark colors. The first three are mobile-sync's slots (1, 2, and 3, in that order) + * and sync; the others are kept on this device only, and are offered once turned on in Settings. + * + * Backups write the slot by its name. Moshi looks the constants up by name, so they must keep their + * names in minified builds: @JsonClass(generateAdapter = false) is what Moshi's R8 rules keep. + */ +@JsonClass(generateAdapter = false) +enum class ReadingBookmarkType(val synced: Boolean) { + TEAL(true), ORANGE(true), RED(true), + GREEN(false), BLUE(false), PURPLE(false), BROWN(false), GREY(false), } diff --git a/common/di/src/main/java/com/quran/mobile/di/RecordedSessionLauncher.kt b/common/di/src/main/java/com/quran/mobile/di/RecordedSessionLauncher.kt new file mode 100644 index 0000000000..3e93f40563 --- /dev/null +++ b/common/di/src/main/java/com/quran/mobile/di/RecordedSessionLauncher.kt @@ -0,0 +1,8 @@ +package com.quran.mobile.di + +import android.content.Context + +/** Opens a recorded Memorize session (Progress's Sessions plays it back there). */ +interface RecordedSessionLauncher { + fun open(context: Context, recordingId: String) +} diff --git a/common/pages/src/main/java/com/quran/page/common/data/AyahCoordinates.kt b/common/pages/src/main/java/com/quran/page/common/data/AyahCoordinates.kt index 5bcc72ca15..43c36c2dca 100644 --- a/common/pages/src/main/java/com/quran/page/common/data/AyahCoordinates.kt +++ b/common/pages/src/main/java/com/quran/page/common/data/AyahCoordinates.kt @@ -8,5 +8,9 @@ data class AyahCoordinates @JvmOverloads constructor( val glyphCoordinates: PageGlyphsCoords?, // one bounds per line of each ayah, aligned with the line val ayahLineCoordinates: Map> = emptyMap(), - val underlineRaiseRatio: Float = 0f + val underlineRaiseRatio: Float = 0f, + // word level glyphs derived from a GlyphTypeResolver when the database has no glyph types. Only + // used for word keys, hiding, and word taps during a recitation session, so existing ayah + // highlights and taps behave as before. + val wordGlyphCoordinates: PageGlyphsCoords? = null ) diff --git a/common/pages/src/main/java/com/quran/page/common/data/coordinates/GlyphTypeResolver.kt b/common/pages/src/main/java/com/quran/page/common/data/coordinates/GlyphTypeResolver.kt new file mode 100644 index 0000000000..56776bd2ae --- /dev/null +++ b/common/pages/src/main/java/com/quran/page/common/data/coordinates/GlyphTypeResolver.kt @@ -0,0 +1,26 @@ +package com.quran.page.common.data.coordinates + +/** + * Supplies glyph types for ayahinfo databases that only store glyph bounds (no glyph_type column), + * so features that work on individual words (e.g. hiding words while memorizing) can still find + * them. Types are returned per ayah as one character per glyph position (1-based position n is + * index n - 1): [WORD], [PAUSE], [SAJDAH], [HIZB] or [END]. + * + * Every page type draws the same text with its own font, so the types are worked out from the + * text together with the [glyphs] of the page type being shown. + */ +interface GlyphTypeResolver { + /** Types of an ayah's [glyphs] (in position order), or null if they can't be told apart. */ + fun glyphTypes(sura: Int, ayah: Int, glyphs: List): String? + + companion object { + const val WORD = 'w' + const val PAUSE = 'p' + const val SAJDAH = 's' + const val HIZB = 'h' + const val END = 'e' + } +} + +/** The size of a glyph's bounding box in an ayahinfo database. */ +data class GlyphSize(val width: Int, val height: Int) diff --git a/common/pages/src/main/java/com/quran/page/common/data/coordinates/PageGlyphsCoords.kt b/common/pages/src/main/java/com/quran/page/common/data/coordinates/PageGlyphsCoords.kt index 2d80bd7d3b..76adeb1929 100644 --- a/common/pages/src/main/java/com/quran/page/common/data/coordinates/PageGlyphsCoords.kt +++ b/common/pages/src/main/java/com/quran/page/common/data/coordinates/PageGlyphsCoords.kt @@ -3,6 +3,7 @@ package com.quran.page.common.data.coordinates import android.graphics.RectF import androidx.core.graphics.plus import com.quran.data.model.AyahGlyph +import com.quran.data.model.AyahGlyph.PauseGlyph import com.quran.data.model.AyahGlyph.WordGlyph import com.quran.data.model.AyahWord import com.quran.data.model.SuraAyah @@ -196,6 +197,54 @@ class PageGlyphsCoords(val page: Int, glyphCoords: List) { } } + // MASK BOUNDS (HIDING) + + private val expandedBoundsByGlyph: Map by lazy { + expandedGlyphs.associate { it.glyph to it.bounds } + } + + /** Whether the ayah ("[sura]:[ayah]") has glyphs on this page. */ + fun hasGlyphs(ayahKey: String): Boolean { + val split = ayahKey.split(":") + return glyphsByAyah.containsKey(SuraAyah(split[0].toInt(), split[1].toInt())) + } + + /** + * Gets bounds that fully cover the ink of a word, or of all the words of an ayah, so that it can + * be hidden. A word is covered together with the waqf marks that follow it; each glyph is + * expanded to the midpoints between it and its neighbours so that no part of it shows. Ayah end, + * hizb and sajdah markers are never covered, so the reader can still see where ayat are. + * + * @param key an ayah key "[sura]:[ayah]" or word key "[sura]:[ayah]:[word]". + * @return one rectangle per line, or null if the ayah or word isn't on this page. + */ + fun getMaskBounds(key: String): List? { + val split = key.split(":") + val ayah = SuraAyah(split[0].toInt(), split[1].toInt()) + val glyphs = glyphsByAyah[ayah] ?: return null + val masked = when (split.size) { + 2 -> glyphs.filter { it.glyph is WordGlyph || it.glyph is PauseGlyph } + 3 -> wordWithTrailingPauses(glyphs, split[2].toInt()) + else -> throw IllegalArgumentException("invalid key: $key, expecting _:_ or _:_:_") + } + if (masked.isEmpty()) return null + return masked + .groupBy { it.line } + .values + .map { lineGlyphs -> + lineGlyphs.fold(RectF()) { bounds, glyph -> + bounds + (expandedBoundsByGlyph[glyph.glyph] ?: glyph.bounds) + } + } + } + + private fun wordWithTrailingPauses(glyphs: List, wordPosition: Int): List { + val index = glyphs.indexOfFirst { it.glyph is WordGlyph && it.glyph.wordPosition == wordPosition } + if (index < 0) return emptyList() + val pauses = glyphs.drop(index + 1).takeWhile { it.glyph is PauseGlyph } + return listOf(glyphs[index]) + pauses + } + // GLYPH BOUNDS (CLICKS) fun getLineAtPoint(x: Float, y: Float): Int? { diff --git a/common/progress/build.gradle.kts b/common/progress/build.gradle.kts new file mode 100644 index 0000000000..5541225748 --- /dev/null +++ b/common/progress/build.gradle.kts @@ -0,0 +1,40 @@ +plugins { + id("quran.android.library.android") + alias(libs.plugins.sqldelight) + alias(libs.plugins.metro) +} + +android.namespace = "com.quran.mobile.progress" + +sqldelight { + databases { + create("ProgressDatabase") { + packageName.set("com.quran.mobile.progress.db") + schemaOutputDirectory.set(file("src/main/sqldelight/databases")) + verifyMigrations.set(true) + } + } +} + +dependencies { + implementation(project(":common:di")) + implementation(project(":common:data")) + + // coroutines + implementation(libs.kotlinx.coroutines.core) + implementation(libs.kotlinx.coroutines.android) + implementation(libs.androidx.core.ktx) + + // sqldelight + implementation(libs.sqldelight.android.driver) + implementation(libs.sqldelight.coroutines.extensions) + + // testing + testImplementation(project(":pages:data:madani")) + testImplementation(project(":pages:data:warsh")) + testImplementation(libs.junit) + testImplementation(libs.truth) + testImplementation(libs.kotlinx.coroutines.test) + testImplementation(libs.turbine) + testImplementation(libs.sqldelight.sqlite.driver) +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/ProgressPreferences.kt b/common/progress/src/main/java/com/quran/mobile/progress/ProgressPreferences.kt new file mode 100644 index 0000000000..b53d1d73e2 --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/ProgressPreferences.kt @@ -0,0 +1,65 @@ +package com.quran.mobile.progress + +import android.content.Context +import android.content.pm.ApplicationInfo +import androidx.core.content.edit +import com.quran.data.di.AppScope +import com.quran.mobile.di.qualifier.ApplicationContext +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow + +/** Progress settings. Kept on the device. */ +@SingleIn(AppScope::class) +class ProgressPreferences @Inject constructor(@param:ApplicationContext private val context: Context) { + private val prefs = context.getSharedPreferences(NAME, Context.MODE_PRIVATE) + private val _changes = MutableStateFlow(0) + + /** Bumps on every change, for screens that show settings. */ + val changes: Flow = _changes.asStateFlow() + + val debuggable: Boolean + get() = context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0 + + /** The daily reminder to finish a reading cycle in time. */ + var reminder: Boolean + get() = prefs.getBoolean(KEY_REMINDER, true) + set(value) = put { putBoolean(KEY_REMINDER, value) } + + /** When the reminder comes, in minutes after local midnight. */ + var reminderMinute: Int + get() = prefs.getInt(KEY_REMINDER_MINUTE, DEFAULT_REMINDER_MINUTE) + set(value) = put { putInt(KEY_REMINDER_MINUTE, value.coerceIn(0, 24 * 60 - 1)) } + + /** The local day the reminder last came on, so it comes at most once a day. */ + var lastReminderDay: Long + get() = prefs.getLong(KEY_LAST_REMINDER_DAY, -1L) + set(value) = put { putLong(KEY_LAST_REMINDER_DAY, value) } + + /** Whether Memorize, Recitation and Salah sessions keep their results here. */ + var sessionLog: Boolean + get() = prefs.getBoolean(KEY_SESSION_LOG, true) + set(value) = put { putBoolean(KEY_SESSION_LOG, value) } + + /** Debuggable builds only: days the progress clock is moved by. */ + var debugDayOffset: Int + get() = if (debuggable) prefs.getInt(KEY_DEBUG_DAY_OFFSET, 0) else 0 + set(value) = put { putInt(KEY_DEBUG_DAY_OFFSET, value) } + + private inline fun put(crossinline block: android.content.SharedPreferences.Editor.() -> Unit) { + prefs.edit { block() } + _changes.value += 1 + } + + companion object { + private const val NAME = "progress" + private const val KEY_REMINDER = "reminder" + private const val KEY_REMINDER_MINUTE = "reminder_minute" + private const val KEY_LAST_REMINDER_DAY = "last_reminder_day" + private const val KEY_SESSION_LOG = "session_log" + private const val KEY_DEBUG_DAY_OFFSET = "debug_day_offset" + const val DEFAULT_REMINDER_MINUTE = 20 * 60 + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/cycle/CycleDetector.kt b/common/progress/src/main/java/com/quran/mobile/progress/cycle/CycleDetector.kt new file mode 100644 index 0000000000..6928e60881 --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/cycle/CycleDetector.kt @@ -0,0 +1,81 @@ +package com.quran.mobile.progress.cycle + +import com.quran.mobile.progress.log.BookmarkPosition +import com.quran.mobile.progress.log.MoveKind +import com.quran.mobile.progress.log.RecordedMove + +/** + * One reading of the Quran by a reading bookmark, from Al-Fatiha to An-Nas. + * + * @param partial whether it started before Progress kept track, so its start isn't known. + * @param endMs when it ended, or null while it is open. + * @param wrapped whether it ended with the bookmark going from the last suras back to Al-Fatiha + * (rather than a new cycle started by hand). + */ +data class Cycle( + val startMs: Long, + val startDay: Long, + val partial: Boolean, + val endMs: Long? = null, + val endDay: Long? = null, + val wrapped: Boolean = false, +) { + val isOpen: Boolean get() = endMs == null +} + +/** Works out a bookmark's cycles from its history; a new one starts when it wraps or by hand. */ +object CycleDetector { + /** A wrap undone this soon (e.g. with the reader's Undo) wasn't one. */ + const val UNDO_MS = 60_000L + + /** Juz 'Amma, where a reading ends. */ + fun isEndZone(position: BookmarkPosition): Boolean = position.sura >= 78 + + /** Al-Fatiha or the first page of Al-Baqara, where a reading starts. */ + fun isStartZone(position: BookmarkPosition): Boolean = + position.sura == 1 || (position.sura == 2 && position.ayah <= 5) + + /** Whether the move at [index] goes from the end back to the start and isn't undone right after. */ + fun isWrap(moves: List, index: Int, previous: BookmarkPosition?): Boolean { + val move = moves[index] + val position = move.position ?: return false + if (move.kind != MoveKind.MOVE || previous == null) return false + if (!isEndZone(previous) || !isStartZone(position)) return false + val next = moves.drop(index + 1).firstOrNull { it.position != null } ?: return true + val undone = next.kind == MoveKind.MOVE && next.atMs - move.atMs <= UNDO_MS && isEndZone(next.position!!) + return !undone + } + + fun cycles(moves: List): List { + val cycles = mutableListOf() + var open: Cycle? = null + var previous: BookmarkPosition? = null + moves.forEachIndexed { index, move -> + when (move.kind) { + MoveKind.CYCLE_MARK -> { + open?.let { cycles += it.copy(endMs = move.atMs, endDay = move.day) } + open = Cycle(move.atMs, move.day, partial = false) + } + MoveKind.BASELINE -> { + if (open == null) { + open = Cycle(move.atMs, move.day, partial = !isStartZone(move.position!!)) + } + previous = move.position + } + MoveKind.MOVE -> { + val current = open + if (current == null) { + open = Cycle(move.atMs, move.day, partial = true) + } else if (isWrap(moves, index, previous)) { + cycles += current.copy(endMs = move.atMs, endDay = move.day, wrapped = true) + open = Cycle(move.atMs, move.day, partial = false) + } + previous = move.position + } + MoveKind.CLEAR -> Unit + } + } + open?.let { cycles += it } + return cycles + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/cycle/DailyProgress.kt b/common/progress/src/main/java/com/quran/mobile/progress/cycle/DailyProgress.kt new file mode 100644 index 0000000000..f04d89e177 --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/cycle/DailyProgress.kt @@ -0,0 +1,74 @@ +package com.quran.mobile.progress.cycle + +import com.quran.mobile.progress.log.BookmarkPosition +import com.quran.mobile.progress.log.MoveKind +import com.quran.mobile.progress.log.RecordedMove + +/** How far a bookmark moved forward each day. */ +object DailyProgress { + + /** + * Pages the bookmark moved forward on each local day of [cycle], from its history [moves]. + * + * Only the net move of each day counts (going back and forward again counts once), and never + * below 0. A BASELINE (a change of page type) starts measuring again from where it is. A cycle + * that ended with a wrap counts the pages to the end of the Quran on the day it wrapped. + * + * @param pageOf a position's page in the page type being shown. + * @param firstPage the first page of the Quran in it, where a cycle that wrapped starts. + * @param lastPage its last page. + */ + fun pagesPerDay( + cycle: Cycle, + moves: List, + pageOf: (BookmarkPosition) -> Int, + firstPage: Int, + lastPage: Int, + ): Map { + val pages = LinkedHashMap() + // where the bookmark was at the cycle's start + var start: Int? = if (cycle.partial) null else firstPage + var end: Int? = start + var day = cycle.startDay + fun close() { + val from = start ?: return + val to = end ?: return + pages[day] = (pages[day] ?: 0) + (to - from).coerceAtLeast(0) + } + for (move in moves) { + if (move.atMs < cycle.startMs) continue + val ended = cycle.endMs + if (ended != null && move.atMs >= ended) break + if (move.day != day) { + close() + day = move.day + start = end + } + val position = move.position ?: continue + val page = pageOf(position) + when (move.kind) { + MoveKind.BASELINE -> { + close() + start = page + end = page + } + MoveKind.MOVE -> { + if (start == null) start = page + end = page + } + else -> Unit + } + } + if (cycle.wrapped) { + // the reading went on to the end before the bookmark went back to the start + if (cycle.endDay != day) { + close() + day = cycle.endDay!! + start = end + } + end = lastPage + 1 + } + close() + return pages + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/cycle/Pace.kt b/common/progress/src/main/java/com/quran/mobile/progress/cycle/Pace.kt new file mode 100644 index 0000000000..57dc6adddd --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/cycle/Pace.kt @@ -0,0 +1,62 @@ +package com.quran.mobile.progress.cycle + +import kotlin.math.ceil + +/** + * Where an open cycle stands against its deadline. + * + * @param dayN today's day of the cycle (1 on the day it started). + * @param pagesDone pages before the bookmark's page. + * @param expectedByToday pages a steady pace has read by the end of today. + * @param ahead pages ahead of that pace (negative when behind). + * @param perDayNeeded pages a day to finish by [finishByDay], counting today. + * @param projectedFinishDay when it finishes at the pace so far, or null before any progress. + * @param finishByDay the last day to finish on. + */ +data class Pace( + val dayN: Int, + val targetDays: Int, + val pagesDone: Int, + val totalPages: Int, + val expectedByToday: Int, + val ahead: Int, + val perDayNeeded: Int, + val projectedFinishDay: Long?, + val finishByDay: Long, +) { + val remaining: Int get() = totalPages - pagesDone + val overdue: Boolean get() = dayN > targetDays +} + +object PaceMath { + /** + * The pace of a cycle that started on [startDay] with its bookmark now on [page]. + * + * @param firstPage the first page of the Quran in the page type shown (pages before it are skipped). + * @param totalPages its pages, not counting skipped ones. + */ + fun pace(startDay: Long, today: Long, page: Int, firstPage: Int, totalPages: Int, targetDays: Int): Pace { + val dayN = (today - startDay + 1).toInt().coerceAtLeast(1) + val done = (page - firstPage).coerceIn(0, totalPages) + val expected = ceil(totalPages.toDouble() * dayN.coerceAtMost(targetDays) / targetDays).toInt() + val daysLeft = (targetDays - dayN + 1).coerceAtLeast(1) + val remaining = totalPages - done + val perDay = ceil(remaining.toDouble() / daysLeft).toInt() + val projected = when { + remaining == 0 -> today + done == 0 -> null + else -> today + ceil(remaining / (done.toDouble() / dayN)).toLong() + } + return Pace( + dayN = dayN, + targetDays = targetDays, + pagesDone = done, + totalPages = totalPages, + expectedByToday = expected, + ahead = done - expected, + perDayNeeded = perDay, + projectedFinishDay = projected, + finishByDay = startDay + targetDays - 1, + ) + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/di/ProgressDataModule.kt b/common/progress/src/main/java/com/quran/mobile/progress/di/ProgressDataModule.kt new file mode 100644 index 0000000000..9fc0ca27ce --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/di/ProgressDataModule.kt @@ -0,0 +1,23 @@ +package com.quran.mobile.progress.di + +import android.content.Context +import app.cash.sqldelight.driver.android.AndroidSqliteDriver +import com.quran.data.di.AppScope +import com.quran.mobile.di.qualifier.ApplicationContext +import com.quran.mobile.progress.db.ProgressDatabase +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.Provides +import dev.zacsweers.metro.SingleIn + +@BindingContainer +@ContributesTo(AppScope::class) +class ProgressDataModule { + + @SingleIn(AppScope::class) + @Provides + fun provideProgressDatabase(@ApplicationContext context: Context): ProgressDatabase { + val driver = AndroidSqliteDriver(schema = ProgressDatabase.Schema, context = context, name = "progress.db") + return ProgressDatabase(driver) + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/history/DebugHistory.kt b/common/progress/src/main/java/com/quran/mobile/progress/history/DebugHistory.kt new file mode 100644 index 0000000000..b821a7d5c9 --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/history/DebugHistory.kt @@ -0,0 +1,55 @@ +package com.quran.mobile.progress.history + +import com.quran.data.core.QuranInfo +import com.quran.data.di.AppScope +import com.quran.mobile.progress.db.ProgressDatabase +import com.quran.mobile.progress.log.MoveKind +import com.quran.mobile.progress.time.LocalDays +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.util.TimeZone + +/** Debuggable builds only: fills in days of reading, to try Progress out without waiting for them. */ +@SingleIn(AppScope::class) +class DebugHistory @Inject constructor(private val database: ProgressDatabase) { + + /** + * Starts a cycle of [slot] at Al-Fatiha [pages] days before [today], and for each day after moves + * it on by that day's pages, with that day's minutes of reading credited to it. Returns the page + * it ends on. + */ + suspend fun seed( + slot: String, + today: Long, + zone: TimeZone, + quranInfo: QuranInfo, + pageType: String, + pages: List, + minutes: List, + ): Int = withContext(Dispatchers.IO) { + val first = today - pages.size + 1 + var page = 1 + quranInfo.skip + database.transaction { + val moves = database.bookmarkMoveQueries + val start = LocalDays.timeOnDay(first, 7 * 60, zone) + moves.insertMove(slot, start, first, MoveKind.BASELINE.name, page.toLong(), pageType, 1L, 1L) + pages.forEachIndexed { index, count -> + val day = first + index + val readAt = LocalDays.timeOnDay(day, 20 * 60, zone) + val movedAt = LocalDays.timeOnDay(day, 21 * 60, zone) + if (minutes[index] > 0) { + database.readingTimeQueries.insertTime(day, readAt, pageType, page.toLong(), minutes[index] * 60_000L, 1L) + } + if (count > 0) { + page = (page + count).coerceAtMost(quranInfo.numberOfPages) + val bounds = quranInfo.getPageBounds(page) + moves.insertMove(slot, movedAt, day, MoveKind.MOVE.name, page.toLong(), pageType, bounds[0].toLong(), bounds[1].toLong()) + database.readingTimeQueries.creditUpTo(slot, movedAt) + } + } + } + page + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/history/ProgressHistory.kt b/common/progress/src/main/java/com/quran/mobile/progress/history/ProgressHistory.kt new file mode 100644 index 0000000000..029ae6ae89 --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/history/ProgressHistory.kt @@ -0,0 +1,91 @@ +package com.quran.mobile.progress.history + +import app.cash.sqldelight.coroutines.asFlow +import app.cash.sqldelight.coroutines.mapToList +import com.quran.data.di.AppScope +import com.quran.mobile.progress.db.ProgressDatabase +import com.quran.mobile.progress.log.RecordedMove +import com.quran.mobile.progress.log.toRecorded +import com.quran.mobile.progress.session.AyahResult +import com.quran.mobile.progress.session.SessionRecord +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.withContext + +/** + * Reading time on one local day, credited to [slot] by its move at [creditedAt] (both null until a + * bookmark moves). + */ +data class DayMinutes(val slot: String?, val day: Long, val ms: Long, val creditedAt: Long? = null) + +/** A session from the log, with the local day it started on. */ +data class LoggedSession(val day: Long, val record: SessionRecord) + +/** What Progress has kept, as it changes. */ +@SingleIn(AppScope::class) +class ProgressHistory @Inject constructor(private val database: ProgressDatabase) { + + /** Every bookmark's history, by slot name, oldest first. */ + fun moves(): Flow>> = + database.bookmarkMoveQueries.allMoves().asFlow().mapToList(Dispatchers.IO) + .map { rows -> rows.groupBy({ it.slot }, { it.toRecorded() }) } + + fun minutes(): Flow> = + database.readingTimeQueries.minutesBySlotAndDay().asFlow().mapToList(Dispatchers.IO) + .map { rows -> rows.map { DayMinutes(it.slot, it.local_day, it.ms ?: 0L, it.credited_at) } } + + fun sessions(): Flow> = combine( + database.memorizeSessionQueries.sessions().asFlow().mapToList(Dispatchers.IO), + database.memorizeSessionQueries.sessionAyahs().asFlow().mapToList(Dispatchers.IO), + ) { sessions, ayahs -> + val bySession = ayahs.groupBy { it.session_id } + sessions.map { row -> + LoggedSession( + day = row.local_day, + record = SessionRecord( + id = row.id, + mode = row.mode, + startedAtMs = row.started_at_ms, + endedAtMs = row.ended_at_ms, + listenedMs = row.listened_ms, + startSura = row.start_sura.toInt(), + startAyah = row.start_ayah.toInt(), + endSura = row.end_sura.toInt(), + endAyah = row.end_ayah.toInt(), + words = row.words.toInt(), + recited = row.recited.toInt(), + hinted = row.hinted.toInt(), + missed = row.missed.toInt(), + mistakes = row.mistakes.toInt(), + finished = row.finished != 0L, + recordingId = row.recording_id, + ayahs = bySession[row.id].orEmpty().map { + AyahResult( + sura = it.sura.toInt(), + ayah = it.ayah.toInt(), + ayahWords = it.ayah_words.toInt(), + words = it.words.toInt(), + hinted = it.hinted.toInt(), + missed = it.missed.toInt(), + mistakes = it.mistakes.toInt(), + ) + }, + ), + ) + } + } + + /** Forgets everything Progress kept: bookmark moves, reading time and sessions. */ + suspend fun clear() = withContext(Dispatchers.IO) { + database.transaction { + database.bookmarkMoveQueries.deleteAllMoves() + database.readingTimeQueries.deleteAllTime() + database.memorizeSessionQueries.deleteAllSessionAyahs() + database.memorizeSessionQueries.deleteAllSessions() + } + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/log/BookmarkMoveRecorder.kt b/common/progress/src/main/java/com/quran/mobile/progress/log/BookmarkMoveRecorder.kt new file mode 100644 index 0000000000..aeb247377c --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/log/BookmarkMoveRecorder.kt @@ -0,0 +1,146 @@ +package com.quran.mobile.progress.log + +import com.quran.data.core.QuranInfo +import com.quran.data.dao.ReadingBookmarksDao +import com.quran.data.dao.Settings +import com.quran.data.di.AppCoroutineScope +import com.quran.data.di.AppScope +import com.quran.data.model.bookmark.AyahReadingBookmark +import com.quran.data.model.bookmark.EmptyReadingBookmark +import com.quran.data.model.bookmark.PageReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmark +import com.quran.mobile.progress.db.Bookmark_move +import com.quran.mobile.progress.db.ProgressDatabase +import com.quran.mobile.progress.time.ProgressClock +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.firstOrNull +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext + +/** + * Keeps the history of every reading bookmark's position (see BookmarkMove.sq), whoever moves it: + * the reader, a backup, or sync from another device (also while the app wasn't running: each + * position is compared with the last one stored, not with the last one seen). A move also credits + * the reading time not yet credited to that bookmark. + */ +@SingleIn(AppScope::class) +class BookmarkMoveRecorder @Inject constructor( + private val readingBookmarksDao: ReadingBookmarksDao, + private val settings: Settings, + private val quranInfoProvider: () -> QuranInfo, + private val database: ProgressDatabase, + private val clock: ProgressClock, + private val scope: AppCoroutineScope, +) { + private val mutex = Mutex() + private var job: Job? = null + + fun start() { + if (job != null) return + job = scope.launch { + while (isActive) { + try { + readingBookmarksDao.readingBookmarksFlow().collect { record(it) } + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + // e.g. before the first start chose a page type: try again once a setting changes + settings.preferencesFlow().firstOrNull() ?: break + } + } + } + } + + /** Stores what changed in [bookmarks] since the last rows. */ + suspend fun record(bookmarks: List): Unit = mutex.withLock { + val pageType = settings.pageType() + val quranInfo = quranInfoProvider() + withContext(Dispatchers.IO) { + val queries = database.bookmarkMoveQueries + queries.transaction { + for (bookmark in bookmarks) { + val slot = bookmark.slot.name + val position = bookmark.position(quranInfo, pageType) + val last = queries.lastMove(slot).executeAsOneOrNull() + val kind = when { + last == null -> if (position == null) null else MoveKind.BASELINE + position == null -> if (last.kind == MoveKind.CLEAR.name) null else MoveKind.CLEAR + last.kind == MoveKind.CLEAR.name || last.kind == MoveKind.CYCLE_MARK.name -> + when (val before = queries.lastPosition(slot).executeAsOneOrNull()) { + null -> MoveKind.BASELINE + else -> movedFrom(before.toPosition(), position) + } + else -> movedFrom(last.toPosition(), position) + } ?: continue + val atMs = atMs(bookmark, last?.at_ms) + queries.insertMove( + slot, atMs, clock.dayOf(atMs), kind.name, + position?.page?.toLong(), position?.pageType, position?.sura?.toLong(), position?.ayah?.toLong() + ) + if (kind == MoveKind.MOVE) { + database.readingTimeQueries.creditUpTo(slot, atMs) + } + } + } + } + } + + /** Starts a new cycle of [slot] now. */ + suspend fun markCycleStart(slot: String) { + mutex.withLock { + withContext(Dispatchers.IO) { + val now = clock.nowMs() + database.bookmarkMoveQueries.insertMove(slot, now, clock.dayOf(now), MoveKind.CYCLE_MARK.name, null, null, null, null) + } + } + } + + private fun movedFrom(before: BookmarkPosition?, now: BookmarkPosition): MoveKind? = when { + before == null -> MoveKind.BASELINE + // pages of another page type can't be compared: measure again from here + before.pageType != now.pageType -> MoveKind.BASELINE + before.page == now.page && before.sura == now.sura && before.ayah == now.ayah -> null + else -> MoveKind.MOVE + } + + /** + * When the bookmark moved: its own time when that's after the last row (a move made on another + * device, or while the app was closed), but never in the future; now when the clock was moved. + */ + private fun atMs(bookmark: ReadingBookmark, lastAt: Long?): Long { + val now = clock.nowMs() + if (clock.isShifted()) return maxOf(now, lastAt ?: 0L) + val own = bookmark.timestamp.toEpochMilliseconds() + return own.coerceIn(lastAt ?: 0L, maxOf(now, lastAt ?: 0L)) + } + + private fun Bookmark_move.toPosition(): BookmarkPosition? { + val page = page ?: return null + return BookmarkPosition(page.toInt(), page_type.orEmpty(), sura?.toInt() ?: 0, ayah?.toInt() ?: 0) + } +} + +/** Where [this] is in [pageType] (whose [quranInfo] is given), or null when it isn't placed. */ +fun ReadingBookmark.position(quranInfo: QuranInfo, pageType: String): BookmarkPosition? = when (this) { + is PageReadingBookmark -> { + val bounds = quranInfo.getPageBounds(page) + BookmarkPosition(page, pageType, bounds[0], bounds[1]) + } + is AyahReadingBookmark -> BookmarkPosition(quranInfo.getPageFromSuraAyah(sura, ayah), pageType, sura, ayah) + is EmptyReadingBookmark -> null +} + +/** This row of the history, as a [RecordedMove]. */ +fun Bookmark_move.toRecorded(): RecordedMove = RecordedMove( + atMs = at_ms, + day = local_day, + kind = MoveKind.valueOf(kind), + position = page?.let { BookmarkPosition(it.toInt(), page_type.orEmpty(), sura?.toInt() ?: 0, ayah?.toInt() ?: 0) }, +) diff --git a/common/progress/src/main/java/com/quran/mobile/progress/log/RecordedMove.kt b/common/progress/src/main/java/com/quran/mobile/progress/log/RecordedMove.kt new file mode 100644 index 0000000000..4c962591d6 --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/log/RecordedMove.kt @@ -0,0 +1,16 @@ +package com.quran.mobile.progress.log + +/** Where a reading bookmark is: its page in [pageType], and the first ayah it marks. */ +data class BookmarkPosition(val page: Int, val pageType: String, val sura: Int, val ayah: Int) + +enum class MoveKind { + /** Where the bookmark was first seen, or seen again in another page type: not a move. */ + BASELINE, + MOVE, + CLEAR, + /** The user started a new cycle by hand. */ + CYCLE_MARK, +} + +/** One row of the bookmark's history (see BookmarkMove.sq). [position] is null for CLEAR and CYCLE_MARK. */ +data class RecordedMove(val atMs: Long, val day: Long, val kind: MoveKind, val position: BookmarkPosition?) diff --git a/common/progress/src/main/java/com/quran/mobile/progress/reading/ReaderPresence.kt b/common/progress/src/main/java/com/quran/mobile/progress/reading/ReaderPresence.kt new file mode 100644 index 0000000000..e9a68b3310 --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/reading/ReaderPresence.kt @@ -0,0 +1,11 @@ +package com.quran.mobile.progress.reading + +import com.quran.data.di.AppScope +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn + +/** Whether the reader is open right now (the daily reminder stays quiet then). */ +@SingleIn(AppScope::class) +class ReaderPresence @Inject constructor() { + @Volatile var open: Boolean = false +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/reading/ReadingTimeAccumulator.kt b/common/progress/src/main/java/com/quran/mobile/progress/reading/ReadingTimeAccumulator.kt new file mode 100644 index 0000000000..6de2440264 --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/reading/ReadingTimeAccumulator.kt @@ -0,0 +1,104 @@ +package com.quran.mobile.progress.reading + +import com.quran.mobile.progress.time.LocalDays +import java.util.TimeZone + +/** Time on one page on one local day. [read] once the page was on screen long enough to count. */ +data class PageTime(val day: Long, val page: Int, val ms: Long, val read: Boolean) + +/** + * Adds up the time Quran pages are on screen while the reader is open, by wall time. + * + * Time counts only up to [idleMs] after the last page turn or touch (the reader keeps the screen + * on, so a page left open isn't being read). Two pages side by side share the time, so the day's + * total is the time spent. A page counts as read once it was on screen for [readMs]. If the clock + * goes back, that stretch is dropped; time is split at local midnight. + */ +class ReadingTimeAccumulator( + private val zone: () -> TimeZone, + private val idleMs: Long = IDLE_MS, + private val readMs: Long = READ_MS, +) { + private var open = false + private var pages: Set = emptySet() + private var lastAt = 0L + private var lastActivity = 0L + // continuous time each page shown now has been on screen + private val onScreen = HashMap() + private val pending = LinkedHashMap, PageTime>() + + fun onResume(now: Long, visible: Set) { + open = true + pages = visible + lastAt = now + lastActivity = now + onScreen.clear() + } + + fun onPages(now: Long, visible: Set) { + advance(now) + if (visible != pages) { + onScreen.keys.retainAll(visible) + pages = visible + } + lastActivity = now + } + + fun onInteraction(now: Long) { + advance(now) + lastActivity = now + } + + fun tick(now: Long) = advance(now) + + fun onPause(now: Long) { + advance(now) + open = false + onScreen.clear() + } + + /** What was counted since the last drain. */ + fun drain(): List { + val drained = pending.values.toList() + pending.clear() + return drained + } + + private fun advance(now: Long) { + if (!open || pages.isEmpty() || now <= lastAt) { + lastAt = now + return + } + var from = lastAt + val until = minOf(now, lastActivity + idleMs) + val tz = zone() + while (from < until) { + val day = LocalDays.epochDay(from, tz) + val to = minOf(until, LocalDays.startOfDayMs(day + 1, tz)) + add(day, to - from) + from = to + } + lastAt = now + } + + private fun add(day: Long, ms: Long) { + val share = ms / pages.size + for (page in pages) { + val seen = (onScreen[page] ?: 0L) + ms + onScreen[page] = seen + val key = day to page + val before = pending[key] + pending[key] = PageTime( + day = day, + page = page, + ms = (before?.ms ?: 0L) + share, + read = before?.read == true || seen >= readMs, + ) + } + } + + companion object { + const val IDLE_MS = 3 * 60_000L + const val READ_MS = 20_000L + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/reading/ReadingTimeLog.kt b/common/progress/src/main/java/com/quran/mobile/progress/reading/ReadingTimeLog.kt new file mode 100644 index 0000000000..34669a0223 --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/reading/ReadingTimeLog.kt @@ -0,0 +1,25 @@ +package com.quran.mobile.progress.reading + +import com.quran.data.di.AppScope +import com.quran.mobile.progress.db.ProgressDatabase +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** Stores reading time (see ReadingTime.sq). */ +@SingleIn(AppScope::class) +class ReadingTimeLog @Inject constructor(private val database: ProgressDatabase) { + + /** Adds [times] spent on [pageType]'s pages, in a stretch that ended at [atMs]. */ + suspend fun add(times: List, pageType: String, atMs: Long) { + if (times.isEmpty()) return + withContext(Dispatchers.IO) { + database.readingTimeQueries.transaction { + times.filter { it.ms > 0 }.forEach { + database.readingTimeQueries.insertTime(it.day, atMs, pageType, it.page.toLong(), it.ms, if (it.read) 1L else 0L) + } + } + } + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/reminder/ReminderDecision.kt b/common/progress/src/main/java/com/quran/mobile/progress/reminder/ReminderDecision.kt new file mode 100644 index 0000000000..8556ddbf30 --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/reminder/ReminderDecision.kt @@ -0,0 +1,77 @@ +package com.quran.mobile.progress.reminder + +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.mobile.progress.summary.BookmarkProgress +import com.quran.mobile.progress.time.LocalDays +import java.util.TimeZone + +/** What the daily reminder says, if anything. */ +sealed interface Reminder { + data object None : Reminder + + /** Nothing read today; [perDay] pages a day finish the cycle by [finishByDay]. */ + data class NotReadToday(val bookmark: BookmarkProgress, val perDay: Int, val finishByDay: Long) : Reminder + + /** [pages] behind a steady pace; [perDay] pages a day still finish it by [finishByDay]. */ + data class Behind(val bookmark: BookmarkProgress, val pages: Int, val perDay: Int, val finishByDay: Long) : Reminder + + /** Past the cycle's days, with [remaining] pages to go. */ + data class Overdue(val bookmark: BookmarkProgress, val remaining: Int) : Reminder +} + +/** + * The daily reminder to finish a reading cycle in its days: it comes once a day, at the time the + * user chose, for an open cycle of a reading bookmark with a deadline that is behind its pace or + * wasn't read yet that day. It stays quiet while the reader is open. + */ +object ReminderDecision { + + fun decide( + enabled: Boolean, + nowMs: Long, + zone: TimeZone, + reminderMinute: Int, + lastReminderDay: Long, + readerOpen: Boolean, + bookmarks: List, + ): Reminder { + val today = LocalDays.epochDay(nowMs, zone) + if (!enabled || readerOpen || lastReminderDay == today) return Reminder.None + if (nowMs < LocalDays.timeOnDay(today, reminderMinute, zone)) return Reminder.None + val due = bookmarks.mapNotNull { bookmark -> + val pace = bookmark.pace ?: return@mapNotNull null + val readToday = bookmark.today?.let { it.day == today && (it.pages > 0 || it.minutes > 0) } == true + when { + pace.remaining <= 0 -> null + pace.overdue -> Reminder.Overdue(bookmark, pace.remaining) + pace.ahead < 0 -> Reminder.Behind(bookmark, -pace.ahead, pace.perDayNeeded, pace.finishByDay) + !readToday -> Reminder.NotReadToday(bookmark, pace.perDayNeeded, pace.finishByDay) + else -> null + } + } + return due.minByOrNull { urgency(it) } ?: Reminder.None + } + + /** When the reminder should next be checked: today at [reminderMinute] if that's still ahead, else tomorrow. */ + fun nextReminderAt(nowMs: Long, zone: TimeZone, reminderMinute: Int): Long { + val today = LocalDays.epochDay(nowMs, zone) + val todayAt = LocalDays.timeOnDay(today, reminderMinute, zone) + return if (todayAt > nowMs) todayAt else LocalDays.timeOnDay(today + 1, reminderMinute, zone) + } + + // overdue first, then the furthest behind, then not read today (teal before the others) + private fun urgency(reminder: Reminder): Long = when (reminder) { + is Reminder.Overdue -> -1_000_000L - reminder.remaining + is Reminder.Behind -> -reminder.pages.toLong() + is Reminder.NotReadToday -> reminder.bookmark.slot.ordinal.toLong() + Reminder.None -> Long.MAX_VALUE + } + + /** The slot a reminder is about. */ + fun Reminder.slot(): ReadingBookmarkType? = when (this) { + is Reminder.Overdue -> bookmark.slot + is Reminder.Behind -> bookmark.slot + is Reminder.NotReadToday -> bookmark.slot + Reminder.None -> null + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/session/SessionLog.kt b/common/progress/src/main/java/com/quran/mobile/progress/session/SessionLog.kt new file mode 100644 index 0000000000..4c897f6f1a --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/session/SessionLog.kt @@ -0,0 +1,90 @@ +package com.quran.mobile.progress.session + +import com.quran.data.di.AppScope +import com.quran.mobile.progress.ProgressPreferences +import com.quran.mobile.progress.db.ProgressDatabase +import com.quran.mobile.progress.time.ProgressClock +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** Counts for one ayah of a session: of its [ayahWords] words, the session went through [words]. */ +data class AyahResult( + val sura: Int, + val ayah: Int, + val ayahWords: Int, + val words: Int, + val hinted: Int, + val missed: Int, + val mistakes: Int, +) + +/** + * What one Memorize, Recitation or Salah session came to: counts only, no audio and no words heard. + * + * @param mode the session's mode's name (MEMORIZE, RECITE or SALAH). + * @param listenedMs audio the session heard. + * @param finished whether the passage was recited to its end. + */ +data class SessionRecord( + val id: String, + val mode: String, + val startedAtMs: Long, + val endedAtMs: Long, + val listenedMs: Long, + val startSura: Int, + val startAyah: Int, + val endSura: Int, + val endAyah: Int, + val words: Int, + val recited: Int, + val hinted: Int, + val missed: Int, + val mistakes: Int, + val finished: Boolean, + val recordingId: String?, + val ayahs: List, +) + +/** Keeps session results on the device, when the user lets it (see [ProgressPreferences.sessionLog]). */ +@SingleIn(AppScope::class) +class SessionLog @Inject constructor( + private val database: ProgressDatabase, + private val preferences: ProgressPreferences, + private val clock: ProgressClock, +) { + val enabled: Boolean get() = preferences.sessionLog + + suspend fun record(record: SessionRecord) { + if (!enabled) return + withContext(Dispatchers.IO) { + val queries = database.memorizeSessionQueries + // the session's day by the progress clock, which a debuggable build may move + val shift = clock.nowMs() - System.currentTimeMillis() + queries.transaction { + queries.insertSession( + record.id, record.mode, record.startedAtMs + shift, clock.dayOf(record.startedAtMs + shift), + record.endedAtMs + shift, record.listenedMs, record.startSura.toLong(), record.startAyah.toLong(), + record.endSura.toLong(), record.endAyah.toLong(), record.words.toLong(), record.recited.toLong(), + record.hinted.toLong(), record.missed.toLong(), record.mistakes.toLong(), if (record.finished) 1L else 0L, + record.recordingId, + ) + record.ayahs.forEach { + queries.insertSessionAyah( + record.id, it.sura.toLong(), it.ayah.toLong(), it.ayahWords.toLong(), it.words.toLong(), it.hinted.toLong(), + it.missed.toLong(), it.mistakes.toLong(), + ) + } + } + } + } + + /** Forgets every session. */ + suspend fun clear() = withContext(Dispatchers.IO) { + database.memorizeSessionQueries.transaction { + database.memorizeSessionQueries.deleteAllSessionAyahs() + database.memorizeSessionQueries.deleteAllSessions() + } + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/summary/BookmarkProgress.kt b/common/progress/src/main/java/com/quran/mobile/progress/summary/BookmarkProgress.kt new file mode 100644 index 0000000000..c308b4eaee --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/summary/BookmarkProgress.kt @@ -0,0 +1,81 @@ +package com.quran.mobile.progress.summary + +import com.quran.data.model.bookmark.ReadingBookmarkPurpose +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.mobile.progress.cycle.Cycle +import com.quran.mobile.progress.cycle.Pace +import com.quran.mobile.progress.log.BookmarkPosition + +/** One day of a bookmark's chart: pages it moved forward, and minutes of reading credited to it. */ +data class DayAmount(val day: Long, val pages: Int, val minutes: Int) + +/** A finished cycle: from [startDay] to [endDay], local days, both included, with [readingMs] read. */ +data class ClosedCycle(val startDay: Long, val endDay: Long, val readingMs: Long) { + val days: Int get() = (endDay - startDay + 1).toInt() +} + +/** + * Where one reading bookmark stands. + * + * @param position where it is now (in the page type shown), or null when it isn't placed. + * @param cycle the open cycle, once Progress has seen the bookmark. + * @param cycleStartPage where the open cycle started: the first page, or where Progress first saw + * the bookmark when it started before. + * @param pace against [targetDays], for a reading bookmark whose open cycle's start is known. + * @param firstDay day 1 of the chart: the cycle's start, or 29 days before today when the chart is + * just the last 30 days (no deadline, or a cycle that started before Progress kept track). + * @param chartDays the days the chart has room for, from [firstDay] (some may be still to come). + * @param days the chart's days up to today, oldest first. + * @param cycleReadingMs reading credited to it since the open cycle started. + * @param cyclePages pages it moved forward since then. + * @param lastCycle the last cycle it finished. + * @param moved whether it has moved since Progress kept track (else there is nothing to show yet). + */ +data class BookmarkProgress( + val slot: ReadingBookmarkType, + val name: String?, + val purpose: ReadingBookmarkPurpose, + val targetDays: Int, + val position: BookmarkPosition?, + val cycle: Cycle?, + val cycleStartPage: Int?, + val pace: Pace?, + val firstDay: Long, + val chartDays: Int, + val days: List, + val cycleReadingMs: Long, + val cyclePages: Int, + val lastCycle: ClosedCycle?, + val moved: Boolean, +) { + val today: DayAmount? get() = days.lastOrNull() +} + +/** Ayat held in one juz or sura: the last time each was memorized, all its words, no hint and none missed. */ +data class Held(val number: Int, val held: Int, val ayat: Int) + +/** One day of sessions of one mode. */ +data class SessionDay( + val day: Long, + val sessions: Int, + val words: Int, + val recited: Int, + val hinted: Int, + val missed: Int, + val mistakes: Int, +) { + /** Words recited without help, out of every word gone through, in percent. */ + val accuracy: Int get() = if (words == 0) 0 else (recited * 100 + words / 2) / words +} + +data class MemorizingProgress( + val juz: List, + /** Per juz (1 to 30), its suras (a sura split between two juz is in both, with its ayat there). */ + val suras: Map>, + /** Memorize sessions, the last 30 days (none for a day without one). */ + val days: List, + val firstDay: Long, + val hasData: Boolean, +) + +data class SalahProgress(val days: List, val firstDay: Long, val hasData: Boolean) diff --git a/common/progress/src/main/java/com/quran/mobile/progress/summary/ProgressCalculator.kt b/common/progress/src/main/java/com/quran/mobile/progress/summary/ProgressCalculator.kt new file mode 100644 index 0000000000..e3393165ea --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/summary/ProgressCalculator.kt @@ -0,0 +1,200 @@ +package com.quran.mobile.progress.summary + +import com.quran.data.core.QuranInfo +import com.quran.data.model.SuraAyah +import com.quran.data.model.bookmark.ReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmarkPurpose +import com.quran.data.model.bookmark.ReadingBookmarkSlotSetting +import com.quran.mobile.progress.cycle.Cycle +import com.quran.mobile.progress.cycle.CycleDetector +import com.quran.mobile.progress.cycle.DailyProgress +import com.quran.mobile.progress.cycle.PaceMath +import com.quran.mobile.progress.history.DayMinutes +import com.quran.mobile.progress.history.LoggedSession +import com.quran.mobile.progress.log.BookmarkPosition +import com.quran.mobile.progress.log.MoveKind +import com.quran.mobile.progress.log.RecordedMove +import com.quran.mobile.progress.log.position + +/** + * Works out what Progress shows from what it kept, in the page type shown ([quranInfo] is that + * page type's, [pageType] its name). + */ +class ProgressCalculator(private val quranInfo: QuranInfo, private val pageType: String) { + private val firstPage = 1 + quranInfo.skip + private val lastPage = quranInfo.numberOfPages + private val totalPages = quranInfo.numberOfPagesConsideringSkipped + + // where each juz starts, by sura and ayah (the same in every Hafs page type) + private val juzStarts: List = (0 until 30).map { juz -> + quranInfo.getQuarterByIndex(juz * 8).let { SuraAyah(it.sura, it.ayah) } + } + + fun juzOf(sura: Int, ayah: Int): Int = juzStarts.indexOfLast { it <= SuraAyah(sura, ayah) } + 1 + + /** A position's page in the page type shown. */ + fun pageOf(position: BookmarkPosition): Int = + if (position.pageType == pageType) position.page else quranInfo.getPageFromSuraAyah(position.sura, position.ayah) + + /** Where [page] is along the 30 juz, from 0 (the start of juz 1) to 30 (the end of juz 30). */ + fun juzPosition(page: Int): Float { + val juz = quranInfo.getJuzFromPage(page) + val start = quranInfo.getStartingPageForJuz(juz) + val end = if (juz == 30) lastPage + 1 else quranInfo.getStartingPageForJuz(juz + 1) + val span = (end - start).coerceAtLeast(1) + return (juz - 1) + ((page - start).toFloat() / span).coerceIn(0f, 1f) + } + + /** The pages of [juz] in the page type shown. */ + fun juzPages(juz: Int): IntRange { + val start = quranInfo.getStartingPageForJuz(juz) + val end = if (juz == 30) lastPage else quranInfo.getStartingPageForJuz(juz + 1) - 1 + return start..end.coerceAtLeast(start) + } + + fun bookmark( + bookmark: ReadingBookmark, + setting: ReadingBookmarkSlotSetting, + moves: List, + minutes: List, + today: Long, + ): BookmarkProgress { + val slot = bookmark.slot + val position = bookmark.position(quranInfo, pageType) + val reading = setting.purpose == ReadingBookmarkPurpose.READING + // a bookmark for something else than reading through has no cycles: one span since it was first seen + val cycles = if (reading) { + CycleDetector.cycles(moves) + } else { + moves.firstOrNull()?.let { listOf(Cycle(it.atMs, it.day, partial = true)) }.orEmpty() + } + val open = cycles.lastOrNull()?.takeIf { it.isOpen } + // the last cycle finished whose start is known + val closed = cycles.lastOrNull { !it.isOpen && !it.partial } + // reading credited to this bookmark: a move credits what was read before it, so a cycle has + // what its own moves credited (the wrap's move credits the end of the cycle it closes) + val credited = minutes.filter { it.slot == slot.name } + fun creditedIn(fromMs: Long, toMs: Long?) = + credited.filter { (it.creditedAt ?: 0L) > fromMs && (toMs == null || (it.creditedAt ?: 0L) <= toMs) } + + val pace = if (reading && open != null && !open.partial && setting.targetDays > 0 && position != null) { + PaceMath.pace(open.startDay, today, pageOf(position), firstPage, totalPages, setting.targetDays) + } else { + null + } + val firstDay: Long + val chartDays: Int + if (pace != null && open != null) { + firstDay = open.startDay + chartDays = maxOf(setting.targetDays, pace.dayN).coerceAtMost(MAX_CHART_DAYS) + } else { + firstDay = today - (RECENT_DAYS - 1) + chartDays = RECENT_DAYS + } + val pagesByDay = if (open != null) DailyProgress.pagesPerDay(open, moves, ::pageOf, firstPage, lastPage) else emptyMap() + val cycleCredit = open?.let { creditedIn(it.startMs, null) }.orEmpty() + // a cycle's chart shows its own reading; the last 30 days show all of it + val minutesByDay = (if (pace != null) cycleCredit else credited).groupBy({ it.day }, { it.ms }).mapValues { it.value.sum() } + val lastShown = minOf(today, firstDay + chartDays - 1) + val days = (firstDay..lastShown).map { day -> + DayAmount(day, pagesByDay[day] ?: 0, ((minutesByDay[day] ?: 0L) / 60_000L).toInt()) + } + val cycleReadingMs = cycleCredit.sumOf { it.ms } + val cyclePages = pace?.pagesDone ?: pagesByDay.values.sum() + val lastCycle = closed?.let { cycle -> + val reading = creditedIn(cycle.startMs, cycle.endMs) + // it ended when its last pages were read (the bookmark may go back to the start days later) + val lastMove = moves.lastOrNull { it.kind == MoveKind.MOVE && it.atMs > cycle.startMs && it.atMs < (cycle.endMs ?: 0L) } + val endDay = maxOf(lastMove?.day ?: cycle.startDay, reading.maxOfOrNull { it.day } ?: cycle.startDay) + .takeIf { cycle.wrapped } ?: (cycle.endDay ?: cycle.startDay) + ClosedCycle(cycle.startDay, endDay, reading.sumOf { it.ms }) + } + val cycleStartPage = open?.let { cycle -> + if (!cycle.partial) firstPage else moves.firstOrNull { it.atMs >= cycle.startMs && it.position != null }?.position?.let(::pageOf) + } + return BookmarkProgress( + slot = slot, + name = bookmark.name, + purpose = setting.purpose, + targetDays = setting.targetDays, + position = position, + cycle = open, + cycleStartPage = cycleStartPage, + pace = pace, + firstDay = firstDay, + chartDays = chartDays, + days = days, + cycleReadingMs = cycleReadingMs, + cyclePages = cyclePages, + lastCycle = lastCycle, + moved = moves.any { it.kind == MoveKind.MOVE }, + ) + } + + fun memorizing(sessions: List, today: Long): MemorizingProgress { + val memorize = sessions.filter { it.record.mode == MEMORIZE } + // the last time each ayah was gone through, in order + val last = HashMap() + memorize.sortedBy { it.record.startedAtMs }.forEach { session -> + session.record.ayahs.forEach { ayah -> + if (ayah.words >= ayah.ayahWords) { + last[SuraAyah(ayah.sura, ayah.ayah)] = ayah.hinted == 0 && ayah.missed == 0 + } + } + } + val juzAyat = IntArray(31) + val juzHeld = IntArray(31) + val suraAyat = HashMap, Int>() + val suraHeld = HashMap, Int>() + for (sura in 1..114) { + for (ayah in 1..quranInfo.getNumberOfAyahs(sura)) { + val juz = juzOf(sura, ayah) + val key = juz to sura + juzAyat[juz]++ + suraAyat[key] = (suraAyat[key] ?: 0) + 1 + if (last[SuraAyah(sura, ayah)] == true) { + juzHeld[juz]++ + suraHeld[key] = (suraHeld[key] ?: 0) + 1 + } + } + } + val firstDay = today - (RECENT_DAYS - 1) + return MemorizingProgress( + juz = (1..30).map { Held(it, juzHeld[it], juzAyat[it]) }, + suras = suraAyat.keys.groupBy({ it.first }, { key -> Held(key.second, suraHeld[key] ?: 0, suraAyat.getValue(key)) }) + .mapValues { (_, suras) -> suras.sortedBy { it.number } }, + days = sessionDays(memorize, firstDay, today), + firstDay = firstDay, + hasData = memorize.isNotEmpty(), + ) + } + + fun salah(sessions: List, today: Long): SalahProgress { + val salah = sessions.filter { it.record.mode == SALAH } + val firstDay = today - (RECENT_DAYS - 1) + return SalahProgress(sessionDays(salah, firstDay, today), firstDay, salah.isNotEmpty()) + } + + private fun sessionDays(sessions: List, firstDay: Long, today: Long): List { + val byDay = sessions.filter { it.day in firstDay..today }.groupBy { it.day } + return (firstDay..today).map { day -> + val ofDay = byDay[day].orEmpty().map { it.record } + SessionDay( + day = day, + sessions = ofDay.size, + words = ofDay.sumOf { it.words }, + recited = ofDay.sumOf { it.recited }, + hinted = ofDay.sumOf { it.hinted }, + missed = ofDay.sumOf { it.missed }, + mistakes = ofDay.sumOf { it.mistakes }, + ) + } + } + + companion object { + const val RECENT_DAYS = 30 + const val MAX_CHART_DAYS = 90 + const val MEMORIZE = "MEMORIZE" + const val SALAH = "SALAH" + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/time/LocalDays.kt b/common/progress/src/main/java/com/quran/mobile/progress/time/LocalDays.kt new file mode 100644 index 0000000000..c99855650b --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/time/LocalDays.kt @@ -0,0 +1,35 @@ +package com.quran.mobile.progress.time + +import java.util.Calendar +import java.util.TimeZone + +/** Local days as epoch days (days since 1970-01-01 in the given time zone), without java.time. */ +object LocalDays { + const val DAY_MS = 86_400_000L + + /** The local day [ms] falls on in [zone]. */ + fun epochDay(ms: Long, zone: TimeZone): Long = (ms + zone.getOffset(ms)).floorDiv(DAY_MS) + + /** When local [day] starts in [zone] (the first moment of it, if midnight is skipped by a clock change). */ + fun startOfDayMs(day: Long, zone: TimeZone): Long { + val utc = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { timeInMillis = day * DAY_MS } + val local = Calendar.getInstance(zone).apply { + clear() + set(utc.get(Calendar.YEAR), utc.get(Calendar.MONTH), utc.get(Calendar.DAY_OF_MONTH), 0, 0, 0) + } + return local.timeInMillis + } + + /** The time [minuteOfDay] minutes into local [day] in [zone]. */ + fun timeOnDay(day: Long, minuteOfDay: Int, zone: TimeZone): Long { + val utc = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { timeInMillis = day * DAY_MS } + val local = Calendar.getInstance(zone).apply { + clear() + set( + utc.get(Calendar.YEAR), utc.get(Calendar.MONTH), utc.get(Calendar.DAY_OF_MONTH), + minuteOfDay / 60, minuteOfDay % 60, 0 + ) + } + return local.timeInMillis + } +} diff --git a/common/progress/src/main/java/com/quran/mobile/progress/time/ProgressClock.kt b/common/progress/src/main/java/com/quran/mobile/progress/time/ProgressClock.kt new file mode 100644 index 0000000000..84905a0d3c --- /dev/null +++ b/common/progress/src/main/java/com/quran/mobile/progress/time/ProgressClock.kt @@ -0,0 +1,28 @@ +package com.quran.mobile.progress.time + +import com.quran.data.di.AppScope +import com.quran.mobile.progress.ProgressPreferences +import dev.zacsweers.metro.ContributesBinding +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import java.util.TimeZone + +/** The time progress is kept in. Debuggable builds may move it by whole days to try out the days ahead. */ +interface ProgressClock { + fun nowMs(): Long + fun zone(): TimeZone + + /** Whether the clock was moved, so the time things really happened doesn't apply. */ + fun isShifted(): Boolean = false + + fun today(): Long = LocalDays.epochDay(nowMs(), zone()) + fun dayOf(ms: Long): Long = LocalDays.epochDay(ms, zone()) +} + +@SingleIn(AppScope::class) +@ContributesBinding(AppScope::class) +class SystemProgressClock @Inject constructor(private val preferences: ProgressPreferences) : ProgressClock { + override fun nowMs(): Long = System.currentTimeMillis() + preferences.debugDayOffset * LocalDays.DAY_MS + override fun zone(): TimeZone = TimeZone.getDefault() + override fun isShifted(): Boolean = preferences.debugDayOffset != 0 +} diff --git a/common/progress/src/main/sqldelight/com/quran/mobile/progress/db/BookmarkMove.sq b/common/progress/src/main/sqldelight/com/quran/mobile/progress/db/BookmarkMove.sq new file mode 100644 index 0000000000..06d34e6b39 --- /dev/null +++ b/common/progress/src/main/sqldelight/com/quran/mobile/progress/db/BookmarkMove.sq @@ -0,0 +1,39 @@ +-- Every change seen in a reading bookmark's position, in the order it was seen. Cycles and the pages +-- read each day are worked out from these rows (see CycleDetector and DailyProgress). +CREATE TABLE bookmark_move ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + -- ReadingBookmarkType's name + slot TEXT NOT NULL, + -- wall time (ProgressClock) and its local day (epoch day in the device's time zone) + at_ms INTEGER NOT NULL, + local_day INTEGER NOT NULL, + -- BASELINE: where it was first seen, or seen in another page type (not a move); MOVE; CLEAR; + -- CYCLE_MARK: the user started a new cycle by hand + kind TEXT NOT NULL, + -- the position (none for CLEAR and CYCLE_MARK): its page in page_type, and its first ayah + page INTEGER, + page_type TEXT, + sura INTEGER, + ayah INTEGER +); + +CREATE INDEX bookmark_move_slot_at ON bookmark_move(slot, at_ms); + +insertMove: +INSERT INTO bookmark_move(slot, at_ms, local_day, kind, page, page_type, sura, ayah) +VALUES (?, ?, ?, ?, ?, ?, ?, ?); + +lastMove: +SELECT * FROM bookmark_move WHERE slot = ? ORDER BY at_ms DESC, id DESC LIMIT 1; + +lastPosition: +SELECT * FROM bookmark_move WHERE slot = ? AND kind IN ('BASELINE', 'MOVE') ORDER BY at_ms DESC, id DESC LIMIT 1; + +movesFor: +SELECT * FROM bookmark_move WHERE slot = ? ORDER BY at_ms, id; + +allMoves: +SELECT * FROM bookmark_move ORDER BY at_ms, id; + +deleteAllMoves: +DELETE FROM bookmark_move; diff --git a/common/progress/src/main/sqldelight/com/quran/mobile/progress/db/MemorizeSession.sq b/common/progress/src/main/sqldelight/com/quran/mobile/progress/db/MemorizeSession.sq new file mode 100644 index 0000000000..7658229760 --- /dev/null +++ b/common/progress/src/main/sqldelight/com/quran/mobile/progress/db/MemorizeSession.sq @@ -0,0 +1,64 @@ +-- What each Memorize, Recitation and Salah session came to (counts only: no audio, no words heard). +CREATE TABLE memorize_session ( + id TEXT PRIMARY KEY NOT NULL, + -- MEMORIZE, RECITE or SALAH + mode TEXT NOT NULL, + started_at_ms INTEGER NOT NULL, + local_day INTEGER NOT NULL, + ended_at_ms INTEGER NOT NULL, + -- audio the session heard + listened_ms INTEGER NOT NULL, + start_sura INTEGER NOT NULL, + start_ayah INTEGER NOT NULL, + end_sura INTEGER NOT NULL, + end_ayah INTEGER NOT NULL, + words INTEGER NOT NULL, + recited INTEGER NOT NULL, + hinted INTEGER NOT NULL, + missed INTEGER NOT NULL, + mistakes INTEGER NOT NULL, + -- 1 if the passage was recited to its end + finished INTEGER NOT NULL, + recording_id TEXT +); + +CREATE INDEX memorize_session_day ON memorize_session(local_day); + +CREATE TABLE memorize_session_ayah ( + session_id TEXT NOT NULL, + sura INTEGER NOT NULL, + ayah INTEGER NOT NULL, + -- the ayah's words, and those of them the session went through + ayah_words INTEGER NOT NULL, + words INTEGER NOT NULL, + hinted INTEGER NOT NULL, + missed INTEGER NOT NULL, + mistakes INTEGER NOT NULL, + PRIMARY KEY (session_id, sura, ayah) +); + +CREATE INDEX memorize_session_ayah_by_ayah ON memorize_session_ayah(sura, ayah); + +insertSession: +INSERT OR REPLACE INTO memorize_session( + id, mode, started_at_ms, local_day, ended_at_ms, listened_ms, start_sura, start_ayah, end_sura, end_ayah, + words, recited, hinted, missed, mistakes, finished, recording_id +) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); + +insertSessionAyah: +INSERT OR REPLACE INTO memorize_session_ayah(session_id, sura, ayah, ayah_words, words, hinted, missed, mistakes) +VALUES (?, ?, ?, ?, ?, ?, ?, ?); + +sessions: +SELECT * FROM memorize_session ORDER BY started_at_ms; + +sessionAyahs: +SELECT memorize_session_ayah.*, memorize_session.mode, memorize_session.started_at_ms +FROM memorize_session_ayah JOIN memorize_session ON memorize_session.id = memorize_session_ayah.session_id +ORDER BY memorize_session.started_at_ms; + +deleteAllSessionAyahs: +DELETE FROM memorize_session_ayah; + +deleteAllSessions: +DELETE FROM memorize_session; diff --git a/common/progress/src/main/sqldelight/com/quran/mobile/progress/db/ReadingTime.sq b/common/progress/src/main/sqldelight/com/quran/mobile/progress/db/ReadingTime.sq new file mode 100644 index 0000000000..e21e27d348 --- /dev/null +++ b/common/progress/src/main/sqldelight/com/quran/mobile/progress/db/ReadingTime.sq @@ -0,0 +1,36 @@ +-- Time spent with Quran pages open in the reader. Each row is one page's share of one stretch of +-- reading; the time is credited to the bookmark that moves next (slot is null until then). +CREATE TABLE reading_time ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + local_day INTEGER NOT NULL, + -- when the stretch ended (wall time, ProgressClock) + at_ms INTEGER NOT NULL, + page_type TEXT NOT NULL, + page INTEGER NOT NULL, + ms INTEGER NOT NULL, + -- 1 once the page had been on screen long enough to count as read + read INTEGER NOT NULL, + -- the bookmark it was credited to, and when (the time of that bookmark's move) + slot TEXT, + credited_at INTEGER +); + +CREATE INDEX reading_time_day ON reading_time(local_day); +CREATE INDEX reading_time_slot_at ON reading_time(slot, at_ms); + +insertTime: +INSERT INTO reading_time(local_day, at_ms, page_type, page, ms, read, slot, credited_at) +VALUES (?, ?, ?, ?, ?, ?, NULL, NULL); + +creditUpTo: +UPDATE reading_time SET slot = :slot, credited_at = :at WHERE slot IS NULL AND at_ms <= :at; + +minutesBySlotAndDay: +SELECT slot, local_day, credited_at, SUM(ms) AS ms FROM reading_time GROUP BY slot, local_day, credited_at; + +timeOnDays: +SELECT local_day, SUM(ms) AS ms, COUNT(DISTINCT CASE WHEN read = 1 THEN page_type || ':' || page END) AS pages +FROM reading_time WHERE local_day BETWEEN ? AND ? GROUP BY local_day; + +deleteAllTime: +DELETE FROM reading_time; diff --git a/common/progress/src/main/sqldelight/databases/1.db b/common/progress/src/main/sqldelight/databases/1.db new file mode 100644 index 0000000000..5378ee6617 Binary files /dev/null and b/common/progress/src/main/sqldelight/databases/1.db differ diff --git a/common/progress/src/test/kotlin/com/quran/mobile/progress/Moves.kt b/common/progress/src/test/kotlin/com/quran/mobile/progress/Moves.kt new file mode 100644 index 0000000000..003c4218ad --- /dev/null +++ b/common/progress/src/test/kotlin/com/quran/mobile/progress/Moves.kt @@ -0,0 +1,48 @@ +package com.quran.mobile.progress + +import com.quran.mobile.progress.log.BookmarkPosition +import com.quran.mobile.progress.log.MoveKind +import com.quran.mobile.progress.log.RecordedMove + +/** + * A bookmark's history for tests, in UTC days: `Moves.of { day(3) { move(262, 15, 1) } }`. Each day's + * rows start at 08:00, a minute apart unless [after] says otherwise. + */ +internal class Moves { + val rows = mutableListOf() + private var day = 0L + private var atMs = 0L + private var gapMs = 60_000L + + fun day(day: Long, block: Moves.() -> Unit) { + this.day = day + atMs = day * DAY + 8 * HOUR - 60_000L + block() + } + + /** The next row comes [seconds] after the last one. */ + fun after(seconds: Long) { + gapMs = seconds * 1000 + } + + fun baseline(page: Int, sura: Int, ayah: Int, pageType: String = "madani") = + add(MoveKind.BASELINE, BookmarkPosition(page, pageType, sura, ayah)) + + fun move(page: Int, sura: Int, ayah: Int, pageType: String = "madani") = + add(MoveKind.MOVE, BookmarkPosition(page, pageType, sura, ayah)) + + fun clear() = add(MoveKind.CLEAR, null) + fun mark() = add(MoveKind.CYCLE_MARK, null) + + private fun add(kind: MoveKind, position: BookmarkPosition?) { + atMs += gapMs + gapMs = 60_000L + rows += RecordedMove(atMs, day, kind, position) + } + + companion object { + const val HOUR = 3_600_000L + const val DAY = 24 * HOUR + fun of(block: Moves.() -> Unit): List = Moves().apply(block).rows + } +} diff --git a/common/progress/src/test/kotlin/com/quran/mobile/progress/cycle/CycleDetectorTest.kt b/common/progress/src/test/kotlin/com/quran/mobile/progress/cycle/CycleDetectorTest.kt new file mode 100644 index 0000000000..08829d675c --- /dev/null +++ b/common/progress/src/test/kotlin/com/quran/mobile/progress/cycle/CycleDetectorTest.kt @@ -0,0 +1,118 @@ +package com.quran.mobile.progress.cycle + +import com.google.common.truth.Truth.assertThat +import com.quran.mobile.progress.Moves +import org.junit.Test + +class CycleDetectorTest { + + @Test + fun anNasBackToAlFatihaClosesTheCycleAndStartsAnother() { + val moves = Moves.of { + day(1) { baseline(1, 1, 1) } + day(20) { move(604, 114, 1) } + day(21) { move(1, 1, 1) } + } + val cycles = CycleDetector.cycles(moves) + assertThat(cycles).hasSize(2) + assertThat(cycles[0].partial).isFalse() + assertThat(cycles[0].startDay).isEqualTo(1) + assertThat(cycles[0].endDay).isEqualTo(21) + assertThat(cycles[0].wrapped).isTrue() + assertThat(cycles[1].startDay).isEqualTo(21) + assertThat(cycles[1].isOpen).isTrue() + assertThat(cycles[1].partial).isFalse() + } + + @Test + fun anyWhereInJuzAmmaToTheFirstPageOfAlBaqaraIsAWrap() { + val moves = Moves.of { + day(1) { baseline(582, 78, 1) } + day(2) { move(2, 2, 1) } + } + val cycles = CycleDetector.cycles(moves) + assertThat(cycles).hasSize(2) + assertThat(cycles[0].partial).isTrue() + assertThat(cycles[1].startDay).isEqualTo(2) + } + + @Test + fun goingBackToAlFatihaFromJuz29IsNotAWrap() { + val moves = Moves.of { + day(1) { baseline(562, 67, 1) } + day(2) { move(1, 1, 1) } + } + assertThat(CycleDetector.cycles(moves)).hasSize(1) + } + + @Test + fun aWrapUndoneRightAfterIsNotOne() { + val moves = Moves.of { + day(1) { + baseline(600, 109, 1) + move(1, 1, 1) + after(10) + move(600, 109, 1) + } + } + assertThat(CycleDetector.cycles(moves)).hasSize(1) + } + + @Test + fun aWrapStillCountsWhenTheNextMoveComesLater() { + val moves = Moves.of { + day(1) { + baseline(600, 109, 1) + move(1, 1, 1) + after(120) + move(3, 2, 6) + } + } + assertThat(CycleDetector.cycles(moves)).hasSize(2) + } + + @Test + fun theFirstCycleSeenIsPartialUnlessItStartsAtTheStart() { + val partial = CycleDetector.cycles(Moves.of { day(1) { baseline(262, 15, 1) } }) + assertThat(partial.single().partial).isTrue() + val atStart = CycleDetector.cycles(Moves.of { day(1) { baseline(1, 1, 1) } }) + assertThat(atStart.single().partial).isFalse() + } + + @Test + fun aCycleStartedByHandEndsTheOpenOne() { + val moves = Moves.of { + day(1) { baseline(262, 15, 1) } + day(5) { mark() } + day(6) { move(270, 15, 50) } + } + val cycles = CycleDetector.cycles(moves) + assertThat(cycles).hasSize(2) + assertThat(cycles[0].endDay).isEqualTo(5) + assertThat(cycles[0].wrapped).isFalse() + assertThat(cycles[1].startDay).isEqualTo(5) + assertThat(cycles[1].partial).isFalse() + } + + @Test + fun aChangeOfPageTypeIsNotAMove() { + // Warsh numbers its pages differently; the end zone is by sura, so the wrap is still seen + val moves = Moves.of { + day(1) { baseline(600, 109, 1) } + day(2) { baseline(556, 109, 1, pageType = "warsh") } + day(3) { move(1, 1, 1, pageType = "warsh") } + } + assertThat(CycleDetector.cycles(moves)).hasSize(2) + } + + @Test + fun aClearDoesNotEndTheCycle() { + val moves = Moves.of { + day(1) { baseline(600, 109, 1) } + day(2) { clear() } + day(3) { move(1, 1, 1) } + } + // the bookmark went from the end to the start, with a clear in between + assertThat(CycleDetector.cycles(moves)).hasSize(2) + } +} diff --git a/common/progress/src/test/kotlin/com/quran/mobile/progress/cycle/DailyProgressTest.kt b/common/progress/src/test/kotlin/com/quran/mobile/progress/cycle/DailyProgressTest.kt new file mode 100644 index 0000000000..9f9fb16bef --- /dev/null +++ b/common/progress/src/test/kotlin/com/quran/mobile/progress/cycle/DailyProgressTest.kt @@ -0,0 +1,81 @@ +package com.quran.mobile.progress.cycle + +import com.google.common.truth.Truth.assertThat +import com.quran.data.core.QuranInfo +import com.quran.labs.androidquran.pages.data.madani.MadaniDataSource +import com.quran.mobile.progress.Moves +import com.quran.mobile.progress.log.BookmarkPosition +import org.junit.Test + +class DailyProgressTest { + private val quranInfo = QuranInfo(MadaniDataSource()) + private val pageOf: (BookmarkPosition) -> Int = { position -> + if (position.pageType == "madani") position.page else quranInfo.getPageFromSuraAyah(position.sura, position.ayah) + } + + private fun pages(moves: List, cycle: Int = 0): Map { + val cycles = CycleDetector.cycles(moves) + return DailyProgress.pagesPerDay(cycles[cycle], moves, pageOf, firstPage = 1, lastPage = 604) + } + + @Test + fun countsTheNetMoveOfEachDay() { + val moves = Moves.of { + day(1) { baseline(1, 1, 1) } + day(2) { + move(10, 2, 62) + move(5, 2, 30) + move(22, 2, 142) + } + day(4) { move(40, 3, 1) } + } + assertThat(pages(moves)).containsExactly(1L, 0, 2L, 21, 4L, 18) + } + + @Test + fun aMoveBackIsZeroNotNegative() { + val moves = Moves.of { + day(1) { baseline(50, 3, 75) } + day(2) { move(40, 3, 1) } + } + assertThat(pages(moves)[2L]).isEqualTo(0) + } + + @Test + fun theDayOfAWrapCountsThePagesToTheEndForTheOldCycleAndTheRestForTheNew() { + val moves = Moves.of { + day(1) { baseline(590, 87, 1) } + day(2) { + move(600, 109, 1) + move(2, 2, 1) + } + } + // 590 -> 600 -> the end (604 read): 15 pages; then 1 -> 2: 1 page + assertThat(pages(moves, 0)[2L]).isEqualTo(15) + assertThat(pages(moves, 1)).containsExactly(2L, 1) + } + + @Test + fun aChangeOfPageTypeMeasuresAgainFromThere() { + val moves = Moves.of { + day(1) { baseline(100, 5, 1) } + day(2) { + move(110, 5, 77) + baseline(120, 5, 77, pageType = "other") + move(125, 5, 100, pageType = "other") + } + } + // 10 pages in madani, then 5:77 to 5:100 in madani's pages + assertThat(pages(moves)[2L]).isEqualTo(10 + (quranInfo.getPageFromSuraAyah(5, 100) - quranInfo.getPageFromSuraAyah(5, 77))) + } + + @Test + fun aClearedBookmarkPlacedAgainCountsFromWhereItWas() { + val moves = Moves.of { + day(1) { baseline(100, 5, 1) } + day(2) { clear() } + day(3) { move(130, 6, 1) } + } + assertThat(pages(moves)[3L]).isEqualTo(30) + } +} diff --git a/common/progress/src/test/kotlin/com/quran/mobile/progress/cycle/PaceTest.kt b/common/progress/src/test/kotlin/com/quran/mobile/progress/cycle/PaceTest.kt new file mode 100644 index 0000000000..29ea33b613 --- /dev/null +++ b/common/progress/src/test/kotlin/com/quran/mobile/progress/cycle/PaceTest.kt @@ -0,0 +1,60 @@ +package com.quran.mobile.progress.cycle + +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +class PaceTest { + + @Test + fun dayTwelveOfThirtyAtPage262IsAheadOfThePace() { + val pace = PaceMath.pace(startDay = 100, today = 111, page = 262, firstPage = 1, totalPages = 604, targetDays = 30) + assertThat(pace.dayN).isEqualTo(12) + assertThat(pace.pagesDone).isEqualTo(261) + // 604 × 12 / 30 = 241.6 + assertThat(pace.expectedByToday).isEqualTo(242) + assertThat(pace.ahead).isEqualTo(19) + // 343 pages in 19 days, today included + assertThat(pace.perDayNeeded).isEqualTo(19) + assertThat(pace.finishByDay).isEqualTo(129) + // 261 pages in 12 days: 343 more take 16 days + assertThat(pace.projectedFinishDay).isEqualTo(111 + 16) + assertThat(pace.overdue).isFalse() + } + + @Test + fun behindThePace() { + val pace = PaceMath.pace(startDay = 0, today = 9, page = 101, firstPage = 1, totalPages = 604, targetDays = 30) + assertThat(pace.ahead).isEqualTo(100 - 202) + } + + @Test + fun nothingReadYetHasNoProjectedFinish() { + val pace = PaceMath.pace(startDay = 0, today = 0, page = 1, firstPage = 1, totalPages = 604, targetDays = 30) + assertThat(pace.dayN).isEqualTo(1) + assertThat(pace.projectedFinishDay).isNull() + assertThat(pace.perDayNeeded).isEqualTo(21) + } + + @Test + fun pastTheDeadlineIsOverdue() { + val pace = PaceMath.pace(startDay = 0, today = 31, page = 500, firstPage = 1, totalPages = 604, targetDays = 30) + assertThat(pace.overdue).isTrue() + assertThat(pace.expectedByToday).isEqualTo(604) + // the rest is due now + assertThat(pace.perDayNeeded).isEqualTo(105) + } + + @Test + fun skippedPagesAreNotCounted() { + // a page type whose first page is a cover: 547 pages from page 2 + val pace = PaceMath.pace(startDay = 0, today = 0, page = 2, firstPage = 2, totalPages = 547, targetDays = 30) + assertThat(pace.pagesDone).isEqualTo(0) + assertThat(pace.expectedByToday).isEqualTo(19) + } + + @Test + fun theLastPageReadIsNotTheEndUntilItWraps() { + val pace = PaceMath.pace(startDay = 0, today = 20, page = 604, firstPage = 1, totalPages = 604, targetDays = 30) + assertThat(pace.remaining).isEqualTo(1) + } +} diff --git a/common/progress/src/test/kotlin/com/quran/mobile/progress/log/BookmarkMoveRecorderTest.kt b/common/progress/src/test/kotlin/com/quran/mobile/progress/log/BookmarkMoveRecorderTest.kt new file mode 100644 index 0000000000..392882bb7d --- /dev/null +++ b/common/progress/src/test/kotlin/com/quran/mobile/progress/log/BookmarkMoveRecorderTest.kt @@ -0,0 +1,175 @@ +package com.quran.mobile.progress.log + +import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver +import com.google.common.truth.Truth.assertThat +import com.quran.data.core.QuranInfo +import com.quran.data.dao.ReadingBookmarksDao +import com.quran.data.dao.Settings +import com.quran.data.di.AppCoroutineScope +import com.quran.data.model.PageAppearance +import com.quran.data.model.SuraAyah +import com.quran.data.model.bookmark.AyahReadingBookmark +import com.quran.data.model.bookmark.EmptyReadingBookmark +import com.quran.data.model.bookmark.PageReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.labs.androidquran.pages.data.madani.MadaniDataSource +import com.quran.mobile.progress.db.ProgressDatabase +import com.quran.mobile.progress.reading.PageTime +import com.quran.mobile.progress.reading.ReadingTimeLog +import com.quran.mobile.progress.time.LocalDays +import com.quran.mobile.progress.time.ProgressClock +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.test.runTest +import org.junit.Test +import java.util.TimeZone +import kotlin.time.Instant + +class BookmarkMoveRecorderTest { + private val driver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY).also { ProgressDatabase.Schema.create(it) } + private val database = ProgressDatabase(driver) + private val clock = FakeClock() + private val settings = FakeSettings() + private val quranInfo = QuranInfo(MadaniDataSource()) + + private fun recorder() = + BookmarkMoveRecorder(NoReadingBookmarks, settings, { quranInfo }, database, clock, AppCoroutineScope()) + + private fun page(slot: ReadingBookmarkType, page: Int) = + PageReadingBookmark(slot, page, Instant.fromEpochMilliseconds(clock.now)) + + private fun rows(slot: ReadingBookmarkType = ReadingBookmarkType.TEAL) = + database.bookmarkMoveQueries.movesFor(slot.name).executeAsList().map { it.toRecorded() } + + @Test + fun theFirstPositionSeenIsABaselineAndTheSameAgainWritesNothing() = runTest { + val recorder = recorder() + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 262))) + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 262))) + val rows = rows() + assertThat(rows.map { it.kind }).containsExactly(MoveKind.BASELINE) + assertThat(rows.single().position).isEqualTo(BookmarkPosition(262, "madani", 15, 1)) + } + + @Test + fun aMoveIsKeptWithItsDay() = runTest { + val recorder = recorder() + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 262))) + clock.now += LocalDays.DAY_MS + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 280))) + val rows = rows() + assertThat(rows.map { it.kind }).containsExactly(MoveKind.BASELINE, MoveKind.MOVE).inOrder() + assertThat(rows[1].day).isEqualTo(rows[0].day + 1) + } + + @Test + fun aMoveCreditsTheReadingTimeBeforeItToThatBookmark() = runTest { + val recorder = recorder() + val log = ReadingTimeLog(database) + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 262), page(ReadingBookmarkType.ORANGE, 500))) + log.add(listOf(PageTime(clock.today(), 262, 600_000, read = true)), "madani", clock.now) + clock.now += 60_000 + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 270), page(ReadingBookmarkType.ORANGE, 500))) + // read after the move: not credited yet + clock.now += 60_000 + log.add(listOf(PageTime(clock.today(), 270, 120_000, read = true)), "madani", clock.now) + + val minutes = database.readingTimeQueries.minutesBySlotAndDay().executeAsList().associate { it.slot to it.ms } + assertThat(minutes).containsExactly("TEAL", 600_000L, null, 120_000L) + } + + @Test + fun aClearedBookmarkPlacedAgainIsAMoveFromWhereItWas() = runTest { + val recorder = recorder() + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 262))) + recorder.record(listOf(EmptyReadingBookmark(ReadingBookmarkType.TEAL, Instant.fromEpochMilliseconds(clock.now)))) + recorder.record(listOf(EmptyReadingBookmark(ReadingBookmarkType.TEAL, Instant.fromEpochMilliseconds(clock.now)))) + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 270))) + assertThat(rows().map { it.kind }).containsExactly(MoveKind.BASELINE, MoveKind.CLEAR, MoveKind.MOVE).inOrder() + } + + @Test + fun anAyahBookmarkIsOnItsPage() = runTest { + recorder().record(listOf(AyahReadingBookmark(ReadingBookmarkType.RED, 18, 1, Instant.fromEpochMilliseconds(clock.now)))) + assertThat(rows(ReadingBookmarkType.RED).single().position) + .isEqualTo(BookmarkPosition(quranInfo.getPageFromSuraAyah(18, 1), "madani", 18, 1)) + } + + @Test + fun aRecorderStartedAgainWritesNothingForWhatItAlreadyKept() = runTest { + recorder().record(listOf(page(ReadingBookmarkType.TEAL, 262))) + recorder().record(listOf(page(ReadingBookmarkType.TEAL, 262))) + assertThat(rows()).hasSize(1) + } + + @Test + fun anotherPageTypeIsABaseline() = runTest { + val recorder = recorder() + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 262))) + settings.type = "warsh" + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 250))) + assertThat(rows().map { it.kind }).containsExactly(MoveKind.BASELINE, MoveKind.BASELINE).inOrder() + } + + @Test + fun aMoveMadeEarlierOnAnotherDeviceKeepsItsTime() = runTest { + val recorder = recorder() + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 262))) + val movedAt = clock.now + 60_000 + clock.now += 3_600_000 + recorder.record(listOf(PageReadingBookmark(ReadingBookmarkType.TEAL, 280, Instant.fromEpochMilliseconds(movedAt)))) + assertThat(rows()[1].atMs).isEqualTo(movedAt) + } + + @Test + fun aCycleStartedByHandIsKept() = runTest { + val recorder = recorder() + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 262))) + recorder.markCycleStart(ReadingBookmarkType.TEAL.name) + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 262))) + recorder.record(listOf(page(ReadingBookmarkType.TEAL, 263))) + assertThat(rows().map { it.kind }).containsExactly(MoveKind.BASELINE, MoveKind.CYCLE_MARK, MoveKind.MOVE).inOrder() + } + + private class FakeClock : ProgressClock { + var now = 20_000L * LocalDays.DAY_MS + 9 * 3_600_000L + override fun nowMs() = now + override fun zone(): TimeZone = TimeZone.getTimeZone("UTC") + } + + private object NoReadingBookmarks : ReadingBookmarksDao { + override fun readingBookmarksFlow(): Flow> = emptyFlow() + override suspend fun readingBookmarks(): List = emptyList() + override suspend fun setPageReadingBookmark(slot: ReadingBookmarkType, page: Int) = error("unused") + override suspend fun setAyahReadingBookmark(slot: ReadingBookmarkType, suraAyah: SuraAyah) = error("unused") + override suspend fun clearReadingBookmark(slot: ReadingBookmarkType): ReadingBookmark = error("unused") + override suspend fun renameReadingBookmark(slot: ReadingBookmarkType, name: String?) = error("unused") + override suspend fun isPageReadingBookmark(slot: ReadingBookmarkType, page: Int) = error("unused") + override suspend fun togglePageReadingBookmark(slot: ReadingBookmarkType, page: Int) = error("unused") + override suspend fun updateReadingBookmarks(ayah: SuraAyah, added: List, removed: List) = + error("unused") + } + + private class FakeSettings : Settings { + var type = "madani" + override suspend fun pageType() = type + override suspend fun setVersion(version: Int) = Unit + override suspend fun setShouldOverlayPageInfo(shouldOverlay: Boolean) = Unit + override suspend fun lastPage() = 1 + override suspend fun pageAppearance(): PageAppearance = error("unused") + override suspend fun pageTextBrightness() = 0 + override suspend fun nightModeBackgroundBrightness() = 0 + override suspend fun dayPageBackgroundColor(): Int? = null + override suspend fun shouldShowHeaderFooter() = false + override suspend fun shouldShowBookmarks() = false + override suspend fun setPageType(pageType: String) = Unit + override suspend fun showSidelines() = false + override suspend fun setShowSidelines(show: Boolean) = Unit + override suspend fun showLineDividers() = false + override suspend fun setShouldShowLineDividers(show: Boolean) = Unit + override suspend fun setAyahTextSize(value: Int) = Unit + override suspend fun translationTextSize() = 0 + override fun preferencesFlow(): Flow = emptyFlow() + } +} diff --git a/common/progress/src/test/kotlin/com/quran/mobile/progress/reading/ReadingTimeAccumulatorTest.kt b/common/progress/src/test/kotlin/com/quran/mobile/progress/reading/ReadingTimeAccumulatorTest.kt new file mode 100644 index 0000000000..dbc9cbc341 --- /dev/null +++ b/common/progress/src/test/kotlin/com/quran/mobile/progress/reading/ReadingTimeAccumulatorTest.kt @@ -0,0 +1,100 @@ +package com.quran.mobile.progress.reading + +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import java.util.TimeZone + +class ReadingTimeAccumulatorTest { + private val utc = TimeZone.getTimeZone("UTC") + private val accumulator = ReadingTimeAccumulator(zone = { utc }) + private val day = 20_000L + private val start = day * 86_400_000L + 10 * 3_600_000L + private fun at(seconds: Long) = start + seconds * 1000 + + @Test + fun countsTheTimeAPageIsOpen() { + accumulator.onResume(at(0), setOf(5)) + accumulator.onPages(at(90), setOf(6)) + accumulator.onPause(at(150)) + assertThat(accumulator.drain()).containsExactly( + PageTime(day, 5, 90_000, read = true), + PageTime(day, 6, 60_000, read = true), + ) + } + + @Test + fun stopsCountingThreeMinutesAfterTheLastPageTurnOrTouch() { + accumulator.onResume(at(0), setOf(5)) + accumulator.onInteraction(at(60)) + accumulator.tick(at(600)) + accumulator.onPause(at(900)) + assertThat(accumulator.drain().single().ms).isEqualTo(240_000) + } + + @Test + fun aPageSeenOnlyBrieflyIsNotRead() { + accumulator.onResume(at(0), setOf(5)) + accumulator.onPages(at(5), setOf(6)) + accumulator.onPause(at(65)) + val times = accumulator.drain().associateBy { it.page } + assertThat(times.getValue(5).read).isFalse() + assertThat(times.getValue(6).read).isTrue() + } + + @Test + fun twoPagesSideBySideShareTheTimeAndAreBothRead() { + accumulator.onResume(at(0), setOf(4, 5)) + accumulator.onPause(at(60)) + assertThat(accumulator.drain()).containsExactly( + PageTime(day, 4, 30_000, read = true), + PageTime(day, 5, 30_000, read = true), + ) + } + + @Test + fun timeWhilePausedIsNotCounted() { + accumulator.onResume(at(0), setOf(5)) + accumulator.onPause(at(30)) + accumulator.tick(at(100)) + accumulator.onResume(at(200), setOf(5)) + accumulator.onPause(at(230)) + assertThat(accumulator.drain().single().ms).isEqualTo(60_000) + } + + @Test + fun aClockGoingBackIsIgnored() { + accumulator.onResume(at(0), setOf(5)) + accumulator.tick(at(-3_600)) + accumulator.onPause(at(-3_570)) + assertThat(accumulator.drain().single().ms).isEqualTo(30_000) + } + + @Test + fun aClockJumpingAheadCountsNoMoreThanTheIdleLimit() { + accumulator.onResume(at(0), setOf(5)) + accumulator.tick(at(86_400)) + assertThat(accumulator.drain().single().ms).isEqualTo(ReadingTimeAccumulator.IDLE_MS) + } + + @Test + fun timeIsSplitAtMidnight() { + val beforeMidnight = (day + 1) * 86_400_000L - 60_000L + accumulator.onResume(beforeMidnight, setOf(5)) + accumulator.onPause(beforeMidnight + 90_000L) + assertThat(accumulator.drain()).containsExactly( + PageTime(day, 5, 60_000, read = true), + PageTime(day + 1, 5, 30_000, read = true), + ) + } + + @Test + fun midnightIsLocal() { + val cairo = TimeZone.getTimeZone("Africa/Cairo") + val local = ReadingTimeAccumulator(zone = { cairo }) + // 22:30 UTC is after midnight in Cairo (UTC+2) + val t = day * 86_400_000L + 22 * 3_600_000L + 30 * 60_000L + local.onResume(t, setOf(5)) + local.onPause(t + 60_000L) + assertThat(local.drain().single().day).isEqualTo(day + 1) + } +} diff --git a/common/progress/src/test/kotlin/com/quran/mobile/progress/reminder/ReminderDecisionTest.kt b/common/progress/src/test/kotlin/com/quran/mobile/progress/reminder/ReminderDecisionTest.kt new file mode 100644 index 0000000000..5ba525d507 --- /dev/null +++ b/common/progress/src/test/kotlin/com/quran/mobile/progress/reminder/ReminderDecisionTest.kt @@ -0,0 +1,119 @@ +package com.quran.mobile.progress.reminder + +import com.google.common.truth.Truth.assertThat +import com.quran.data.model.bookmark.ReadingBookmarkPurpose +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.mobile.progress.cycle.Cycle +import com.quran.mobile.progress.cycle.PaceMath +import com.quran.mobile.progress.summary.BookmarkProgress +import com.quran.mobile.progress.summary.DayAmount +import com.quran.mobile.progress.time.LocalDays +import org.junit.Test +import java.util.TimeZone + +class ReminderDecisionTest { + private val cairo = TimeZone.getTimeZone("Africa/Cairo") + private val today = 20_400L + private val eightPm = 20 * 60 + private fun at(hour: Int, minute: Int = 0) = LocalDays.timeOnDay(today, hour * 60 + minute, cairo) + + /** A teal cycle started [dayN] days ago (day 1 = today), the bookmark on [page], [todayPages] read today. */ + private fun cycle(dayN: Int, page: Int, todayPages: Int = 0, slot: ReadingBookmarkType = ReadingBookmarkType.TEAL) = + BookmarkProgress( + slot = slot, + name = null, + purpose = ReadingBookmarkPurpose.READING, + targetDays = 30, + position = null, + cycle = Cycle(0L, today - dayN + 1, partial = false), + cycleStartPage = 1, + pace = PaceMath.pace(today - dayN + 1, today, page, 1, 604, 30), + firstDay = today - dayN + 1, + chartDays = 30, + days = listOf(DayAmount(today, todayPages, todayPages * 2)), + cycleReadingMs = 0, + cyclePages = page - 1, + lastCycle = null, + moved = true, + ) + + private fun decide( + bookmarks: List, + now: Long = at(20, 5), + enabled: Boolean = true, + last: Long = today - 1, + readerOpen: Boolean = false, + ) = ReminderDecision.decide(enabled, now, cairo, eightPm, last, readerOpen, bookmarks) + + @Test + fun offSaysNothing() { + assertThat(decide(listOf(cycle(10, 50)), enabled = false)).isEqualTo(Reminder.None) + } + + @Test + fun noOpenCycleWithADeadlineSaysNothing() { + assertThat(decide(listOf(cycle(10, 50).copy(pace = null)))).isEqualTo(Reminder.None) + assertThat(decide(emptyList())).isEqualTo(Reminder.None) + } + + @Test + fun onceADay() { + assertThat(decide(listOf(cycle(10, 50)), last = today)).isEqualTo(Reminder.None) + } + + @Test + fun notBeforeItsTime() { + assertThat(decide(listOf(cycle(10, 50)), now = at(19, 59))).isEqualTo(Reminder.None) + } + + @Test + fun notWhileReading() { + assertThat(decide(listOf(cycle(10, 50)), readerOpen = true)).isEqualTo(Reminder.None) + } + + @Test + fun aheadAndReadTodaySaysNothing() { + assertThat(decide(listOf(cycle(10, 300, todayPages = 20)))).isEqualTo(Reminder.None) + } + + @Test + fun aheadButNotReadToday() { + val reminder = decide(listOf(cycle(10, 300))) + assertThat(reminder).isInstanceOf(Reminder.NotReadToday::class.java) + // 305 pages in 21 days + assertThat((reminder as Reminder.NotReadToday).perDay).isEqualTo(15) + } + + @Test + fun behindSaysByHowMuch() { + val reminder = decide(listOf(cycle(10, 101, todayPages = 5))) + assertThat(reminder).isInstanceOf(Reminder.Behind::class.java) + reminder as Reminder.Behind + assertThat(reminder.pages).isEqualTo(102) + assertThat(reminder.finishByDay).isEqualTo(today - 9 + 29) + } + + @Test + fun overdueComesFirst() { + val reminder = decide(listOf(cycle(10, 101), cycle(33, 500, slot = ReadingBookmarkType.GREEN))) + assertThat(reminder).isInstanceOf(Reminder.Overdue::class.java) + assertThat((reminder as Reminder.Overdue).remaining).isEqualTo(105) + } + + @Test + fun theNextReminderIsTodayAtItsTimeOrTomorrow() { + assertThat(ReminderDecision.nextReminderAt(at(9), cairo, eightPm)).isEqualTo(at(20)) + assertThat(ReminderDecision.nextReminderAt(at(20), cairo, eightPm)) + .isEqualTo(LocalDays.timeOnDay(today + 1, eightPm, cairo)) + } + + @Test + fun theNextReminderKeepsItsLocalTimeOverAClockChange() { + // London moves its clocks forward on 29 March 2026 + val london = TimeZone.getTimeZone("Europe/London") + val beforeChange = LocalDays.epochDay(1_774_656_000_000L, london) // 2026-03-28 + val now = LocalDays.timeOnDay(beforeChange, 21 * 60, london) + val next = ReminderDecision.nextReminderAt(now, london, eightPm) + assertThat(next - now).isEqualTo(22 * 3_600_000L) // 21:00 GMT to 20:00 BST is 22 hours + } +} diff --git a/common/progress/src/test/kotlin/com/quran/mobile/progress/summary/ProgressCalculatorTest.kt b/common/progress/src/test/kotlin/com/quran/mobile/progress/summary/ProgressCalculatorTest.kt new file mode 100644 index 0000000000..2c553ba6f5 --- /dev/null +++ b/common/progress/src/test/kotlin/com/quran/mobile/progress/summary/ProgressCalculatorTest.kt @@ -0,0 +1,151 @@ +package com.quran.mobile.progress.summary + +import com.google.common.truth.Truth.assertThat +import com.quran.data.core.QuranInfo +import com.quran.data.model.bookmark.PageReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmarkPurpose +import com.quran.data.model.bookmark.ReadingBookmarkSlotSetting +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.labs.androidquran.pages.data.madani.MadaniDataSource +import com.quran.mobile.progress.Moves +import com.quran.mobile.progress.history.DayMinutes +import com.quran.mobile.progress.history.LoggedSession +import com.quran.mobile.progress.session.AyahResult +import com.quran.mobile.progress.session.SessionRecord +import org.junit.Test +import kotlin.time.Instant + +class ProgressCalculatorTest { + private val quranInfo = QuranInfo(MadaniDataSource()) + private val calculator = ProgressCalculator(quranInfo, "madani") + private val teal = ReadingBookmarkSlotSetting(ReadingBookmarkType.TEAL, enabled = true, targetDays = 30) + + private fun at(page: Int) = PageReadingBookmark(ReadingBookmarkType.TEAL, page, Instant.fromEpochMilliseconds(0)) + /** [minutes] read on [day], credited by the move at [creditedAt] (uncredited without a slot). */ + private fun minutes(day: Long, minutes: Int, creditedAt: Long, slot: String? = "TEAL") = + DayMinutes(slot, day, minutes * 60_000L, creditedAt.takeIf { slot != null }) + + @Test + fun aCycleWithADeadlineHasItsPaceAndADayForEachPageAndMinute() { + val moves = Moves.of { + day(100) { + baseline(1, 1, 1) + move(21, 2, 137) + } + day(101) { move(45, 3, 1) } + } + val progress = calculator.bookmark( + at(45), teal, moves, + listOf(minutes(100, 30, moves[1].atMs), minutes(101, 20, moves[2].atMs), minutes(101, 5, 0, slot = null)), + today = 101 + ) + assertThat(progress.pace!!.dayN).isEqualTo(2) + assertThat(progress.pace!!.pagesDone).isEqualTo(44) + assertThat(progress.firstDay).isEqualTo(100) + assertThat(progress.chartDays).isEqualTo(30) + assertThat(progress.days).containsExactly(DayAmount(100, 20, 30), DayAmount(101, 24, 20)).inOrder() + assertThat(progress.cycleReadingMs).isEqualTo(50 * 60_000L) + assertThat(progress.cyclePages).isEqualTo(44) + assertThat(progress.lastCycle).isNull() + assertThat(progress.moved).isTrue() + } + + @Test + fun aWrapEndsTheLastCycleWithItsDatesAndTime() { + val moves = Moves.of { + day(10) { baseline(1, 1, 1) } + day(20) { move(300, 16, 1) } + day(37) { move(604, 114, 1) } + day(38) { move(2, 2, 1) } + } + val wrap = moves[3].atMs + val reading = listOf( + minutes(20, 100, moves[1].atMs), + minutes(37, 40, moves[2].atMs), + // the end of the Quran, read on the day it wrapped: credited by the wrap, to the cycle it closes + minutes(38, 25, wrap), + // read after the wrap, credited by a later move + minutes(38, 10, wrap + 3_600_000L), + ) + val progress = calculator.bookmark(at(2), teal, moves, reading, today = 38) + assertThat(progress.lastCycle).isEqualTo(ClosedCycle(startDay = 10, endDay = 38, readingMs = 165 * 60_000L)) + assertThat(progress.lastCycle!!.days).isEqualTo(29) + assertThat(progress.cycle!!.startDay).isEqualTo(38) + assertThat(progress.pace!!.dayN).isEqualTo(1) + assertThat(progress.days.single()).isEqualTo(DayAmount(38, 1, 10)) + assertThat(progress.cycleReadingMs).isEqualTo(10 * 60_000L) + } + + @Test + fun aCycleEndsWhenItsLastPagesWereReadNotWhenTheNextOneStarts() { + val moves = Moves.of { + day(10) { baseline(1, 1, 1) } + day(37) { move(604, 114, 1) } + day(41) { move(1, 1, 1) } + } + val progress = calculator.bookmark(at(1), teal, moves, listOf(minutes(37, 40, moves[2].atMs)), today = 41) + assertThat(progress.lastCycle).isEqualTo(ClosedCycle(startDay = 10, endDay = 37, readingMs = 40 * 60_000L)) + assertThat(progress.cycle!!.startDay).isEqualTo(41) + } + + @Test + fun withoutADeadlineTheChartIsTheLast30Days() { + val study = teal.copy(slot = ReadingBookmarkType.ORANGE, targetDays = 0) + val moves = Moves.of { + day(100) { baseline(40, 3, 1) } + day(120) { move(60, 3, 92) } + } + val progress = calculator.bookmark( + PageReadingBookmark(ReadingBookmarkType.ORANGE, 60, Instant.fromEpochMilliseconds(0)), study, moves, emptyList(), today = 125 + ) + assertThat(progress.pace).isNull() + assertThat(progress.firstDay).isEqualTo(96) + assertThat(progress.days).hasSize(30) + assertThat(progress.days.single { it.pages > 0 }).isEqualTo(DayAmount(120, 20, 0)) + } + + @Test + fun aMemorizationBookmarkHasNoCycles() { + val hifz = teal.copy(purpose = ReadingBookmarkPurpose.MEMORIZATION) + val moves = Moves.of { + day(1) { baseline(600, 109, 1) } + day(2) { move(1, 1, 1) } + } + val progress = calculator.bookmark(at(1), hifz, moves, emptyList(), today = 2) + assertThat(progress.lastCycle).isNull() + assertThat(progress.pace).isNull() + } + + @Test + fun theJuzLineRunsFromTheStartOfJuz1ToTheEndOfJuz30() { + assertThat(calculator.juzPosition(1)).isEqualTo(0f) + assertThat(calculator.juzPosition(quranInfo.getStartingPageForJuz(30))).isEqualTo(29f) + assertThat(calculator.juzPosition(604)).isLessThan(30f) + assertThat(calculator.juzOf(2, 142)).isEqualTo(2) + assertThat(calculator.juzOf(2, 141)).isEqualTo(1) + assertThat(calculator.juzOf(114, 6)).isEqualTo(30) + } + + @Test + fun anAyahIsHeldWhenItsLastMemorizingWentWithoutHelp() { + fun session(id: String, day: Long, hinted: Int) = LoggedSession( + day, + SessionRecord( + id, "MEMORIZE", day * 86_400_000L, day * 86_400_000L + 60_000, 50_000, 112, 1, 112, 2, 6, 6 - hinted, hinted, 0, 0, + finished = false, recordingId = null, + ayahs = listOf( + AyahResult(112, 1, ayahWords = 4, words = 4, hinted = 0, missed = 0, mistakes = 0), + AyahResult(112, 2, ayahWords = 2, words = 2, hinted = hinted, missed = 0, mistakes = 0), + ), + ), + ) + val clean = calculator.memorizing(listOf(session("a", 5, hinted = 0)), today = 5) + assertThat(clean.juz.single { it.number == 30 }.held).isEqualTo(2) + assertThat(clean.suras.getValue(30).single { it.number == 112 }).isEqualTo(Held(112, 2, 4)) + + val later = calculator.memorizing(listOf(session("a", 5, hinted = 0), session("b", 6, hinted = 1)), today = 6) + assertThat(later.juz.single { it.number == 30 }.held).isEqualTo(1) + assertThat(later.days.last().accuracy).isEqualTo(83) + assertThat(later.juz.sumOf { it.ayat }).isEqualTo(6236) + } +} diff --git a/common/recitation/src/main/java/com/quran/recitation/pages/PagePreviews.kt b/common/recitation/src/main/java/com/quran/recitation/pages/PagePreviews.kt new file mode 100644 index 0000000000..b15de470f4 --- /dev/null +++ b/common/recitation/src/main/java/com/quran/recitation/pages/PagePreviews.kt @@ -0,0 +1,38 @@ +package com.quran.recitation.pages + +import android.app.Activity +import android.view.View +import com.quran.data.model.SuraAyah +import com.quran.recitation.presenter.RecitationHighlightsPresenter.HighlightAction + +/** + * Draws mushaf pages as the reading screen does (the page type in use, its theme, night mode), but + * outside of it: e.g. to play a recorded session back on its own pages. + */ +interface PagePreviews { + /** Pages for [activity], until [PageRenderer.close] (at the latest when the activity goes). */ + fun open(activity: Activity): PageRenderer +} + +interface PageRenderer { + /** Whether pages are drawn at night (the reading screen's setting). */ + val isNightMode: Boolean + + /** + * A view of [page], loading as the reading screen does (downloading a missing image). [onTapped] + * gets the ayah tapped, and its word when the page knows where its words are. + */ + fun page(page: Int, onTapped: (ayah: SuraAyah, word: Int?) -> Unit): PagePreview + + fun close() +} + +interface PagePreview { + val view: View + + /** Changes the page's highlights; they are kept until its layout has loaded. */ + fun apply(actions: List) + + /** Stops loading and frees the page's image. */ + fun release() +} diff --git a/common/recitation/src/main/java/com/quran/recitation/presenter/RecitationPresenter.kt b/common/recitation/src/main/java/com/quran/recitation/presenter/RecitationPresenter.kt index 3bea185b72..7a9ac1854d 100644 --- a/common/recitation/src/main/java/com/quran/recitation/presenter/RecitationPresenter.kt +++ b/common/recitation/src/main/java/com/quran/recitation/presenter/RecitationPresenter.kt @@ -13,7 +13,28 @@ interface RecitationPresenter : Presenter { fun isRecitationEnabledFlow(): StateFlow fun onRequestPermissionsResult(requestCode: Int, grantResults: IntArray) - fun startOrStopRecitation(startAyah: () -> SuraAyah, showModeSelection: Boolean = false) + fun startOrStopRecitation(startAyah: () -> SuraAyah, start: RecitationStart = RecitationStart.DEFAULT) fun endSession() + /** Whether sessions produce a transcript the user can open. */ + fun supportsTranscript(): Boolean = true + + /** Whether sessions are recorded and can be played back. */ + fun supportsPlayback(): Boolean = true + + /** Whether the session hides the ayat, so the user can show and hide them again. */ + fun supportsAyahVisibility(): Boolean = true + + /** Whether the user can ask for a hint (the next word) during a session. */ + fun supportsHints(): Boolean = false + + /** The user asked for the next word. */ + fun onHintRequested() {} + + /** + * Called by the reading screen: the pages on screen (one, or two side by side) and how to start a + * session there, for sessions started from the presenter's own controls. + */ + fun setReadingScreen(pagesOnScreen: () -> List, start: (RecitationStart) -> Unit) {} + } diff --git a/common/recitation/src/main/java/com/quran/recitation/presenter/RecitationStart.kt b/common/recitation/src/main/java/com/quran/recitation/presenter/RecitationStart.kt new file mode 100644 index 0000000000..f45091cf8c --- /dev/null +++ b/common/recitation/src/main/java/com/quran/recitation/presenter/RecitationStart.kt @@ -0,0 +1,13 @@ +package com.quran.recitation.presenter + +/** How the user asked to start a session from the reading screen. */ +enum class RecitationStart { + /** Right away, the usual way (e.g. the toolbar's "Memorize"). */ + DEFAULT, + + /** Let the user choose how to recite (a microphone was tapped). */ + CHOOSE, + + /** Let the user choose among every way there is (a microphone was long-pressed). */ + CHOOSE_ALL, +} diff --git a/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/AdaptiveWidth.kt b/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/AdaptiveWidth.kt new file mode 100644 index 0000000000..2ffceb9007 --- /dev/null +++ b/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/AdaptiveWidth.kt @@ -0,0 +1,13 @@ +package com.quran.labs.androidquran.common.ui.core + +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp + +/** Material's window width classes: one pane on a phone, more side by side on larger screens. */ +enum class WidthClass { Compact, Medium, Expanded } + +fun widthClassOf(width: Dp): WidthClass = when { + width < 600.dp -> WidthClass.Compact + width < 840.dp -> WidthClass.Medium + else -> WidthClass.Expanded +} diff --git a/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/ReadingBookmarkSlots.kt b/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/ReadingBookmarkSlots.kt index 2a346f6bee..6fe13a205a 100644 --- a/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/ReadingBookmarkSlots.kt +++ b/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/ReadingBookmarkSlots.kt @@ -18,32 +18,25 @@ data class ReadingBookmarkSlotSpec( ) object ReadingBookmarkSlots { - private val teal = ReadingBookmarkSlotSpec( - slot = ReadingBookmarkType.TEAL, - colorResourceId = R.color.reading_bookmark_teal, - nameResourceId = R.string.reading_bookmark_teal - ) - - private val orange = ReadingBookmarkSlotSpec( - slot = ReadingBookmarkType.ORANGE, - colorResourceId = R.color.reading_bookmark_orange, - nameResourceId = R.string.reading_bookmark_orange - ) - - private val red = ReadingBookmarkSlotSpec( - slot = ReadingBookmarkType.RED, - colorResourceId = R.color.reading_bookmark_red, - nameResourceId = R.string.reading_bookmark_red - ) - - operator fun get(slot: ReadingBookmarkType): ReadingBookmarkSlotSpec { - return when (slot) { - ReadingBookmarkType.TEAL -> teal - ReadingBookmarkType.ORANGE -> orange - ReadingBookmarkType.RED -> red + private val specs = ReadingBookmarkType.entries.associateWith { slot -> + when (slot) { + ReadingBookmarkType.TEAL -> ReadingBookmarkSlotSpec(slot, R.color.reading_bookmark_teal, R.string.reading_bookmark_teal) + ReadingBookmarkType.ORANGE -> + ReadingBookmarkSlotSpec(slot, R.color.reading_bookmark_orange, R.string.reading_bookmark_orange) + ReadingBookmarkType.RED -> ReadingBookmarkSlotSpec(slot, R.color.reading_bookmark_red, R.string.reading_bookmark_red) + ReadingBookmarkType.GREEN -> + ReadingBookmarkSlotSpec(slot, R.color.reading_bookmark_green, R.string.reading_bookmark_green) + ReadingBookmarkType.BLUE -> ReadingBookmarkSlotSpec(slot, R.color.reading_bookmark_blue, R.string.reading_bookmark_blue) + ReadingBookmarkType.PURPLE -> + ReadingBookmarkSlotSpec(slot, R.color.reading_bookmark_purple, R.string.reading_bookmark_purple) + ReadingBookmarkType.BROWN -> + ReadingBookmarkSlotSpec(slot, R.color.reading_bookmark_brown, R.string.reading_bookmark_brown) + ReadingBookmarkType.GREY -> ReadingBookmarkSlotSpec(slot, R.color.reading_bookmark_grey, R.string.reading_bookmark_grey) } } + operator fun get(slot: ReadingBookmarkType): ReadingBookmarkSlotSpec = specs.getValue(slot) + fun displayName(context: Context, slot: ReadingBookmarkType, name: String?): String = name?.takeIf { it.isNotBlank() } ?: context.getString(this[slot].nameResourceId) diff --git a/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/Theme.kt b/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/Theme.kt index ba3485e821..410b13b8dc 100644 --- a/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/Theme.kt +++ b/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/Theme.kt @@ -95,6 +95,7 @@ object QuranIcons { val FastRewind: ImageVector get() = com.quran.labs.androidquran.common.ui.core.icons.FastRewind val HighlightOff: ImageVector get() = com.quran.labs.androidquran.common.ui.core.icons.HighlightOff val Logout: ImageVector get() = com.quran.labs.androidquran.common.ui.core.icons.Logout + val Lightbulb: ImageVector get() = com.quran.labs.androidquran.common.ui.core.icons.Lightbulb val MenuBook: ImageVector get() = com.quran.labs.androidquran.common.ui.core.icons.MenuBook val Mic: ImageVector get() = com.quran.labs.androidquran.common.ui.core.icons.Mic val Notes: ImageVector get() = com.quran.labs.androidquran.common.ui.core.icons.Notes diff --git a/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/icons/Lightbulb.kt b/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/icons/Lightbulb.kt new file mode 100644 index 0000000000..84a4a30476 --- /dev/null +++ b/common/ui/core/src/main/java/com/quran/labs/androidquran/common/ui/core/icons/Lightbulb.kt @@ -0,0 +1,38 @@ +package com.quran.labs.androidquran.common.ui.core.icons + +import androidx.compose.material3.Icon +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.tooling.preview.Preview + +val Lightbulb: ImageVector by lazy { + materialIcon(name = "Filled.Lightbulb") { + materialPath { + moveTo(9.0f, 21.0f) + curveToRelative(0.0f, 0.55f, 0.45f, 1.0f, 1.0f, 1.0f) + horizontalLineToRelative(4.0f) + curveToRelative(0.55f, 0.0f, 1.0f, -0.45f, 1.0f, -1.0f) + verticalLineToRelative(-1.0f) + horizontalLineTo(9.0f) + verticalLineToRelative(1.0f) + close() + moveTo(12.0f, 2.0f) + curveTo(8.14f, 2.0f, 5.0f, 5.14f, 5.0f, 9.0f) + curveToRelative(0.0f, 2.38f, 1.19f, 4.47f, 3.0f, 5.74f) + verticalLineTo(17.0f) + curveToRelative(0.0f, 0.55f, 0.45f, 1.0f, 1.0f, 1.0f) + horizontalLineToRelative(6.0f) + curveToRelative(0.55f, 0.0f, 1.0f, -0.45f, 1.0f, -1.0f) + verticalLineToRelative(-2.26f) + curveToRelative(1.81f, -1.27f, 3.0f, -3.36f, 3.0f, -5.74f) + curveToRelative(0.0f, -3.86f, -3.14f, -7.0f, -7.0f, -7.0f) + close() + } + } +} + +@Preview +@Composable +private fun LightbulbIconPreview() { + Icon(imageVector = Lightbulb, contentDescription = null) +} diff --git a/common/ui/core/src/main/res/values-ar/strings.xml b/common/ui/core/src/main/res/values-ar/strings.xml index 58a4a069e0..f78a7b9378 100644 --- a/common/ui/core/src/main/res/values-ar/strings.xml +++ b/common/ui/core/src/main/res/values-ar/strings.xml @@ -21,8 +21,13 @@ أزرق وردي بنفسجي - + أزرق مخضر برتقالي أحمر + أخضر + أزرق + بنفسجي + بني + رمادي diff --git a/common/ui/core/src/main/res/values-night/colors.xml b/common/ui/core/src/main/res/values-night/colors.xml index 4cc959af8d..b5a6a6aa03 100644 --- a/common/ui/core/src/main/res/values-night/colors.xml +++ b/common/ui/core/src/main/res/values-night/colors.xml @@ -4,4 +4,9 @@ #ff4db6ac #ffffb74d #ffe57373 + #ff81c784 + #ff64b5f6 + #ffba68c8 + #ffa1887f + #ff90a4ae diff --git a/common/ui/core/src/main/res/values/colors.xml b/common/ui/core/src/main/res/values/colors.xml index 3c1b047e90..71ba8a1d41 100644 --- a/common/ui/core/src/main/res/values/colors.xml +++ b/common/ui/core/src/main/res/values/colors.xml @@ -12,12 +12,18 @@ #FFFEB0CA #FFD8B1FE #ff00897b #ffef6c00 #ffc62828 + #ff2e7d32 + #ff1565c0 + #ff6a1b9a + #ff6d4c41 + #ff546e7a + Teal Orange Red + Green + Blue + Purple + Brown + Grey diff --git a/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/presenter/AudioBarPresenter.kt b/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/presenter/AudioBarPresenter.kt index e8a500a617..d456d2af66 100644 --- a/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/presenter/AudioBarPresenter.kt +++ b/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/presenter/AudioBarPresenter.kt @@ -153,11 +153,18 @@ class AudioBarPresenter @Inject constructor( return if (recitationSession == null) { null } else if (isListening) { - AudioBarState.RecitationListening + AudioBarState.RecitationListening( + showTranscript = recitationPresenter.supportsTranscript(), + showHint = recitationPresenter.supportsHints(), + showHideVerses = recitationPresenter.supportsAyahVisibility(), + ) } else if (isPlaying) { - AudioBarState.RecitationPlaying + AudioBarState.RecitationPlaying(showTranscript = recitationPresenter.supportsTranscript()) } else { - AudioBarState.RecitationStopped + AudioBarState.RecitationStopped( + showTranscript = recitationPresenter.supportsTranscript(), + showPlayback = recitationPresenter.supportsPlayback(), + ) } } diff --git a/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/state/AudioBarEvent.kt b/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/state/AudioBarEvent.kt index 58e0733e09..2c53a31663 100644 --- a/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/state/AudioBarEvent.kt +++ b/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/state/AudioBarEvent.kt @@ -23,6 +23,7 @@ sealed class AudioBarEvent { data object RecitationLongPress : AudioBarEvent() data object Transcript : AudioBarEvent() data object HideVerses : AudioBarEvent() + data object RecitationHint : AudioBarEvent() data object EndSession : AudioBarEvent() data object PlayRecitation : AudioBarEvent() data object PauseRecitation : AudioBarEvent() diff --git a/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/state/AudioBarScreen.kt b/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/state/AudioBarScreen.kt index 33823d85ee..758bcec83f 100644 --- a/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/state/AudioBarScreen.kt +++ b/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/state/AudioBarScreen.kt @@ -39,11 +39,18 @@ internal sealed class AudioBarState { val messageResource: Int ) : AudioBarState() - data object RecitationListening : AudioBarState() + data class RecitationListening( + val showTranscript: Boolean = true, + val showHint: Boolean = false, + val showHideVerses: Boolean = true, + ) : AudioBarState() - data object RecitationPlaying : AudioBarState() + data class RecitationPlaying(val showTranscript: Boolean = true) : AudioBarState() - data object RecitationStopped : AudioBarState() + data class RecitationStopped( + val showTranscript: Boolean = true, + val showPlayback: Boolean = true, + ) : AudioBarState() } internal class AudioBarUiEvents( @@ -110,6 +117,7 @@ internal sealed class AudioBarUiEvent(val audioBarEvent: AudioBarEvent) { sealed class RecitationListeningEvent(event: AudioBarEvent) : AudioBarUiEvent(event) { data object HideVerses : RecitationListeningEvent(AudioBarEvent.HideVerses) + data object Hint : RecitationListeningEvent(AudioBarEvent.RecitationHint) } sealed class RecitationPlayingEvent(event: AudioBarEvent) : AudioBarUiEvent(event) { diff --git a/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/ui/AudioBar.kt b/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/ui/AudioBar.kt index 18782f5df2..c4236117a3 100644 --- a/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/ui/AudioBar.kt +++ b/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/ui/AudioBar.kt @@ -71,18 +71,24 @@ internal fun AudioBar( ) is AudioBarState.RecitationListening -> RecitationListeningAudioBar( + showTranscript = audioBarState.showTranscript, + showHint = audioBarState.showHint, + showHideVerses = audioBarState.showHideVerses, eventSink = eventListeners.commonRecordingEventSink, listeningEventSink = eventListeners.recitationListeningEventSink, modifier = updatedModifier ) is AudioBarState.RecitationPlaying -> RecitationPlayingAudioBar( + showTranscript = audioBarState.showTranscript, eventSink = eventListeners.commonRecordingEventSink, playingEventSink = eventListeners.recitationPlayingEventSink, modifier = updatedModifier ) is AudioBarState.RecitationStopped -> RecitationStoppedAudioBar( + showTranscript = audioBarState.showTranscript, + showPlayback = audioBarState.showPlayback, eventSink = eventListeners.commonRecordingEventSink, stoppedEventSink = eventListeners.recitationStoppedEventSink, modifier = updatedModifier diff --git a/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/ui/RecitationAudioBar.kt b/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/ui/RecitationAudioBar.kt index ff000b4330..e6b39e7b49 100644 --- a/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/ui/RecitationAudioBar.kt +++ b/feature/audiobar/src/main/kotlin/com/quran/mobile/feature/audiobar/ui/RecitationAudioBar.kt @@ -34,11 +34,21 @@ import com.quran.mobile.feature.audiobar.state.AudioBarUiEvent internal fun RecitationListeningAudioBar( eventSink: (AudioBarUiEvent.CommonRecordingEvent) -> Unit, listeningEventSink: (AudioBarUiEvent.RecitationListeningEvent) -> Unit, - modifier: Modifier = Modifier + modifier: Modifier = Modifier, + showTranscript: Boolean = true, + showHint: Boolean = false, + showHideVerses: Boolean = true, ) { - RecitationAudioBar(eventSink, true, modifier = modifier) { - IconButton(onClick = { listeningEventSink(AudioBarUiEvent.RecitationListeningEvent.HideVerses) }) { - Icon(QuranIcons.MenuBook, contentDescription = "") + RecitationAudioBar(eventSink, true, modifier = modifier, showTranscript = showTranscript) { + if (showHideVerses) { + IconButton(onClick = { listeningEventSink(AudioBarUiEvent.RecitationListeningEvent.HideVerses) }) { + Icon(QuranIcons.MenuBook, contentDescription = "") + } + } + if (showHint) { + IconButton(onClick = { listeningEventSink(AudioBarUiEvent.RecitationListeningEvent.Hint) }) { + Icon(QuranIcons.Lightbulb, contentDescription = "") + } } } } @@ -47,9 +57,10 @@ internal fun RecitationListeningAudioBar( internal fun RecitationPlayingAudioBar( eventSink: (AudioBarUiEvent.CommonRecordingEvent) -> Unit, playingEventSink: (AudioBarUiEvent.RecitationPlayingEvent) -> Unit, - modifier: Modifier = Modifier + modifier: Modifier = Modifier, + showTranscript: Boolean = true, ) { - RecitationAudioBar(eventSink, false, modifier = modifier) { + RecitationAudioBar(eventSink, false, modifier = modifier, showTranscript = showTranscript) { IconButton(onClick = { playingEventSink(AudioBarUiEvent.RecitationPlayingEvent.EndSession) }) { Icon(QuranIcons.Close, contentDescription = "") } @@ -64,15 +75,19 @@ internal fun RecitationPlayingAudioBar( internal fun RecitationStoppedAudioBar( eventSink: (AudioBarUiEvent.CommonRecordingEvent) -> Unit, stoppedEventSink: (AudioBarUiEvent.RecitationStoppedEvent) -> Unit, - modifier: Modifier = Modifier + modifier: Modifier = Modifier, + showTranscript: Boolean = true, + showPlayback: Boolean = true, ) { - RecitationAudioBar(eventSink, false, modifier = modifier) { + RecitationAudioBar(eventSink, false, modifier = modifier, showTranscript = showTranscript) { IconButton(onClick = { stoppedEventSink(AudioBarUiEvent.RecitationStoppedEvent.EndSession) }) { Icon(QuranIcons.Close, contentDescription = "") } - IconButton(onClick = { stoppedEventSink(AudioBarUiEvent.RecitationStoppedEvent.PlayRecitation) }) { - Icon(QuranIcons.PlayArrow, contentDescription = "") + if (showPlayback) { + IconButton(onClick = { stoppedEventSink(AudioBarUiEvent.RecitationStoppedEvent.PlayRecitation) }) { + Icon(QuranIcons.PlayArrow, contentDescription = "") + } } } } @@ -82,6 +97,7 @@ internal fun RecitationAudioBar( eventSink: (AudioBarUiEvent.CommonRecordingEvent) -> Unit, isRecitationActive: Boolean, modifier: Modifier = Modifier, + showTranscript: Boolean = true, actions: @Composable () -> Unit ) { Row( @@ -104,15 +120,17 @@ internal fun RecitationAudioBar( .width(Dp.Hairline) ) - IconButton(onClick = { eventSink(AudioBarUiEvent.CommonRecordingEvent.Transcript) }) { - Icon(QuranIcons.Chat, contentDescription = "") - } + if (showTranscript) { + IconButton(onClick = { eventSink(AudioBarUiEvent.CommonRecordingEvent.Transcript) }) { + Icon(QuranIcons.Chat, contentDescription = "") + } - Divider( - modifier = Modifier - .fillMaxHeight() - .width(Dp.Hairline) - ) + Divider( + modifier = Modifier + .fillMaxHeight() + .width(Dp.Hairline) + ) + } Box( modifier = Modifier diff --git a/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/presenter/AyahBookmarkPresenter.kt b/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/presenter/AyahBookmarkPresenter.kt index 966beb0099..67fe002cf1 100644 --- a/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/presenter/AyahBookmarkPresenter.kt +++ b/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/presenter/AyahBookmarkPresenter.kt @@ -82,11 +82,14 @@ class AyahBookmarkPresenter( } val otherReadingBookmarks = remember(readingBookmarks.value, suggestedReadingBookmark.slot) { - val placed = readingBookmarks.value - .orEmpty() + val listed = readingBookmarks.value.orEmpty() + val placed = listed .filterNot { it is EmptyReadingBookmark } .associateBy { it.slot } + // the synced slots, and those kept on the device that are turned on (the DAO lists only those) + val offered = listed.mapTo(HashSet()) { it.slot } ReadingBookmarkType.entries + .filter { it.synced || it in offered } .filterNot { it == suggestedReadingBookmark.slot } .map { slot -> placed[slot] ?: EmptyReadingBookmark(slot, Instant.DISTANT_PAST) } .toImmutableList() diff --git a/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/readingbookmark/presenter/ReadingBookmarkSheetPresenter.kt b/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/readingbookmark/presenter/ReadingBookmarkSheetPresenter.kt index 6e09493f5e..1618176546 100644 --- a/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/readingbookmark/presenter/ReadingBookmarkSheetPresenter.kt +++ b/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/readingbookmark/presenter/ReadingBookmarkSheetPresenter.kt @@ -59,7 +59,8 @@ class ReadingBookmarkSheetPresenter( val draftNames = remember { mutableStateOf>(emptyMap()) } val slots = remember(stored, draftNames.value, target) { - ReadingBookmarkType.entries.map { slot -> + // the synced slots, and those kept on the device that are turned on (the DAO lists only those) + ReadingBookmarkType.entries.filter { it.synced || it in stored }.map { slot -> val row = stored[slot] ReadingBookmarkSlotItem( slot = slot, diff --git a/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/readingbookmark/ui/ReadingBookmarkSheet.kt b/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/readingbookmark/ui/ReadingBookmarkSheet.kt index 78fa3bdcbb..79d63bd250 100644 --- a/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/readingbookmark/ui/ReadingBookmarkSheet.kt +++ b/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/readingbookmark/ui/ReadingBookmarkSheet.kt @@ -9,7 +9,9 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme @@ -120,22 +122,29 @@ internal fun ReadingBookmarkSheet( ) ) - state.slots.forEachIndexed { index, item -> - if (index > 0) { - HorizontalDivider( - color = MaterialTheme.colorScheme.outlineVariant, - modifier = Modifier.padding(horizontal = 18.dp) + // up to eight slots (the five kept on the device once turned on): they scroll on short screens + Column( + modifier = Modifier + .weight(1f, fill = false) + .verticalScroll(rememberScrollState()) + ) { + state.slots.forEachIndexed { index, item -> + if (index > 0) { + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant, + modifier = Modifier.padding(horizontal = 18.dp) + ) + } + ReadingBookmarkSlotRow( + item = item, + target = state.target, + isEditing = state.isEditing, + locationNameResolver = state.locationNameResolver, + onPlace = { eventSink(ReadingBookmarkSheetEvent.PlaceSlot(item.slot)) }, + onClear = { eventSink(ReadingBookmarkSheetEvent.ClearSlot(item.slot)) }, + onNameChange = { eventSink(ReadingBookmarkSheetEvent.NameChanged(item.slot, it)) } ) } - ReadingBookmarkSlotRow( - item = item, - target = state.target, - isEditing = state.isEditing, - locationNameResolver = state.locationNameResolver, - onPlace = { eventSink(ReadingBookmarkSheetEvent.PlaceSlot(item.slot)) }, - onClear = { eventSink(ReadingBookmarkSheetEvent.ClearSlot(item.slot)) }, - onNameChange = { eventSink(ReadingBookmarkSheetEvent.NameChanged(item.slot, it)) } - ) } } } diff --git a/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/ui/ReadingBookmarkCard.kt b/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/ui/ReadingBookmarkCard.kt index 754ccc9d20..19247d6092 100644 --- a/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/ui/ReadingBookmarkCard.kt +++ b/feature/ayahbookmark/src/main/kotlin/com/quran/mobile/feature/ayahbookmark/ui/ReadingBookmarkCard.kt @@ -191,7 +191,7 @@ private fun OtherReadingBookmarksRow( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.width(others.stackWidth()) ) { - others.forEachIndexed { index, bookmark -> + others.take(MAX_GLYPHS).forEachIndexed { index, bookmark -> Icon( imageVector = if (bookmark is EmptyReadingBookmark) BookmarkOutlineIcon else BookmarkIcon, contentDescription = null, @@ -225,5 +225,10 @@ private val ButtonContentPadding = PaddingValues(horizontal = 16.dp, vertical = private val GlyphSize = 14.dp private val GlyphOverlap = 5.dp -private fun ImmutableList.stackWidth(): Dp = - if (isEmpty()) 0.dp else GlyphSize * size - GlyphOverlap * (size - 1) +// with more bookmarks turned on, the stack shows the first few +private const val MAX_GLYPHS = 4 + +private fun ImmutableList.stackWidth(): Dp { + val shown = size.coerceAtMost(MAX_GLYPHS) + return if (shown == 0) 0.dp else GlyphSize * shown - GlyphOverlap * (shown - 1) +} diff --git a/feature/downloadmanager/src/main/kotlin/com/quran/mobile/feature/downloadmanager/ui/common/DownloadManagerToolbar.kt b/feature/downloadmanager/src/main/kotlin/com/quran/mobile/feature/downloadmanager/ui/common/DownloadManagerToolbar.kt index 1576b049cf..af0cc37d4d 100644 --- a/feature/downloadmanager/src/main/kotlin/com/quran/mobile/feature/downloadmanager/ui/common/DownloadManagerToolbar.kt +++ b/feature/downloadmanager/src/main/kotlin/com/quran/mobile/feature/downloadmanager/ui/common/DownloadManagerToolbar.kt @@ -6,10 +6,8 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import com.quran.labs.androidquran.common.ui.core.QuranIcons -import com.quran.labs.androidquran.common.ui.core.modifier.autoMirror @Composable fun DownloadManagerToolbar( @@ -29,8 +27,7 @@ fun DownloadManagerToolbar( IconButton(onClick = onBackPressed) { Icon( imageVector = QuranIcons.ArrowBack, - contentDescription = "", - modifier = Modifier.autoMirror() + contentDescription = "" ) } }, diff --git a/feature/linebyline/build.gradle.kts b/feature/linebyline/build.gradle.kts index dea8c8ede6..06b9574348 100644 --- a/feature/linebyline/build.gradle.kts +++ b/feature/linebyline/build.gradle.kts @@ -11,6 +11,7 @@ dependencies { implementation(project(":common:audio")) implementation(project(":common:bookmark")) implementation(project(":common:reading")) + implementation(project(":common:recitation")) implementation(project(":common:analytics")) implementation(project(":common:drawing")) implementation(project(":common:linebyline:ui")) diff --git a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/model/HighlightType.kt b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/model/HighlightType.kt index e3967ff24d..d4dd607365 100644 --- a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/model/HighlightType.kt +++ b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/model/HighlightType.kt @@ -1,5 +1,6 @@ package com.quran.labs.androidquran.extra.feature.linebyline.model +import androidx.annotation.ColorRes import com.quran.data.model.highlight.HighlightColor sealed interface HighlightType { @@ -9,4 +10,7 @@ sealed interface HighlightType { data object Bookmark : HighlightType data class Highlight(val color: HighlightColor) : HighlightType + + /** A mark of a recitation session (e.g. a mistake), drawn under the text in its own colors. */ + data class Recitation(@ColorRes val color: Int, @ColorRes val nightColor: Int) : HighlightType } diff --git a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/model/PageInfo.kt b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/model/PageInfo.kt index 244fb41676..7a11a7f627 100644 --- a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/model/PageInfo.kt +++ b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/model/PageInfo.kt @@ -1,6 +1,7 @@ package com.quran.labs.androidquran.extra.feature.linebyline.model import com.quran.data.model.PageAppearance +import com.quran.mobile.linebyline.data.dao.AyahHighlight import com.quran.mobile.linebyline.data.dao.AyahMarkerInfo import com.quran.mobile.linebyline.data.dao.SuraHeader import kotlinx.collections.immutable.ImmutableList @@ -19,7 +20,9 @@ data class PageInfo( val sidelines: ImmutableList, val targetScrollPosition: Int, val showSidelines: Boolean, - val skippedPageCount: Int + val skippedPageCount: Int, + // the parts of lines a recitation session hides (words not recited yet) + val hiddenRanges: ImmutableList = persistentListOf() ) val EmptySettings = diff --git a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/presenter/QuranLineByLinePresenter.kt b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/presenter/QuranLineByLinePresenter.kt index 49d8a4b4cb..ba28bca469 100644 --- a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/presenter/QuranLineByLinePresenter.kt +++ b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/presenter/QuranLineByLinePresenter.kt @@ -14,6 +14,8 @@ import com.quran.data.dao.Settings import com.quran.data.model.SuraAyah import com.quran.data.model.bookmark.AyahReadingBookmark import com.quran.data.model.highlight.Highlight +import com.quran.data.model.highlight.HighlightInfo +import com.quran.data.model.highlight.HighlightType as RecitationHighlightType import com.quran.data.model.selection.AyahSelection import com.quran.data.model.selection.SelectionIndicator import com.quran.data.model.selection.SelectionRectangle @@ -47,6 +49,10 @@ import com.quran.mobile.linebyline.data.model.PageModel import com.quran.mobile.mapper.imlaei.data.ImlaeiUthmaniMapper import com.quran.mobile.mapper.imlaei.data.WordAlignment import com.quran.reading.common.ReadingEventPresenter +import com.quran.recitation.presenter.RecitationHighlightsPresenter +import com.quran.recitation.presenter.RecitationHighlightsPresenter.HighlightAction +import com.quran.recitation.presenter.RecitationHighlightsPresenter.RecitationPage +import com.quran.recitation.presenter.RecitationPresenter import dev.zacsweers.metro.Inject import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf @@ -56,9 +62,13 @@ import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async +import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import java.io.File @@ -79,6 +89,8 @@ class QuranLineByLinePresenter @Inject constructor( private val crashReporter: CrashReporter, private val quranInfo: QuranInfo, private val imlaeiUthmaniMapper: ImlaeiUthmaniMapper, + private val recitationPresenter: RecitationPresenter, + private val recitationHighlightsPresenter: RecitationHighlightsPresenter, pages: IntArray ) { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) @@ -121,8 +133,9 @@ class QuranLineByLinePresenter @Inject constructor( return combine( pageSelection(), readingBookmarksForPage(), - lineByLineSettings.displaySettingsFlow - ) { highlights, readingBookmarks, displaySettings -> + lineByLineSettings.displaySettingsFlow, + recitationMarks() + ) { highlights, readingBookmarks, displaySettings, recitationMarks -> val displayText = DisplayText( quranPageInfo.suraName(page), quranPageInfo.juz(page), @@ -146,6 +159,7 @@ class QuranLineByLinePresenter @Inject constructor( } val pageDetails = pageDetailsFetcher.await() + val recitation = RecitationHighlights.of(recitationMarks, pageDetails.ayahBounds, pageDetails.wordBounds) PageInfo( page, pageProvider.pageType(), @@ -154,12 +168,13 @@ class QuranLineByLinePresenter @Inject constructor( pageDetails.lines, pageDetails.suraHeaders, pageDetails.ayahMarkers, - highlights, + (recitation.underText + highlights).toImmutableList(), readingBookmarks, sidelines, targetScrollPosition, showSidelines, - quranPageInfo.skippedPagesCount() + quranPageInfo.skippedPagesCount(), + recitation.hidden ) } } @@ -402,6 +417,38 @@ class QuranLineByLinePresenter @Inject constructor( .distinctUntilChanged() } + /** The marks of a recitation session (e.g. memorizing) on this page, while the page is shown. */ + private fun recitationMarks(): Flow> { + if (!recitationPresenter.isRecitationEnabled()) return flowOf(emptyList()) + return callbackFlow { + val marks = LinkedHashMap() + val recitationPage = object : RecitationPage { + override val pageNumbers = setOf(page) + + override fun applyHighlights(highlights: List) { + highlights.forEach { action -> + when (action) { + is HighlightAction.Highlight -> marks[action.highlightInfo.mark()] = action.highlightInfo + is HighlightAction.Unhighlight -> marks.remove(action.highlightInfo.mark()) + is HighlightAction.UnhighlightAll -> + if (action.page == null || action.page == page) { + marks.keys.removeAll { it.type == action.highlightType } + } + } + } + trySend(marks.values.toList()) + } + } + send(emptyList()) + recitationHighlightsPresenter.bind(recitationPage) + awaitClose { recitationHighlightsPresenter.unbind(recitationPage) } + }.flowOn(Dispatchers.Main) + } + + private data class RecitationMark(val sura: Int, val ayah: Int, val word: Int, val type: RecitationHighlightType) + + private fun HighlightInfo.mark() = RecitationMark(sura, ayah, word, highlightType) + private fun highlightsForPage(): Flow> { val range = quranInfo.getVerseRangeForPage(page) val startAyah = SuraAyah(range.startSura, range.startAyah) diff --git a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/presenter/RecitationHighlights.kt b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/presenter/RecitationHighlights.kt new file mode 100644 index 0000000000..e51c852abd --- /dev/null +++ b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/presenter/RecitationHighlights.kt @@ -0,0 +1,55 @@ +package com.quran.labs.androidquran.extra.feature.linebyline.presenter + +import com.quran.data.model.highlight.HighlightInfo +import com.quran.data.model.highlight.HighlightType.Mode.HIDE +import com.quran.labs.androidquran.extra.feature.linebyline.model.HighlightAyah +import com.quran.labs.androidquran.extra.feature.linebyline.model.HighlightType +import com.quran.mobile.linebyline.data.dao.AyahHighlight +import com.quran.mobile.linebyline.data.dao.WordHighlight +import com.quran.mobile.linebyline.data.dao.asAyahHighlight +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.toImmutableList + +/** + * A recitation session's marks on a line page: the hidden ones become parts of lines that are not + * drawn, the others are drawn under the text in their own colors. + */ +internal class RecitationHighlights( + val hidden: ImmutableList, + val underText: List +) { + companion object { + fun of( + marks: List, + ayahBounds: List, + wordBounds: List + ): RecitationHighlights { + val hidden = mutableListOf() + val underText = mutableListOf() + marks.forEach { mark -> + val bounds = bounds(mark, ayahBounds, wordBounds) + if (mark.highlightType.mode == HIDE) { + hidden += bounds + } else if (bounds.isNotEmpty()) { + val type = HighlightType.Recitation(mark.highlightType.colorResId, mark.highlightType.nightColorResId) + underText += HighlightAyah(type, bounds) + } + } + return RecitationHighlights(hidden.distinct().toImmutableList(), underText) + } + + // a word where the page has word bounds; otherwise its whole ayah, as layouts without them + // only have one box per ayah and line + private fun bounds( + mark: HighlightInfo, + ayahBounds: List, + wordBounds: List + ): List { + if (mark.word > 0) { + val words = wordBounds.filter { it.sura == mark.sura && it.ayah == mark.ayah } + if (words.isNotEmpty()) return listOfNotNull(words.getOrNull(mark.word - 1)?.asAyahHighlight()) + } + return ayahBounds.filter { it.sura == mark.sura && it.ayah == mark.ayah } + } + } +} diff --git a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/HighlightPainting.kt b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/HighlightPainting.kt index 127db05966..67555b02dd 100644 --- a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/HighlightPainting.kt +++ b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/HighlightPainting.kt @@ -1,15 +1,30 @@ package com.quran.labs.androidquran.extra.feature.linebyline.ui +import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.colorResource import com.quran.data.model.bookmark.ReadingBookmarkType import com.quran.labs.androidquran.common.ui.core.HighlightColors import com.quran.labs.androidquran.extra.feature.linebyline.model.HighlightType val HighlightType.isUnderText: Boolean - get() = this is HighlightType.Highlight + get() = this is HighlightType.Highlight || this is HighlightType.Recitation private const val NightHighlightAlpha = 0.40f +// as on image pages, whose night filter would otherwise make these marks glare +private const val NightRecitationAlpha = 0x66 / 255f + +@Composable +fun HighlightType.color(isNightMode: Boolean): Color { + return if (this is HighlightType.Recitation) { + val color = colorResource(if (isNightMode) nightColor else color) + if (isNightMode) color.copy(alpha = NightRecitationAlpha) else color + } else { + paintColor(isNightMode) + } +} + fun HighlightType.paintColor(isNightMode: Boolean): Color { return when (this) { HighlightType.Selection -> Color(0x46, 0x94, 0xa6, 0x40) @@ -20,6 +35,8 @@ fun HighlightType.paintColor(isNightMode: Boolean): Color { val paletteColor = HighlightColors[color].color if (isNightMode) paletteColor.copy(alpha = NightHighlightAlpha) else paletteColor } + // a resource: see color() + is HighlightType.Recitation -> Color.Unspecified } } @@ -28,5 +45,10 @@ fun ReadingBookmarkType.paintColor(isNightMode: Boolean): Color { ReadingBookmarkType.TEAL -> if (isNightMode) Color(0xFF4DB6AC) else Color(0xFF00897B) ReadingBookmarkType.ORANGE -> if (isNightMode) Color(0xFFFFB74D) else Color(0xFFEF6C00) ReadingBookmarkType.RED -> if (isNightMode) Color(0xFFE57373) else Color(0xFFC62828) + ReadingBookmarkType.GREEN -> if (isNightMode) Color(0xFF81C784) else Color(0xFF2E7D32) + ReadingBookmarkType.BLUE -> if (isNightMode) Color(0xFF64B5F6) else Color(0xFF1565C0) + ReadingBookmarkType.PURPLE -> if (isNightMode) Color(0xFFBA68C8) else Color(0xFF6A1B9A) + ReadingBookmarkType.BROWN -> if (isNightMode) Color(0xFFA1887F) else Color(0xFF6D4C41) + ReadingBookmarkType.GREY -> if (isNightMode) Color(0xFF90A4AE) else Color(0xFF546E7A) } } diff --git a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/QuranLine.kt b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/QuranLine.kt index 566f6d2f70..eaa3e5a2a5 100644 --- a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/QuranLine.kt +++ b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/QuranLine.kt @@ -5,11 +5,16 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.ClipOp import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.clipPath import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize +import com.quran.mobile.linebyline.data.dao.AyahHighlight import kotlin.math.floor @Composable @@ -19,7 +24,9 @@ fun QuranLine( lineRatio: Float, colorFilter: ColorFilter, drawDivider: Boolean, - lineColor: Color + lineColor: Color, + // parts of the line not to draw (left and right as fractions of its width) + hidden: List = emptyList() ) { Canvas(modifier = Modifier.fillMaxSize()) { val totalWidth = this.size.width @@ -28,12 +35,23 @@ fun QuranLine( val lineHeight = totalWidth * lineRatio val lastLineIndex = 14f val y = floor((totalHeight - lineHeight) / lastLineIndex * lineId).toInt() - drawImage( - image = image, - dstOffset = IntOffset(0, y), - dstSize = IntSize(totalWidth.toInt(), lineHeight.toInt()), - colorFilter = colorFilter - ) + val drawLineImage = { + drawImage( + image = image, + dstOffset = IntOffset(0, y), + dstSize = IntSize(totalWidth.toInt(), lineHeight.toInt()), + colorFilter = colorFilter + ) + } + if (hidden.isEmpty()) { + drawLineImage() + } else { + // the whole height of this line's image: lines overlap, but each is drawn on its own + val hiddenParts = Path().apply { + hidden.forEach { addRect(Rect(it.left * totalWidth, y.toFloat(), it.right * totalWidth, y + lineHeight)) } + } + clipPath(hiddenParts, ClipOp.Difference) { drawLineImage() } + } if (drawDivider) { drawLine(lineColor, start = Offset(0f, y.toFloat()), end = Offset(totalWidth, y.toFloat())) diff --git a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/QuranPage.kt b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/QuranPage.kt index d9b3a23945..ce3fcc0bac 100644 --- a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/QuranPage.kt +++ b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/QuranPage.kt @@ -83,7 +83,7 @@ fun QuranPage( pageInfo.ayahHighlights .filter { it.highlightType.isUnderText } .forEach { highlightAyah -> - val color = highlightAyah.highlightType.paintColor(isNightMode) + val color = highlightAyah.highlightType.color(isNightMode) highlightAyah.ayahHighlights.forEach { highlightComposable(it, color) } } @@ -140,7 +140,7 @@ fun QuranPage( highlightAyah.ayahHighlights.any { it.lineId == lineId } } highlights.forEach { highlightAyah -> - val color = highlightAyah.highlightType.paintColor(isNightMode) + val color = highlightAyah.highlightType.color(isNightMode) highlightAyah.ayahHighlights .filter { it.lineId == lineId } .forEach { diff --git a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/QuranPageWrapper.kt b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/QuranPageWrapper.kt index 6a16adf20f..b20846c2d9 100644 --- a/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/QuranPageWrapper.kt +++ b/feature/linebyline/src/main/java/com/quran/labs/androidquran/extra/feature/linebyline/ui/QuranPageWrapper.kt @@ -148,7 +148,8 @@ fun QuranPageWrapper( ratio, colorFilter = colorFilter, displaySettings.showLineDividers && shouldShowLineFor(pageInfo.page, it.lineId), - lineColor + lineColor, + hidden = pageInfo.hiddenRanges.filter { hidden -> hidden.lineId == it.lineId } ) }, suraHeaderComposable = { diff --git a/feature/linebyline/src/test/java/com/quran/labs/androidquran/extra/feature/linebyline/presenter/RecitationHighlightsTest.kt b/feature/linebyline/src/test/java/com/quran/labs/androidquran/extra/feature/linebyline/presenter/RecitationHighlightsTest.kt new file mode 100644 index 0000000000..b066a2618a --- /dev/null +++ b/feature/linebyline/src/test/java/com/quran/labs/androidquran/extra/feature/linebyline/presenter/RecitationHighlightsTest.kt @@ -0,0 +1,57 @@ +package com.quran.labs.androidquran.extra.feature.linebyline.presenter + +import com.google.common.truth.Truth.assertThat +import com.quran.data.model.highlight.HighlightInfo +import com.quran.labs.androidquran.extra.feature.linebyline.model.HighlightAyah +import com.quran.mobile.linebyline.data.dao.AyahHighlight +import com.quran.mobile.linebyline.data.dao.WordHighlight +import org.junit.Test +import com.quran.data.model.highlight.HighlightType as RecitationType +import com.quran.labs.androidquran.extra.feature.linebyline.model.HighlightType as LineType + +class RecitationHighlightsTest { + + private val hidden = RecitationType(1001, 1, RecitationType.Mode.HIDE) + private val mistake = RecitationType(1002, 2, RecitationType.Mode.UNDERLAY, nightColorResId = 3) + + // 1:1 on the first line, 1:2 over the end of it and the second line + private val ayah1 = AyahHighlight(1, 1, 1, 1, lineId = 0, left = 0.5f, right = 1f) + private val ayah2Line0 = AyahHighlight(2, 1, 1, 2, lineId = 0, left = 0f, right = 0.5f) + private val ayah2Line1 = AyahHighlight(2, 1, 1, 2, lineId = 1, left = 0.2f, right = 1f) + private val ayahBounds = listOf(ayah1, ayah2Line0, ayah2Line1) + + @Test + fun `a hidden ayah leaves out its parts of lines`() { + val result = RecitationHighlights.of(listOf(mark(1, 2, -1, hidden)), ayahBounds, emptyList()) + assertThat(result.hidden).containsExactly(ayah2Line0, ayah2Line1) + assertThat(result.underText).isEmpty() + } + + @Test + fun `without word bounds a word is hidden and marked with its whole ayah`() { + val marks = listOf(mark(1, 2, 3, hidden), mark(1, 2, 4, hidden), mark(1, 2, 3, mistake)) + val result = RecitationHighlights.of(marks, ayahBounds, emptyList()) + assertThat(result.hidden).containsExactly(ayah2Line0, ayah2Line1) + assertThat(result.underText).containsExactly(HighlightAyah(LineType.Recitation(2, 3), listOf(ayah2Line0, ayah2Line1))) + } + + @Test + fun `with word bounds a word is hidden alone`() { + val words = listOf( + WordHighlight(1, 1, 0, 1, 2, 1, left = 0.3f, right = 0.5f), + WordHighlight(2, 1, 0, 1, 2, 2, left = 0f, right = 0.3f), + ) + val result = RecitationHighlights.of(listOf(mark(1, 2, 2, hidden)), ayahBounds, words) + assertThat(result.hidden).containsExactly(AyahHighlight(2, 1, 1, 2, 0, 0f, 0.3f)) + } + + @Test + fun `marks of ayat elsewhere are not drawn`() { + val result = RecitationHighlights.of(listOf(mark(2, 1, -1, hidden), mark(2, 1, 1, mistake)), ayahBounds, emptyList()) + assertThat(result.hidden).isEmpty() + assertThat(result.underText).isEmpty() + } + + private fun mark(sura: Int, ayah: Int, word: Int, type: RecitationType) = + HighlightInfo(sura, ayah, word, type, scrollToAyah = false) +} diff --git a/feature/memorize/MODEL_LICENSE b/feature/memorize/MODEL_LICENSE new file mode 100644 index 0000000000..defd34f974 --- /dev/null +++ b/feature/memorize/MODEL_LICENSE @@ -0,0 +1,148 @@ +Quran-Lab No-Profit License +Version 1.2 (NPL-1.2) + +Copyright (c) 2026 Muno459 / Quran-Lab + +This work, including its source code, specification documents, data +artifacts, token lexicon, generated labels, model weights, and any file +distributed alongside it (the "Work"), is made available under the following +terms. By downloading, using, running, copying, or adapting the Work, you agree +to these terms. If you do not agree, you may not use the Work. + +Changes from Version 1.1: the condition is now stated as attaching to the Work +itself rather than to the user or their organisation. Charging for the Work, for +access to it, or for any feature it powers remains prohibited. Earning a living +by your own labour alongside the Work is not restricted, and was never intended +to be. Section 13 states plainly that this License is not a ruling on anyone's +livelihood. Version 1.1 removed the attribution requirement; that remains so. + +1. DEFINITIONS + + "You" means the individual or entity exercising rights under this License. + + "Derivative" means any work based on the Work, including any + modification, fork, port, translation, format conversion, or re-export, + any dataset, lexicon, label set, or artifact produced from the Work, + any machine-learning model trained, fine-tuned, aligned, or evaluated + using the Work or its outputs, and any model, file, or artifact + produced from the Work or from another Derivative. + + "Charge" means requiring or accepting payment of any kind for the Work, for + access to the Work, or for any feature, capability, or output that the Work + provides. This includes sale, licensing for a fee, rental, a paid product or + feature, a paid subscription, a paywall, a trial that later requires payment, + and advertising revenue earned on a feature the Work powers. + + "Hosted Service" means making the Work or a Derivative available to other + people over a network, for example through an API, a web application, or an + inference endpoint. + + "Local Use" means running the Work or a Derivative on your own device or + infrastructure, for yourself or for those you teach or serve directly, + without making it available to other people over a network. + + "Cost Recovery" means charging the users of a Hosted Service no more than + the actual, documented, strictly necessary direct costs of operating that + service for those users, such as compute, storage, and bandwidth. Cost + Recovery does not include any margin, markup, profit, salaries beyond + direct operation, or overhead unrelated to running the service. + +2. GRANT + + Subject to the conditions below, You are granted a worldwide, royalty-free, + non-exclusive, non-transferable license to use, run, copy, and create + Derivatives of the Work. + +3. THE WORK IS NOT FOR SALE + + You may not Charge for the Work or for any Derivative. It may not be sold, + licensed for a fee, rented, or supplied for payment, and neither the Work nor + any feature it powers may be placed behind a payment, a subscription, a + paywall, or advertising. + + This condition attaches to the Work, not to You. Your own labour remains your + own. A teacher may charge for teaching, a developer may draw a salary, and an + organisation may earn from products, services and activities that do not + include the Work or any feature it powers. What may never be charged for is + the Work itself, access to it, or a feature that depends on it. + +4. LOCAL USE + + Local Use is always permitted and is never a Charge. Running the Work on your + own device, for yourself or for your own students, is not selling it, and + nothing in this License restricts payment You receive for your own teaching, + services, or labour, so long as the Work itself is not what is being sold and + no one is charged for access to it or to a feature it powers. + +5. HOSTED SERVICE: COST RECOVERY ONLY + + You may operate the Work or a Derivative as a Hosted Service free of charge, + or on a Cost Recovery basis. You may recover from users no more than Cost + Recovery as defined above, and never any amount beyond it. On reasonable + request, You must be able to demonstrate that the amounts charged do not + exceed Cost Recovery. + + Cost Recovery covers the cost of running the Work for a user. It does not + cover development time, effort, expertise, support, or a service fee, and no + user may be denied the Work for declining to pay. + +6. NO ATTRIBUTION REQUIRED + + No credit, acknowledgement, or attribution to the author is required, in any + form, anywhere. You must retain this License file when you distribute the + Work or a Derivative (see Section 7), but you owe the author no mention. + +7. SHARE-ALIKE + + You must distribute and make available every Derivative under this same + License, either Version 1.2 or any later version published by Quran-Lab, with + no additional or different terms. You may not sublicense the Work or a + Derivative under any other license, and You may not relicense a Derivative to + remove or weaken these terms. + +8. UPSTREAM COMPONENTS + + Where this Work builds on upstream components released under other terms, + those components retain their own terms for their original portions, and + this License governs the Work as distributed in this repository. Nothing + here purports to revoke any rights granted by an upstream license for the + original upstream material. Any upstream components are identified in the + repository README. + +9. NO COMMERCIAL LICENSE + + There is no license to Charge for this Work, and none will be granted. The + right to sell the Work, to place it or a feature it powers behind a payment, + or to charge for access to it, is not available for a fee, a revenue share, a + one-time payment, or any other arrangement. + +10. TERMINATION + + Any use that breaches these terms immediately and automatically ends the + rights granted to You under this License. + +11. NO WARRANTY + + The Work is provided "as is", without warranty of any kind, express or + implied, including but not limited to the warranties of merchantability, + fitness for a particular purpose, and noninfringement. In no event shall + the authors or copyright holders be liable for any claim, damages, or other + liability arising from or in connection with the Work or its use. + +12. NOT LEGAL ADVICE + + This License text sets out the author's terms of use for the Work. It is + not, and does not constitute, legal advice. + +13. NOT A RULING ON ANYONE'S LIVELIHOOD + + This License states the conditions on which this Work is given. It is not a + ruling on anyone's livelihood, and nothing in it says that taking a wage for + teaching the Quran, or for any other lawful work, is impermissible. + +--- + +This work is shared freely for the sake of Allah, so that it reaches as many +people as possible and so that whoever builds on it does so as sadaqah. + + وَما أَسأَلُكُم عَلَيهِ مِن أَجرٍ إِن أَجرِيَ إِلّا عَلىٰ رَبِّ العالَمِين diff --git a/feature/memorize/README.md b/feature/memorize/README.md new file mode 100644 index 0000000000..8259e2d96e --- /dev/null +++ b/feature/memorize/README.md @@ -0,0 +1,249 @@ +# Memorize (احفظ) and the prayer corrector (مصحح الصلاة) + +Recite from memory with the mushaf page open: the words of the passage are hidden and appear as +they are recited correctly. A wrong word is marked (not shown); if the reciter is stuck, the next +word is given, one word at a time, in a reciter's voice. The same corrector works hands-free during +salah, with the screen off. A session goes on into the next suras (as in taraweeh) until the user +ends it. + +**Recitation** (تلاوة) is the same session with the text shown: the user reads from the page and +nothing is hidden. The words read get a light trail (the app's accent), so the reader sees where the +session follows them; a wrong or skipped word is marked, and after the hint delay the correct word +is said in the hint voice. There is no help when the reader stops: the next word is in front of +them. "Recitation: mark mistakes" and "Recitation: say the correct word" turn either off; the trail +is always there. + +A floating mic on the reading screen starts a session (green), shows when it listens (blue) and +pauses, resumes or ends it. Tapping it (or the audio bar's mic, or "Recite from here") opens a +window: Memorization or Recitation, and where the session starts; a long press adds salah. The +toolbar's "Memorize" starts memorizing at once. The words are hidden as soon as a memorization +starts, and the user may begin anywhere from three pages before the page on screen to three after +it: once the start is found the words before it are shown again. Reciting something that isn't +there marks the first word on screen (and, while memorizing, gives it after the delay). + +**Everything runs on the device.** Audio is processed in memory and dropped; nothing is sent, and +nothing is recorded unless the user turns on "Record my recitation" or "Record and contribute" (both +off by default). Recordings stay in the app's no-backup storage and only leave the phone if the user +exports them. When a session ends, Progress keeps what it came to: the passage, the mode, when and +how long, and how many words of each ayah were recited, given, missed or marked (no audio and no +words heard). It stays on the device; Settings > Progress turns it off and clears it. +The only network use is the one-time download of the speech model and, if the user agrees (or turns +on automatic downloads), the hint reciter's sura audio through the app's normal audio downloads. + +## How it works + +``` +microphone (16 kHz, VOICE_RECOGNITION) ─► speech engine (sherpa-onnx, streaming zipformer2-CTC, +phoneme output) ─► RecitationTracker (aligns the phonemes with the expected words) ─► HintScheduler +(when to give a word) ─► MemorizeState ─► page masks + spoken hints (PromptPlayer) +``` + +* `:feature:memorize:tracker` — pure Kotlin, no Android: `PhonemeNormalizer`, `RecitationTracker` + (weighted semi-global alignment; repetition, re-sync after misheard words, recovery when the user + skips ahead, phrases that aren't part of the passage such as isti'adha/basmala/takbir), + `SalahFlow` (Al-Fatiha and prayer phrases are ignored; hints only while the passage is recited; + the passage continues in the next rak'ah), `HintScheduler` (mark → wait → one word → wait → ...). + The tracker is a port of the reference implementation used to benchmark the models; the golden + tests in `src/test/resources/golden` keep the two identical. +* `:feature:memorize:engine-sherpa` — the only module with native code (sherpa-onnx AAR, fetched by + `tools/memorize/fetch_sherpa_onnx.sh`, SHA-256 pinned). +* `:feature:memorize` — plugs into the app's recitation slot (`common:recitation`) instead of + `:feature:recitation`'s stubs: session controller, microphone foreground service, page masks, + hint audio, settings, model download/import. + +When a word is given (`HintScheduler`, delay T from the settings, 4 s by default): + +| | on screen | in salah (spoken hints) | +|---|---|---| +| wrong word | marked at once; a word T later | a word T later, once the reciter pauses (not over them) | +| stuck mid-ayah | after T without progress and 2 s of silence | same | +| stuck between ayat (before an ayah, or on its last word) | after T | after 2 × T (a pause there is often ruku; the takbir disarms hints) | +| the same word wrong again | at the reciter's next pause, without waiting for T | same | +| still stuck after 3 single words | the rest of the ayah if no longer than the line, else the rest of the line | same | +| no answer after 10 hints | stops until the reciter recites a word | same | + +Pages: every page type is the same text in its own font, so which glyphs are words is worked out +for the page type in use from its own glyph boxes (`GlyphTypes`: the text gives the words and the +hizb/sajdah markers, the font's shortest glyphs are its waqf marks — this reproduces the madani +pages' types exactly for all 6,236 ayat at every width). Marks are backgrounds under the words +(red: mistake, teal: hinted, amber: skipped) so colored (tajweed) mushafs keep their colors. +Word by word needs a box per glyph: the Madani and Tajweed page types have them. The newer Madani +prints (1421, 1440, and the 1439/1441 line-by-line ones) and the Shemerly print only have a box per +ayah and line, so there each ayah is hidden until all of it has been recited, and marks cover the +whole ayah. Shemerly's ayat that run on to the next page are hidden on both pages. + +Recordings (opt-in): a recording per sura or per session, named by where it starts and ends, played +back from the audio bar or the floating mic (the page follows), and exported as a .zip: the audio +(16 kHz AAC), `alignment.json` (every word with its time from the recognizer, whether it was +recited, hinted or missed, how many times a mistake was marked on it, and its phonemes) and a NeMo +`manifest.jsonl` of the ayat recited entirely, cut before any hint (see `RecordingFormat`, version +2; version 1 files still read). + +**Record and contribute** records every session (whatever "Record my recitation" says) to help +improve the speech models; turning it on explains what is kept, and nothing is sent. Its recordings +also keep `.heard.jsonl` (`heard.jsonl` in an export, see `RecordingDetails`): the session's +settings, speech model, app version and phone, then one line per token the model heard (its time, +text and confidence) and per thing the app decided (mistakes, marks shown and cleared, hints, +repetitions, phrases, double-check verdicts, speech and silence, the hint voice playing, pauses, +calls), in the recording's time. The model's input features (80-dim fbank) aren't kept: they come +from the audio and would take more room than it. Each detail goes to the per-sura recording that +holds the audio it is about, written once the recognizer can't report more for it. + +**Recording sessions** (Settings) lists the sessions by day, with their mode, range and length and +whether they were contributed; a row swipes away (with Undo), and all can be exported or deleted. A +session opens in a window that plays it back on its own mushaf pages, without going to them in the +reader: the page turns with the word being heard, which is lit with a trail behind it, hints, +skipped words and mistakes are marked, and tapping a word plays from it. The app draws those pages +(`PagePreviews` in `common/recitation`, implemented in `:app`), as the reading screen does. + +**No ayah is left out** (Memorization; Recitation too). The tracker knows which ayah each word is +in. A user who goes on to a later ayah without reciting one is held at its first word: nothing +after it is revealed, the word is marked as a mistake and given after the hint delay, then the next, +until they are back; after ten hints in a row, or once the hint delay is over when no hint will +give the word (mistake hints off; Recitation without "say the correct word"), the session follows +them on and marks what they left out as skipped. Before holding, it checks what it heard: if there was speech where the words +should be (said but misheard, e.g. a noisy stretch), they are passed over and marked as skipped; +only words with nothing heard for them count as left out. Settings, "Words missed inside a verse": +"Let a word or two pass" (default; never more than half an ayah) or "Every word must be heard" +(misheard words hold too). In salah ayat may still be left out (that is how a rak'ah picks the +passage up again). + +**Restarts and similar ayat** (every mode). Going back to the start of the ayah being recited is a +repetition, not a mistake; when lost, a restart behind is preferred to a jump ahead, so ayat that +open alike (2:149 and 2:150) or share a phrase (2:144 and 2:150) no longer pull the session forward. +At the start, while what is heard is the same word for word at two places on the pages around, the +session waits for the words that tell them apart. + +In salah any phrase of ruku/sujud (takbir, tasmi', tahmid, tasbeeh, tasleem) ends the passage of the +rak'ah; hints resume when the passage continues after the next Al-Fatiha. A pause is 0.8 s of +silence or 1.5 s without anything new recognized (loud mosques are never silent). The speech +stream is restarted only in real silence: never in a held madd. + +The pages are images, so words are hidden by clipping their glyphs out (`HighlightType.Mode.HIDE`). +The madani ayahinfo databases have no glyph types; `MadaniGlyphTypeResolver` supplies them from +`assets/memorize/glyph_types_madani_v1.txt` and the app derives word-level glyphs +(`AyahCoordinates.wordGlyphCoordinates`) that are only used for word keys and hiding, so existing +highlights are unchanged. + +## Bundled data (regenerate with `tools/memorize/`) + +| asset | script | notes | +|---|---|---| +| `memorize/glyph_types_madani_v1.txt` | `build_glyph_types.py` | glyph type per position for all 6,236 ayat; identical for every ayahinfo width | +| `memorize/lexicon_v1.db` | `build_lexicon.py --compact` | pronunciation of all 77,433 words (in context and alone) + prayer phrases, from [quran-transcript](https://github.com/obadx/quran-transcript) (MIT) | +| `memorize/timings/husary_murattal_wbw_v1.db` | `align_timing_pack.py` | word timings of the app's Husary sura files, by forced alignment | +| `memorize/timings/husary_mujawwad_wbw_v1.db` | `align_timing_pack.py` + `merge_timing_packs.py` | same for Husary Mujawwad | +| `memorize/timings/husary_muallim_wbw_v1.db` | `align_timing_pack.py` + `merge_timing_packs.py --truncated 4:33` | same for Husary Muallim; the upstream 004.mp3 stops in 4:34, so hints after 4:33 are shown without audio | + +Word numbering everywhere is the page's glyph word numbering (`WordGlyph.wordPosition`). + +## Speech model + +One model: Quran-Lab's streaming Zipformer2-CTC phoneme recognizer **zipformer_p-arabic-v3.1**, int8 +(69 MB) — +(`zipformer_p_arabic_v3.1.int8.onnx` and `tokens.txt` at commit `3da514fc`; the repository is +gated). The app downloads the byte-identical files once from an ungated mirror, + (`quran-stt-int8.onnx`, pinned to commit +`51ec9bcd` and checked by SHA-256 in `SpeechModelSpec`), or imports them for a setup without +internet (Settings → Recitation model → Import files: pick `quran-stt-int8.onnx` and `tokens.txt` +one at a time, or the .zip they came in; files are recognized by their SHA-256, whatever their +name). Settings → Download for offline use gets the model and the hint voice for the whole Quran at +once. + +License: Quran-Lab No-Profit License 1.2, included verbatim in [MODEL_LICENSE](MODEL_LICENSE) +(Copyright (c) 2026 Muno459 / Quran-Lab). It allows free use, adaptation and redistribution, forbids +charging for the model or for any feature it powers, and its access terms ask applications to state +that automatic feedback can be wrong and does not replace a qualified teacher (shown before the +first session). The engine interface is model-agnostic; another model can be swapped in. + +### Optional: the double-check + +The setting is Settings → Double-check before correcting. It is off by default and needs a 92 MB +download. Before a hint is spoken, a second, larger model listens again to the last 8 seconds the +user said. It does the same a second after a mistake, before the mark is shown. If the word was said +after all, nothing is corrected. The word must be in that model's transcript, within a quarter of +its letters, right after the word before it. A dropped hint counts the word as recited. + +* **What it changes.** In the lab (`REPORT.md` §15): + * false hints in mosque prayers: −28 %, and −43 % while the passage is being recited; + * clips from users' phones (tlog) with false mistake marks: −57 %; + * reveal recall is unchanged; + * in 400 real stalls, the hint was never wrongly dropped. +* **The model.** muhdur's Tilawi FastConformer, + (CC-BY-4.0), pinned to commit `e9448a0e` and checked by SHA-256 (`DoubleCheckModel.SPEC`). + * The app downloads `fastconformer_full_mixed.onnx`, `vocab.json` and `quran.json`. + * It runs on the sherpa-onnx already in the app, so the APK grows by nothing. + * It runs in a process of its own (`DoubleCheckService`). With sherpa-onnx 1.13.8, a second model + in the speech engine's process corrupts the engine's state. On a Mi 11 the session went deaf + for 20–45 s after a check. + * `CheckGraph` adapts the graph once, on the phone: it adds three nodes for the input sherpa + gives, and the weights are untouched. The result is byte-identical to the lab's conversion with + onnx (`bench/tilawi_rename.py`) and is checked by its SHA-256. +* **The Quran text.** `quran.json` holds the Tanzil Quran text (CC BY 3.0, verbatim). Its + plain-letter form is only used to compare with what the model writes, and is never shown. The + comparison rules (`CheckText`) reproduce the lab's tables for all 1,025 pieces and 77,433 words. +* **Which phones.** The model needs about 300 MB more memory while the user recites. + * The setting recommends itself on phones with about 6 GB of memory or more and a 64-bit + processor. + * Once it has run, the time a check takes on the phone decides: it is not recommended above + 1.5 s, because hints would come late. + * Where it is recommended, it is also offered with the recitation model's first download and in + Download for offline use. + +## Tests + +* `./gradlew :feature:memorize:tracker:test` — tracker golden parity, salah flow, hint scheduler. +* `./gradlew :feature:memorize:testReleaseUnitTest` — page masks, word timings, and the session + controller with a scripted engine (hints, salah disarming, start/stop races, start failures), + recordings (splits, pauses, details, dropped audio). With `-Pmemorize.render`, + `MemorizeScreensRenderTest` draws the mode window and the Recording sessions screens to + `build/outputs/memorize-renders` (light and dark, English and Arabic, phone and tablet). +* `./gradlew :app:testMadaniDebugUnitTest --tests '*WordGlyphs*'` — derived word glyphs. +* `tools/memorize/run_device_benchmark.sh testlab|adb [engine|session] [MODEL,VERSION ...]` — on real + phones (Firebase Test Lab or USB): `engine` = speed and memory of the recognizer at 1/2/4 threads, + `session` = whole memorization sessions fed in real time with 26 clips — Husary and 8 other + professional reciters and styles (QUD, CC-BY-4.0), non-professional readers incl. real wording + mistakes (sobolev210, MIT) and non-native readers of 8 countries (RetaSy) — measuring per clip and + per group how much is revealed, mistakes, hints and how soon after each word is said it appears. + The model and the audio are staged into the test APKs by `tools/memorize/stage_test_clips.py` + (`build/memorize-testlab`, never committed). + + Results (Test Lab, 2026-10-22): + + | phone | engine, 2 threads | model load | session: revealed / hints / mistakes | reveal latency p50 / p90 / max | + |---|---|---|---|---| + | Galaxy A10 (2019 low end, Android 10) | 0.42 × real time | 7.3 s | 60 / 0 / 0 of 60 words | 0.34 / 0.63 / 2.6 s | + | Galaxy S21 (Snapdragon 888, as the Mi 11) | 0.07 × real time | 2.1 s | 60 / 0 / 0 | 0.16 / 0.46 / 2.5 s | + | virtual Arm phone, Android 14 and 16 KB-page Android 16 | 0.05–0.07 | 1.1–2.0 s | 60 / 0 / 0 | 0.13–0.15 / 0.44–0.46 / 2.5 s | + + Native memory ~105–150 MB. The microphone starts before the model has loaded, so nothing said + during those seconds is lost: on the A10 listening starts after 0.2 s and the words said while the + model loads appear once it's ready (latency p50 / p90 / max 0.43 / 2.65 / 6.3 s, still 60/60). + A Robo crawl of the app found no crash. + +### Diagnostics + +When a session doesn't follow, it can say why. `adb shell setprop log.tag.MemorizeTrace DEBUG` +turns on its trace from the next session start, and `adb logcat -s MemorizeTrace` shows it. The +trace includes: + +* what the recognizer heard, and when the user is speaking or silent; +* every start search: the confident words and the best run found; +* salah phases (Al-Fatiha, passage, between rak'ahs); +* recognized words, mistakes and phrases; +* the hint scheduler's decisions; +* a status line every 10 s. + +It is off by default and logs nothing otherwise. A session trace contains what was recited, as +text, so it is only for development. + +## Known limitations + +* Hafs only (the Warsh and Qaloon qira'at aren't covered by the model or the lexicon). Ayah by ayah, + not word by word, on page types without word boxes (see Pages). Recognition degrades on heavily reverberant/noisy audio. On real prayer + recordings from mosques (evaluation T6, 3 hours) passages are followed with 97.6 % recall; false + spoken hints per 10 minutes: 0 (Masjid an-Nabawi, qiyam), 1–2 (Masjid al-Haram, UK mosques), + 3 (Indonesian/Pakistani imams), 5 (local mosques with loudspeakers). Where loudspeakers garble the + ruku/sujud phrases (Al-Aqsa) hints can come between rak'ahs; at most 10 in a row. +* Salah mode follows the passage the user picked; reciting a different sura is treated as mistakes. +* Hints need the hint reciter's sura audio to be downloaded; otherwise they are only shown. diff --git a/feature/memorize/build.gradle.kts b/feature/memorize/build.gradle.kts new file mode 100644 index 0000000000..7cda042d5e --- /dev/null +++ b/feature/memorize/build.gradle.kts @@ -0,0 +1,67 @@ +plugins { + id("quran.android.library.compose") + alias(libs.plugins.metro) +} + +android { + namespace = "com.quran.mobile.feature.memorize" + defaultConfig { + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + // the session tests read the bundled lexicon + testOptions.unitTests.isIncludeAndroidResources = true + // library modules only build release; the on-device session test runs against it + testBuildType = "release" +} + +// the speech model and test audio for on-device tests, staged by +// tools/memorize/run_device_benchmark.sh (not in git); without the model the tests download it +androidComponents { + onVariants { variant -> + (variant as? com.android.build.api.variant.HasDeviceTests)?.deviceTests?.values?.forEach { + it.sources.assets?.addStaticSourceDirectory(rootProject.file("build/memorize-testlab").path) + } + } +} + +// -Pmemorize.render: MemorizeScreensRenderTest draws the feature's screens to +// build/outputs/memorize-renders (light, dark, Arabic; phone and tablet) to look at them +tasks.withType().configureEach { + if (providers.gradleProperty("memorize.render").isPresent) systemProperty("memorize.render", "true") +} + +dependencies { + implementation(project(":common:data")) + implementation(project(":common:di")) + implementation(project(":common:progress")) + implementation(project(":common:download")) + implementation(project(":common:pages")) + implementation(project(":common:recitation")) + implementation(project(":common:ui:core")) + implementation(project(":feature:memorize:tracker")) + implementation(project(":feature:memorize:engine-sherpa")) + + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.appcompat) + implementation(libs.compose.animation) + implementation(libs.compose.foundation) + implementation(libs.compose.material3) + implementation(libs.compose.ui) + implementation(libs.androidx.annotation) + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.media3.exoplayer) + implementation(libs.androidx.preference.ktx) + implementation(libs.kotlinx.coroutines.android) + implementation(libs.kotlinx.coroutines.core) + + testImplementation(libs.junit) + testImplementation(libs.truth) + testImplementation(libs.robolectric) + testImplementation(libs.androidx.junit) + testImplementation(libs.kotlinx.coroutines.test) + testImplementation(libs.turbine) + + androidTestImplementation(libs.androidx.test.runner) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.truth) +} diff --git a/feature/memorize/engine-sherpa/build.gradle.kts b/feature/memorize/engine-sherpa/build.gradle.kts new file mode 100644 index 0000000000..c9aacc4468 --- /dev/null +++ b/feature/memorize/engine-sherpa/build.gradle.kts @@ -0,0 +1,33 @@ +plugins { + id("quran.android.library.android") +} + +android { + namespace = "com.quran.mobile.feature.memorize.engine.sherpa" + defaultConfig { + consumerProguardFiles("consumer-rules.pro") + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + // library modules only build release; the on-device benchmark runs against it + testBuildType = "release" +} + +// the speech model and test audio for on-device tests, staged by +// tools/memorize/run_device_benchmark.sh (not in git); without the model the tests download it +androidComponents { + onVariants { variant -> + (variant as? com.android.build.api.variant.HasDeviceTests)?.deviceTests?.values?.forEach { + it.sources.assets?.addStaticSourceDirectory(rootProject.file("build/memorize-testlab").path) + } + } +} + +dependencies { + api(project(":feature:memorize:tracker")) + // the only module with native code; see tools/memorize/fetch_sherpa_onnx.sh + implementation(libs.sherpa.onnx) + + androidTestImplementation(libs.androidx.test.runner) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.truth) +} diff --git a/feature/memorize/engine-sherpa/consumer-rules.pro b/feature/memorize/engine-sherpa/consumer-rules.pro new file mode 100644 index 0000000000..19b80a7dfe --- /dev/null +++ b/feature/memorize/engine-sherpa/consumer-rules.pro @@ -0,0 +1,2 @@ +# sherpa-onnx's native code reads and creates these classes (and their fields) through JNI by name. +-keep class com.k2fsa.sherpa.onnx.** { *; } diff --git a/feature/memorize/engine-sherpa/src/androidTest/AndroidManifest.xml b/feature/memorize/engine-sherpa/src/androidTest/AndroidManifest.xml new file mode 100644 index 0000000000..ffdc789967 --- /dev/null +++ b/feature/memorize/engine-sherpa/src/androidTest/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/feature/memorize/engine-sherpa/src/androidTest/kotlin/com/quran/mobile/feature/memorize/engine/sherpa/SherpaEngineBenchmarkTest.kt b/feature/memorize/engine-sherpa/src/androidTest/kotlin/com/quran/mobile/feature/memorize/engine/sherpa/SherpaEngineBenchmarkTest.kt new file mode 100644 index 0000000000..4b7f98dd2f --- /dev/null +++ b/feature/memorize/engine-sherpa/src/androidTest/kotlin/com/quran/mobile/feature/memorize/engine/sherpa/SherpaEngineBenchmarkTest.kt @@ -0,0 +1,147 @@ +package com.quran.mobile.feature.memorize.engine.sherpa + +import android.os.Bundle +import android.os.Debug +import android.util.Log +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.google.common.truth.Truth.assertThat +import com.quran.mobile.feature.memorize.tracker.PhonemeNormalizer +import com.quran.mobile.feature.memorize.tracker.RecitationTracker +import com.quran.mobile.feature.memorize.tracker.TimedPhoneme +import com.quran.mobile.feature.memorize.tracker.TrackerEvent +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import java.net.URL +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.security.MessageDigest + +/** + * On-device benchmark of the speech engine (run on real phones, e.g. Firebase Test Lab): + * recognition speed (real-time factor) for 1, 2 and 4 threads, native memory, and whether the + * tracker follows a known recitation. Results are reported as instrumentation status and in logcat + * (tag MemorizeBenchmark). + */ +@RunWith(AndroidJUnit4::class) +class SherpaEngineBenchmarkTest { + + private val context = InstrumentationRegistry.getInstrumentation().targetContext + private val testContext = InstrumentationRegistry.getInstrumentation().context + + @Test + fun benchmark() { + val (model, tokens) = modelFiles() + val audio = loadWav("fatiha_husary_30s.wav") + val results = Bundle() + + for (threads in listOf(1, 2, 4)) { + val heapBefore = Debug.getNativeHeapAllocatedSize() + val loadStart = System.nanoTime() + val engine = SherpaRecitationEngine(model, tokens, threads) + val loadMs = (System.nanoTime() - loadStart) / 1e6 + val stream = engine.newStream() + + val tracker = RecitationTracker(FATIHA.map { PhonemeNormalizer.normalize(it, false) }, phrases = PHRASES) + val recited = mutableListOf() + val chunk = 1_600 // 100 ms, as the microphone delivers it + var worstChunkMs = 0.0 + val start = System.nanoTime() + var offset = 0 + while (offset < audio.size) { + val count = minOf(chunk, audio.size - offset) + val t0 = System.nanoTime() + val tokensOut = stream.accept(audio.copyOfRange(offset, offset + count)) + worstChunkMs = maxOf(worstChunkMs, (System.nanoTime() - t0) / 1e6) + val phonemes = tokensOut.flatMap { token -> + PhonemeNormalizer.normalize(token.text, false).map { TimedPhoneme(it, token.timeMs) } + } + tracker.feed(phonemes).filterIsInstance().forEach { recited += it.index } + offset += count + } + stream.finish() + val seconds = (System.nanoTime() - start) / 1e9 + val rtf = seconds / (audio.size / 16_000.0) + val heapMb = (Debug.getNativeHeapAllocatedSize() - heapBefore) / 1e6 + stream.close() + engine.close() + + val line = "threads=$threads rtf=%.3f load_ms=%.0f worst_chunk_ms=%.1f native_heap_mb=%.1f words=%d/%d" + .format(rtf, loadMs, worstChunkMs, heapMb, recited.size, FATIHA.size) + Log.i(TAG, line) + results.putString("threads_$threads", line) + + // 30 s of Husary covers the isti'adha and the first ayat of Al-Fatiha + assertThat(recited.take(8)).containsExactly(0, 1, 2, 3, 4, 5, 6, 7).inOrder() + assertThat(rtf).isLessThan(1.0) + } + InstrumentationRegistry.getInstrumentation().sendStatus(0, results) + } + + private fun modelFiles(): Pair { + val directory = File(context.cacheDir, "memorize-benchmark").apply { mkdirs() } + val model = modelFile(directory, "quran-stt-int8.onnx", MODEL_SHA256) + val tokens = modelFile(directory, "tokens.txt", TOKENS_SHA256) + return model to tokens + } + + /** From the test's assets when the run bundled the model (as in Test Lab), else downloaded. */ + private fun modelFile(directory: File, name: String, sha256: String): File { + val file = File(directory, name) + if (!file.exists() || sha(file) != sha256) { + val bundled = testContext.assets.list("").orEmpty().contains(name) + val input = if (bundled) { + testContext.assets.open(name) + } else { + URL("$MODEL_BASE/$name").openConnection().apply { + connectTimeout = 30_000 + readTimeout = 60_000 + }.getInputStream() + } + input.use { source -> file.outputStream().use { source.copyTo(it) } } + } + assertThat(sha(file)).isEqualTo(sha256) + return file + } + + private fun sha(file: File): String { + val digest = MessageDigest.getInstance("SHA-256") + file.inputStream().use { input -> + val buffer = ByteArray(1 shl 16) + while (true) { + val read = input.read(buffer) + if (read < 0) break + digest.update(buffer, 0, read) + } + } + return digest.digest().joinToString("") { "%02x".format(it) } + } + + /** 16 kHz mono 16-bit PCM WAV -> floats in [-1, 1]. */ + private fun loadWav(asset: String): FloatArray { + val bytes = testContext.assets.open(asset).use { it.readBytes() } + val buffer = ByteBuffer.wrap(bytes, WAV_HEADER, bytes.size - WAV_HEADER).order(ByteOrder.LITTLE_ENDIAN) + return FloatArray((bytes.size - WAV_HEADER) / 2) { buffer.short / 32_768f } + } + + private companion object { + const val TAG = "MemorizeBenchmark" + const val WAV_HEADER = 44 + const val MODEL_BASE = + "https://huggingface.co/Saboorhsn/quran-stt-onnx/resolve/51ec9bcddeaf1c480bbe39064a2a3b88bc2ff224" + const val MODEL_SHA256 = "31755836528da336a6192121cd7bc82cb41752dddb65566fd000b89c8686da6b" + const val TOKENS_SHA256 = "252c10687e442aa9291973065fae19fa39bcd681c4f5612ec496a647e20b43a1" + + // Al-Fatiha as pronounced (lexicon_v1, in context) + val FATIHA = listOf( + "بِسمِ", "للَااهِ", "ررَحمَاانِ", "ررَحِۦۦۦۦم", "ءَلحَمدُ", "لِللَااهِ", "رَببِ", "لعَاالَمِۦۦۦۦن", + "ءَررَحمَاانِ", "ررَحِۦۦۦۦم", "مَاالِكِ", "يَومِ", "ددِۦۦۦۦن", "ءِييَااكَ", "نَعبُدُ", "وَءِييَااكَ", + "نَستَعِۦۦۦۦن", "ءِهدِنَ", "صصِرَااطَ", "لمُستَقِۦۦۦۦم", "صِرَااطَ", "للَذِۦۦنَ", "ءَنعَمتَ", "عَلَيهِم", + "غَيرِ", "لمَغضُۥۥبِ", "عَلَيهِم", "وَلَ", "ضضَااااااللِۦۦۦۦن", + ) + val PHRASES = listOf( + "isti'adha" to PhonemeNormalizer.normalize("ءَعُۥۥذُ بِللَااهِ مِنَ ششَيطَاانِ ررَجِۦۦۦۦم", false) + ) + } +} diff --git a/feature/memorize/engine-sherpa/src/main/kotlin/com/quran/mobile/feature/memorize/engine/sherpa/SherpaPieceRecognizer.kt b/feature/memorize/engine-sherpa/src/main/kotlin/com/quran/mobile/feature/memorize/engine/sherpa/SherpaPieceRecognizer.kt new file mode 100644 index 0000000000..e997dd33cc --- /dev/null +++ b/feature/memorize/engine-sherpa/src/main/kotlin/com/quran/mobile/feature/memorize/engine/sherpa/SherpaPieceRecognizer.kt @@ -0,0 +1,45 @@ +package com.quran.mobile.feature.memorize.engine.sherpa + +import com.k2fsa.sherpa.onnx.FeatureConfig +import com.k2fsa.sherpa.onnx.OfflineModelConfig +import com.k2fsa.sherpa.onnx.OfflineOmnilingualAsrCtcModelConfig +import com.k2fsa.sherpa.onnx.OfflineRecognizer +import com.k2fsa.sherpa.onnx.OfflineRecognizerConfig +import java.io.File + +/** + * An offline (whole clip) CTC model on raw audio, run by the sherpa-onnx already in the app: the + * pieces it hears, as ids. [tokens] names piece i "p" (see bench/tilawi_for_sherpa.py). + */ +class SherpaPieceRecognizer(model: File, tokens: File, numThreads: Int = 2) : AutoCloseable { + private val recognizer = OfflineRecognizer( + null, + OfflineRecognizerConfig( + featConfig = FeatureConfig(sampleRate = SAMPLE_RATE, featureDim = 80), + modelConfig = OfflineModelConfig( + omnilingual = OfflineOmnilingualAsrCtcModelConfig(model.path), + tokens = tokens.path, + numThreads = numThreads, + provider = "cpu", + ), + ), + ) + + /** The pieces heard in [audio] (16 kHz mono), blanks and repeats collapsed. */ + fun pieces(audio: FloatArray): IntArray { + val stream = recognizer.createStream() + try { + stream.acceptWaveform(audio, SAMPLE_RATE) + recognizer.decode(stream) + return recognizer.getResult(stream).tokens.map { it.removePrefix("p").toInt() }.toIntArray() + } finally { + stream.release() + } + } + + override fun close() = recognizer.release() + + private companion object { + const val SAMPLE_RATE = 16_000 + } +} diff --git a/feature/memorize/engine-sherpa/src/main/kotlin/com/quran/mobile/feature/memorize/engine/sherpa/SherpaRecitationEngine.kt b/feature/memorize/engine-sherpa/src/main/kotlin/com/quran/mobile/feature/memorize/engine/sherpa/SherpaRecitationEngine.kt new file mode 100644 index 0000000000..9f8c7cadfa --- /dev/null +++ b/feature/memorize/engine-sherpa/src/main/kotlin/com/quran/mobile/feature/memorize/engine/sherpa/SherpaRecitationEngine.kt @@ -0,0 +1,109 @@ +package com.quran.mobile.feature.memorize.engine.sherpa + +import com.k2fsa.sherpa.onnx.FeatureConfig +import com.k2fsa.sherpa.onnx.OnlineModelConfig +import com.k2fsa.sherpa.onnx.OnlineRecognizer +import com.k2fsa.sherpa.onnx.OnlineRecognizerConfig +import com.k2fsa.sherpa.onnx.OnlineStream +import com.k2fsa.sherpa.onnx.OnlineZipformer2CtcModelConfig +import com.quran.mobile.feature.memorize.tracker.engine.RecitationEngine +import com.quran.mobile.feature.memorize.tracker.engine.RecitationStream +import com.quran.mobile.feature.memorize.tracker.engine.RecognizedToken +import java.io.File + +/** + * Runs a streaming Zipformer2-CTC phoneme model with sherpa-onnx, entirely on the device. + * + * @param model the int8 ONNX model file + * @param tokens the model's symbol table (tokens.txt) + */ +class SherpaRecitationEngine(model: File, tokens: File, numThreads: Int = 2) : RecitationEngine { + + private val recognizer = OnlineRecognizer( + assetManager = null, + config = OnlineRecognizerConfig( + featConfig = FeatureConfig(sampleRate = SAMPLE_RATE, featureDim = 80), + modelConfig = OnlineModelConfig( + zipformer2Ctc = OnlineZipformer2CtcModelConfig(model = model.absolutePath), + tokens = tokens.absolutePath, + numThreads = numThreads, + provider = "cpu", + ), + // Not sherpa's endpointing: it measures silence as frames without new tokens, which is also + // what a held madd looks like, and starting over there cuts the end of the word. + enableEndpoint = false, + decodingMethod = "greedy_search", + ) + ) + + override fun newStream(): RecitationStream = SherpaStream(recognizer) + + override fun close() { + recognizer.release() + } + + private class SherpaStream(private val recognizer: OnlineRecognizer) : RecitationStream { + private val stream: OnlineStream = recognizer.createStream() + private var emitted = 0 + private var samplesFed = 0L + // audio time (ms) at which the stream was last reset; result timestamps are relative to it + private var segmentStartMs = 0L + private var silentSamples = 0L + private var lastTokenAt = 0L + + override fun accept(samples: FloatArray, count: Int, speech: Boolean): List { + stream.acceptWaveform(if (count == samples.size) samples else samples.copyOf(count), SAMPLE_RATE) + samplesFed += count + silentSamples = if (speech) 0 else silentSamples + count + return decode() + } + + override fun finish(): List { + stream.inputFinished() + return decode() + } + + private fun decode(): List { + while (recognizer.isReady(stream)) { + recognizer.decode(stream) + } + val result = recognizer.getResult(stream) + val tokens = ArrayList(result.tokens.size - emitted) + for (i in emitted until result.tokens.size) { + val timeMs = segmentStartMs + (result.timestamps.getOrElse(i) { 0f } * 1000).toLong() + tokens += RecognizedToken(result.tokens[i], timeMs, result.ysProbs.getOrNull(i)) + } + emitted = result.tokens.size + if (tokens.isNotEmpty()) lastTokenAt = samplesFed + if (shouldStartOver()) { + recognizer.reset(stream) + emitted = 0 + segmentStartMs = samplesFed * 1000 / SAMPLE_RATE + } + return tokens + } + + /** + * Starting over keeps the results (and memory) from growing for the whole session, at the cost + * of the model's context, so it is done in real silence only. + */ + private fun shouldStartOver(): Boolean { + if (emitted == 0) return false + val sinceToken = samplesFed - lastTokenAt + return (silentSamples >= QUIET_SAMPLES && sinceToken >= QUIET_SAMPLES) || + // audio that never goes quiet (e.g. a mosque's loudspeakers): rarely, after a long gap + (emitted >= MAX_SEGMENT_TOKENS && sinceToken >= LONG_GAP_SAMPLES) + } + + override fun close() { + stream.release() + } + } + + private companion object { + const val SAMPLE_RATE = 16_000 + const val QUIET_SAMPLES = 2L * SAMPLE_RATE + const val LONG_GAP_SAMPLES = 3L * SAMPLE_RATE + const val MAX_SEGMENT_TOKENS = 1_500 + } +} diff --git a/feature/memorize/src/androidTest/AndroidManifest.xml b/feature/memorize/src/androidTest/AndroidManifest.xml new file mode 100644 index 0000000000..054d5cdf6d --- /dev/null +++ b/feature/memorize/src/androidTest/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/feature/memorize/src/androidTest/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckOnDeviceTest.kt b/feature/memorize/src/androidTest/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckOnDeviceTest.kt new file mode 100644 index 0000000000..7b9ec028c7 --- /dev/null +++ b/feature/memorize/src/androidTest/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckOnDeviceTest.kt @@ -0,0 +1,169 @@ +package com.quran.mobile.feature.memorize.check + +import android.app.ActivityManager +import android.os.Bundle +import android.os.SystemClock +import android.util.Log +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.google.common.truth.Truth.assertThat +import com.quran.data.model.SuraAyah +import com.quran.mobile.feature.memorize.data.LexiconRepository +import com.quran.mobile.feature.memorize.engine.sherpa.SherpaRecitationEngine +import com.quran.mobile.feature.memorize.model.SpeechModelStore +import kotlinx.coroutines.runBlocking +import org.json.JSONObject +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/** + * The double-check on a device, as the app runs it: + * - its model is downloaded as published and converted on the device; + * - it is loaded in a process of its own; + * - it hears words of Al-Husary's Al-Mulk 1–5; + * - and the speech engine hears the same as without it while checks run next to it. + * + * The last is the corruption that made the check move to its own process. Results go to logcat + * (tag MemorizeDoubleCheck) and to the instrumentation status. + */ +@RunWith(AndroidJUnit4::class) +class DoubleCheckOnDeviceTest { + + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val context = instrumentation.targetContext + + @Test + fun checksInItsOwnProcessWithoutDisturbingTheSpeechEngine() { + val speech = SpeechModelStore(context) + installSpeechModel(speech) + + // downloaded and converted the way the app does it + val store = SpeechModelStore.of(context, DoubleCheckModel.SPEC) + val downloadStarted = SystemClock.elapsedRealtime() + if (!store.isInstalled()) { + store.startDownload() + val deadline = downloadStarted + 15 * 60_000 + while (store.state.value is SpeechModelStore.State.Downloading && SystemClock.elapsedRealtime() < deadline) { + SystemClock.sleep(500) + } + } + val downloadSeconds = (SystemClock.elapsedRealtime() - downloadStarted) / 1000.0 + assertThat(store.state.value).isEqualTo(SpeechModelStore.State.Installed) + + val model = DoubleCheckModel.forTest(store) { file, tokens -> RemotePieceRecognizer(context, file, tokens) } + val loadStarted = SystemClock.elapsedRealtime() + val check = requireNotNull(model.open()) { "the double-check didn't load" } + val loadSeconds = (SystemClock.elapsedRealtime() - loadStarted) / 1000.0 + val processes = context.getSystemService(ActivityManager::class.java).runningAppProcesses.orEmpty().map { it.processName } + assertThat(processes).contains("${context.packageName}:doublecheck") + + val audio = loadWav("mulk_1_5_husary.wav") + val ends = wordEnds() + val lexicon = LexiconRepository(context) + val mulk = runBlocking { lexicon.passage(SuraAyah(67, 1)) } + val ikhlas = runBlocking { lexicon.passage(SuraAyah(112, 1)) } + + // the speech engine on its own + val alone = recognize(speech, audio, check = null) + + // checks: words said in the last seconds are found, a word from elsewhere isn't + val said = listOf(5, 12, 20, 33, 47).associateWith { k -> check.said(lastSeconds(audio, ends[k] + 300), mulk, k) } + val elsewhere = check.said(lastSeconds(audio, ends[20] + 300), ikhlas, 2) + val checkMs = check.lastMs + + // the speech engine again, with a check every 10 s of audio next to it, as in a session + val withChecks = recognize(speech, audio, check = { heard -> check.said(heard, mulk, 0) }) + check.close() + + val status = Bundle().apply { + putString("download", "%.1f s, %d MB".format(downloadSeconds, DoubleCheckModel.SPEC.downloadSize / 1_000_000)) + putString("load", "%.1f s".format(loadSeconds)) + putString("said", said.entries.joinToString { "${it.key}=${it.value}" } + " elsewhere=$elsewhere") + putString("check_ms", checkMs.toString()) + putString("engine", "alone=${alone.length} letters, with checks=${withChecks.length}, same=${alone == withChecks}") + } + for (key in status.keySet()) Log.i(TAG, "$key: ${status.getString(key)}") + instrumentation.sendStatus(0, status) + + assertThat(said.values.count { it }).isAtLeast(4) + assertThat(elsewhere).isFalse() + assertThat(withChecks).isEqualTo(alone) + } + + /** What the speech engine hears of [audio] (100 ms frames), running [check] every 10 s. */ + private fun recognize(models: SpeechModelStore, audio: FloatArray, check: ((FloatArray) -> Unit)?): String { + val engine = SherpaRecitationEngine(models.modelFile, models.tokensFile) + val stream = engine.newStream() + val out = StringBuilder() + var frame = 0 + while (frame * FRAME < audio.size) { + val samples = audio.copyOfRange(frame * FRAME, minOf(audio.size, (frame + 1) * FRAME)) + stream.accept(samples, samples.size, speech = true).forEach { out.append(it.text) } + frame++ + if (check != null && frame % 100 == 0) check(lastSeconds(audio, frame * 100L)) + } + stream.finish().forEach { out.append(it.text) } + stream.close() + engine.close() + return out.toString() + } + + private fun lastSeconds(audio: FloatArray, untilMs: Long): FloatArray { + val end = minOf(audio.size, (untilMs * SAMPLE_RATE / 1000).toInt()) + return audio.copyOfRange(maxOf(0, end - 8 * SAMPLE_RATE), end) + } + + private fun wordEnds(): List { + val json = instrumentation.context.assets.open("clips/manifest.json").use { String(it.readBytes()) } + val clip = JSONObject(json).getJSONArray("clips").getJSONObject(0) + check(clip.getString("file") == "mulk_1_5_husary.wav") + val ends = clip.getJSONArray("word_ends_ms") + return (0 until ends.length()).map { ends.getLong(it) } + } + + /** From the test's assets when the run bundled the model (as in Test Lab), else downloaded. */ + private fun installSpeechModel(models: SpeechModelStore) { + if (models.isInstalled()) return + val bundled = instrumentation.context.assets.list("").orEmpty().toSet() + val directory = models.modelFile.parentFile!!.apply { mkdirs() } + for (file in models.spec.files) { + if (file.name !in bundled) continue + instrumentation.context.assets.open(file.name).use { input -> + File(directory, file.name).outputStream().use { input.copyTo(it) } + } + } + if (models.isInstalled()) return + models.startDownload() + val deadline = SystemClock.elapsedRealtime() + 10 * 60_000 + while (models.state.value is SpeechModelStore.State.Downloading && SystemClock.elapsedRealtime() < deadline) { + SystemClock.sleep(500) + } + assertThat(models.state.value).isEqualTo(SpeechModelStore.State.Installed) + } + + /** 16 kHz mono 16-bit PCM WAV. */ + private fun loadWav(name: String): FloatArray { + val bytes = instrumentation.context.assets.open(name).use { it.readBytes() } + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + var offset = 12 + while (offset + 8 <= bytes.size) { + val id = String(bytes, offset, 4, Charsets.US_ASCII) + val size = buffer.getInt(offset + 4) + if (id == "data") { + val pcm = ByteBuffer.wrap(bytes, offset + 8, size).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer() + return FloatArray(pcm.remaining()) { pcm.get(it) / 32_768f } + } + offset += 8 + size + (size and 1) + } + error("no audio in $name") + } + + private companion object { + const val TAG = "MemorizeDoubleCheck" + const val SAMPLE_RATE = 16_000 + const val FRAME = SAMPLE_RATE / 10 + } +} diff --git a/feature/memorize/src/androidTest/kotlin/com/quran/mobile/feature/memorize/session/MemorizeSessionOnDeviceTest.kt b/feature/memorize/src/androidTest/kotlin/com/quran/mobile/feature/memorize/session/MemorizeSessionOnDeviceTest.kt new file mode 100644 index 0000000000..eefc319c70 --- /dev/null +++ b/feature/memorize/src/androidTest/kotlin/com/quran/mobile/feature/memorize/session/MemorizeSessionOnDeviceTest.kt @@ -0,0 +1,289 @@ +package com.quran.mobile.feature.memorize.session + +import android.os.Bundle +import android.os.SystemClock +import android.util.Log +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.google.common.truth.Truth.assertThat +import com.quran.data.model.SuraAyah +import com.quran.mobile.feature.memorize.audio.AudioSource +import com.quran.mobile.feature.memorize.audio.AudioSourceFactory +import com.quran.mobile.feature.memorize.audio.EnergyVoiceActivity +import com.quran.mobile.feature.memorize.data.LexiconRepository +import com.quran.mobile.feature.memorize.engine.sherpa.SherpaRecitationEngine +import com.quran.mobile.feature.memorize.model.SpeechModelStore +import com.quran.mobile.feature.memorize.prompt.HintVoice +import com.quran.mobile.feature.memorize.settings.MemorizePreferences +import com.quran.mobile.feature.memorize.tracker.WordId +import com.quran.recitation.events.RecitationEventPresenter +import org.json.JSONObject +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.concurrent.atomic.AtomicInteger +import kotlin.math.roundToInt + +/** + * Whole memorization sessions on a real phone, one per clip of clips/manifest.json (staged by + * tools/memorize/stage_test_clips.py): professional reciters of different styles, non-professional + * readers and non-native readers. Each clip is played into the session in real time, as the + * microphone would deliver it, through the real speech engine, tracker and hint scheduler. + * + * Reports per clip and per group how much of what was recited is revealed, the mistakes marked and + * hints given, and how long after a word is said it appears. Results go to logcat (tag + * MemorizeSession) and to the instrumentation status (e.g. Firebase Test Lab). + */ +@RunWith(AndroidJUnit4::class) +class MemorizeSessionOnDeviceTest { + + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val context = instrumentation.targetContext + + private class Clip( + val file: String, + val group: String, + val label: String, + val start: SuraAyah, + val words: Int, + /** When each of the [words] ends in the clip (its first recitation), when known. */ + val wordEndsMs: List?, + /** "complete", "mistake" (a wrong word or ayah should be caught) or "incomplete". */ + val expect: String, + ) + + private class Outcome(val clip: Clip, val revealed: Int, val mistakes: Int, val hints: Int, val latencies: List) { + val complete get() = revealed == clip.words + val asExpected + get() = when (clip.expect) { + "complete" -> complete + "mistake" -> mistakes > 0 || !complete + else -> !complete + } + } + + @Test + fun followsDifferentReaders() { + val models = SpeechModelStore(context) + installModel(models) + val preferences = MemorizePreferences(context).apply { + correctorEnabled = true + hintDelaySeconds = 4 + } + val source = ClipSource() + val controller = MemorizeSessionController( + lexicon = LexiconRepository(context), + models = models, + preferences = preferences, + recitationEventPresenter = RecitationEventPresenter(), + engineFactory = { SherpaRecitationEngine(it.modelFile, it.tokensFile) }, + promptPlayer = RecordingVoice(), + audioSources = source, + callState = { false }, + lines = { emptyMap() }, + upcoming = {}, + recorders = { _, _, _, _ -> null }, + doubleChecks = { null }, + results = {}, + ) + + val outcomes = clips().map { clip -> session(controller, source, clip) } + + val status = Bundle() + outcomes.forEachIndexed { i, outcome -> + val line = outcome.describe() + Log.i(TAG, line) + status.putString("clip_%02d".format(i + 1), line) + } + for ((group, results) in outcomes.groupBy { it.clip.group }) { + val expectedComplete = results.filter { it.clip.expect == "complete" } + val words = expectedComplete.sumOf { it.clip.words } + val revealed = expectedComplete.sumOf { it.revealed } + val latencies = results.flatMap { it.latencies }.sorted() + val line = ("group=%s clips=%d as_expected=%d/%d revealed=%d/%d (%.1f%%) mistakes=%d hints=%d " + + "latency_p50=%.2fs latency_p90=%.2fs late_frames=%d") + .format( + group, results.size, results.count { it.asExpected }, results.size, revealed, words, + 100.0 * revealed / maxOf(words, 1), results.sumOf { it.mistakes }, results.sumOf { it.hints }, + latencies.percentile(0.5), latencies.percentile(0.9), source.late.get(), + ) + Log.i(TAG, line) + status.putString("group_$group", line) + } + instrumentation.sendStatus(0, status) + + // professional recitation is followed almost entirely; the other groups are measured, not judged + val professional = outcomes.filter { it.clip.group == "professional" } + assertThat(professional.sumOf { it.revealed }.toDouble() / professional.sumOf { it.clip.words }).isAtLeast(0.9) + } + + /** Runs one session on [clip] and measures it. */ + private fun session(controller: MemorizeSessionController, source: ClipSource, clip: Clip): Outcome { + source.next(loadWav(clip.file)) + val revealedAt = HashMap() + var mistakes = 0 + var lastMistake: Int? = null + instrumentation.runOnMainSync { controller.start(clip.start) } + while (!source.finished) { + val state = controller.state.value + if (state != null) { + val now = SystemClock.elapsedRealtime() + for (i in 0 until minOf(state.cursor, clip.words)) if (i !in revealedAt) revealedAt[i] = now + if (state.mistake != null && state.mistake != lastMistake) mistakes++ + lastMistake = state.mistake + } + SystemClock.sleep(10) + } + val hinted = controller.state.value?.hinted.orEmpty().filter { it < clip.words }.toSet() + instrumentation.runOnMainSync { controller.stop() } + + val latencies = clip.wordEndsMs?.let { ends -> + (0 until clip.words).mapNotNull { i -> + val at = revealedAt[i] ?: return@mapNotNull null + if (i in hinted) null else (at - (source.startedAt + ends[i])) / 1000.0 + } + }.orEmpty() + val revealed = (0 until clip.words).count { it in revealedAt && it !in hinted } + return Outcome(clip, revealed, mistakes, hinted.size, latencies) + } + + private fun Outcome.describe(): String { + val sorted = latencies.sorted() + val latency = if (sorted.isEmpty()) "" else { + " latency_p50=%.2fs latency_p90=%.2fs".format(sorted.percentile(0.5), sorted.percentile(0.9)) + } + return "clip=%s group=%s start=%d:%d revealed=%d/%d mistakes=%d hints=%d expect=%s ok=%b%s label=\"%s\"".format( + clip.file.substringAfterLast('/'), clip.group, clip.start.sura, clip.start.ayah, revealed, clip.words, + mistakes, hints, clip.expect, asExpected, latency, clip.label, + ) + } + + private fun List.percentile(p: Double): Double = + if (isEmpty()) Double.NaN else this[((size - 1) * p).roundToInt()] + + private fun clips(): List { + val json = instrumentation.context.assets.open("clips/manifest.json").use { String(it.readBytes()) } + val list = JSONObject(json).getJSONArray("clips") + return (0 until list.length()).map { i -> + val c = list.getJSONObject(i) + val ends = c.optJSONArray("word_ends_ms") + Clip( + file = c.getString("file"), + group = c.getString("group"), + label = c.getString("label"), + start = SuraAyah(c.getInt("sura"), c.getInt("ayah")), + words = c.getInt("words"), + wordEndsMs = ends?.let { a -> (0 until a.length()).map { a.getLong(it) } }, + expect = c.getString("expect"), + ) + } + } + + /** From the test's assets when the run bundled the model (as in Test Lab), else downloaded. */ + private fun installModel(models: SpeechModelStore) { + if (models.isInstalled()) return + val bundled = instrumentation.context.assets.list("").orEmpty().toSet() + val directory = models.modelFile.parentFile!!.apply { mkdirs() } + for (file in models.spec.files) { + if (file.name !in bundled) continue + instrumentation.context.assets.open(file.name).use { input -> + File(directory, file.name).outputStream().use { input.copyTo(it) } + } + } + if (models.isInstalled()) return + models.startDownload() + val deadline = SystemClock.elapsedRealtime() + 10 * 60_000 + while (models.state.value is SpeechModelStore.State.Downloading && SystemClock.elapsedRealtime() < deadline) { + SystemClock.sleep(500) + } + assertThat(models.state.value).isEqualTo(SpeechModelStore.State.Installed) + } + + /** 16 kHz mono 16-bit PCM WAV. */ + private fun loadWav(name: String): FloatArray { + val bytes = instrumentation.context.assets.open(name).use { it.readBytes() } + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + var offset = 12 // "RIFF" size "WAVE" + while (offset + 8 <= bytes.size) { + val id = String(bytes, offset, 4, Charsets.US_ASCII) + val size = buffer.getInt(offset + 4) + if (id == "data") { + val pcm = ByteBuffer.wrap(bytes, offset + 8, size).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer() + return FloatArray(pcm.remaining()) { pcm.get(it) / 32_768f } + } + offset += 8 + size + (size and 1) + } + error("no audio in $name") + } + + /** + * Plays the current clip in 100 ms frames at the pace of a real microphone, from the moment the + * session starts listening, then 3 s of silence. + */ + private class ClipSource : AudioSourceFactory { + @Volatile var finished = false + @Volatile var startedAt = 0L + // frames the audio thread itself couldn't deliver on time (the phone was too busy) + val late = AtomicInteger() + private var audio = FloatArray(0) + + fun next(clip: FloatArray) { + audio = clip + finished = false + } + + override fun create(onFrame: (FloatArray, Int, Boolean) -> Unit, onError: (Throwable) -> Unit): AudioSource { + val audio = audio + return object : AudioSource { + @Volatile private var running = false + + override fun start() { + running = true + Thread({ + val vad = EnergyVoiceActivity() + val frames = audio.size / FRAME + (TRAILING_SILENCE_MS / 100).toInt() + startedAt = SystemClock.elapsedRealtime() + for (k in 0 until frames) { + if (!running) break + // keep to the clock, like a microphone: a slow consumer can't slow the audio down + val due = startedAt + k * 100L + val wait = due - SystemClock.elapsedRealtime() + if (wait > 0) SystemClock.sleep(wait) else if (wait < -100) late.incrementAndGet() + val frame = FloatArray(FRAME) + val from = k * FRAME + if (from < audio.size) System.arraycopy(audio, from, frame, 0, minOf(FRAME, audio.size - from)) + onFrame(frame, FRAME, vad.isSpeech(frame, FRAME)) + } + finished = true + }, "clip-audio").start() + } + + override fun stop() { + running = false + } + } + } + } + + /** Records the hints instead of playing them. */ + private class RecordingVoice : HintVoice { + private class Words(val words: List) : HintVoice.Clip + + override fun prepare(qariId: Int, words: List): HintVoice.Clip = Words(words) + + override fun play(clip: HintVoice.Clip, onStarted: () -> Unit, onFinished: () -> Unit) { + onStarted() + onFinished() + } + + override fun stop() {} + } + + private companion object { + const val TAG = "MemorizeSession" + const val FRAME = 1_600 + const val TRAILING_SILENCE_MS = 3_000L + } +} diff --git a/feature/memorize/src/main/AndroidManifest.xml b/feature/memorize/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..26322aed80 --- /dev/null +++ b/feature/memorize/src/main/AndroidManifest.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/feature/memorize/src/main/assets/memorize/glyph_types_madani_v1.txt b/feature/memorize/src/main/assets/memorize/glyph_types_madani_v1.txt new file mode 100644 index 0000000000..bc47440bfc --- /dev/null +++ b/feature/memorize/src/main/assets/memorize/glyph_types_madani_v1.txt @@ -0,0 +1,6236 @@ +1 1 wwwwe +1 2 wwwwe +1 3 wwe +1 4 wwwe +1 5 wwwwe +1 6 wwwe +1 7 wwwwwwwwwe +2 1 we +2 2 wwwwpwpwwe +2 3 wwwwwwwwe +2 4 wwwwwwwwwwwwe +2 5 wwwwwpwwwe +2 6 wwwwwwwwwwwe +2 7 wwwwwwpwwwpwwwe +2 8 wwwwwwwwwwwe +2 9 wwwwwwwwwwe +2 10 wwwwwwpwwwwwwe +2 11 wwwwwwwwwwwe +2 12 wwwwwwwe +2 13 wwwwwwwwwwwwpwwwwwwwe +2 14 wwwwwwwwwwwwwwwwe +2 15 wwwwwwwe +2 16 wwwwwwwwwwwe +2 17 wwwwwwwwwwwwwwwwwe +2 18 wwwwwwe +2 19 wwwwwwwwwwwwwwwwpwwwe +2 20 wwwwpwwwwwwwwwpwwwwwwpwwwwwwe +2 21 wwwwwwwwwwwe +2 22 wwwwwwwwwwwwwwwwwpwwwwwwe +2 23 wwwwwwwwwwwwwwwwwwwwe +2 24 wwwwwwwwwwwpwwe +2 25 wwwwwwwwwwwwpwwwwwwpwwwwwwpwwwpwwwwpwwwe +2 26 hwwwwwwwwwwwpwwwwwwwwpwwwwwwwwwpwwwwwwpwwwwwe +2 27 wwwwwwwwwwwwwwwwwpwwwe +2 28 wwwwwwpwwwwwwwe +2 29 wwwwwwwwwwwwwwwpwwwwe +2 30 wwwwwwwwwpwwwwwwwwwwwwwpwwwwwwe +2 31 wwwwwwwwwwwwwwwe +2 32 wwwwwwwwpwwwwe +2 33 wwwwpwwwwwwwwwwwwwwwwwwe +2 34 wwwwwwwwwwwwwe +2 35 wwwwwwwwwwwwwwwwwwe +2 36 wwwwwwwpwwwwwpwwwwwwwe +2 37 wwwwwwwpwwwwe +2 38 wwwwpwwwwwwwwwwwwwe +2 39 wwwwwwwpwwwe +2 40 wwwwwwwwwwwwwe +2 41 wwwwwwwwwwwpwwwwwwwe +2 42 wwwwwwwwe +2 43 wwwwwwwe +2 44 hwwwwwwwwpwwe +2 45 wwwpwwwwwe +2 46 wwwwwwwwe +2 47 wwwwwwwwwwwe +2 48 wwwwwwwwwwwwwwwwwwwe +2 49 wwwwwwwwwwwwpwwwwwwe +2 50 wwwwwwwwwwe +2 51 wwwwwwwwwwwwe +2 52 wwwwwwwwe +2 53 wwwwwwwe +2 54 wwwwwwwwwwwwwwwwwwwwwwpwwwwe +2 55 wwwwwwwwwwwwwwe +2 56 wwwwwwwe +2 57 wwwwwwwpwwwwwpwwwwwwe +2 58 wwwwwwwwwwwwwwwwwwpwwe +2 59 wwwwwwwwwwwwwwwwwwe +2 60 hwwwwwwwwpwwwwwpwwwwwpwwwwwwwwwwe +2 61 wwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwpwwwwwwpwwwwwwwwpwwwwwwwwwwpwwwwwe +2 62 wwwwwwwwwwwwwwwwwwwwwwwwe +2 63 wwwwwwwwwwwwwwwe +2 64 wwwwwpwwwwwwwwe +2 65 wwwwwwwwwwwwe +2 66 wwwwwwwwwe +2 67 wwwwwwwwwwpwwwpwwwwwwwe +2 68 wwwwwwwwpwwwwwwwwwwwwpwwwe +2 69 wwwwwwwwpwwwwwwwwwwe +2 70 wwwwwwwwwwwwwwwwwe +2 71 wwwwwwwwwwwwwwwwpwwwwpwwwwe +2 72 wwwwwpwwwwwe +2 73 wwwpwwwwwwwwe +2 74 wwwwwwwwwwwpwwwwwwwpwwwwwwwpwwwwwwwpwwwwwe +2 75 hwwwwwwwwwwwwwwwwwwwe +2 76 wwwwwwwwwwwwwwwwwwwwwpwwe +2 77 wwwwwwwwwe +2 78 wwwwwwwwwwwe +2 79 wwwwwwwwwwwwwwwpwwwwwwwwwe +2 80 wwwwwwwpwwwwwwwwwpwwwwwwwe +2 81 wwwwwwwwwwpwwwe +2 82 wwwwwwwpwwwe +2 83 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +2 84 wwwwwwwwwwwwwwwe +2 85 wwwwwwwwwwwwwwwwwwwwwwpwwwwwpwwwwwwwwwwwpwwwwwwpwwwwwe +2 86 wwwwwwpwwwwwwwe +2 87 wwwwwwwwpwwwwwwwwpwwwwwwwwwwwwe +2 88 wwwpwwwwwwwe +2 89 wwwwwwwwwwwwwwwwwwwwwwpwwwwe +2 90 wwwwwwwwwwwwwwwwwwwwpwwwwpwwwe +2 91 wwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwe +2 92 hwwwwwwwwwwwe +2 93 wwwwwwwwwwwpwwwwwwwwpwwwwwwwwe +2 94 wwwwwwwwwwwwwwwwwe +2 95 wwwwwwpwwwe +2 96 wwwwwwwwpwwwwwwwwwwwwwpwwwwe +2 97 wwwwwwwwwwwwwwwwwwe +2 98 wwwwwwwwwwwwe +2 99 wwwwwpwwwwwe +2 100 wwwwwwpwwwwe +2 101 wwwwwwwwwwwwwwwwwwwwwwe +2 102 wwwwwwwpwwwwwwwwwwwwwwwwpwwwwwwwwwwwpwwwwwwwwpwwwwwwwwwpwwwwwpwwwwwwwwwwpwwwwwpwwwe +2 103 wwwwwwwwwpwwwe +2 104 wwwwwwwwwpwwwe +2 105 wwwwwwwwwwwwwwwwpwwwwwpwwwwe +2 106 hwwwwwwwwwwwpwwwwwwwwe +2 107 wwwwwwwwpwwwwwwwwwe +2 108 wwwwwwwwwwpwwwwwwwwe +2 109 wwwwwwwwwwwwwwwwwwwwwpwwwwwwpwwwwwwe +2 110 wwwwpwwwwwwwwpwwwwwe +2 111 wwwwwwwwwwpwwpwwwwwwe +2 112 wwwwwwwwwwwwwwwwwe +2 113 wwwwwwwwwwwwwwwpwwwwwwwpwwwwwwwwwe +2 114 wwwwwwwwwwwwwpwwwwwwwwpwwwwwwwwwe +2 115 wwwpwwwwwpwwwwe +2 116 wwwwpwpwwwwwwpwwwe +2 117 wwwpwwwwwwwwe +2 118 wwwwwwwwwwpwwwwwwwpwwpwwwwwe +2 119 wwwwwpwwwwwe +2 120 wwwwwwwwwpwwwwwwpwwwwwwwwpwwwwwwwwe +2 121 wwwwwwwwwpwwwwwwe +2 122 wwwwwwwwwwwe +2 123 wwwwwwwwwwwwwwwwwwe +2 124 hwwwwwwpwwwwwpwwwpwwwwwe +2 125 wwwwwwwwwwwpwwwwwwwwwwwe +2 126 wwwwwwwwwwwwwwwwwwpwwwwwwwwwwpwwe +2 127 wwwwwwwwwwpwwwwe +2 128 wwwwwwwwwwwwwpwwwwe +2 129 wwwwwwwwwwwwpwwwwe +2 130 wwwwwwwwwpwwwwpwwwwwe +2 131 wwwwwpwwwwe +2 132 wwwwwwwwwwwwwwwwe +2 133 wwwwwwwwwwwwwwwwwwwwwwwwwwwe +2 134 wwwwpwwwwwwpwwwwwe +2 135 wwwwwwpwwwwwpwwwwe +2 136 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +2 137 wwwwwwwwpwwwwwwpwwpwwwe +2 138 wwpwwwwwpwwwe +2 139 wwwwwwwwwwwwwwe +2 140 wwwwwwwwwwwwpwwwwwpwwwwwwwwpwwwwwe +2 141 wwwwpwwwwwwpwwwwwe +2 142 hwwwwwwwwwwwpwwwwpwwwwwwe +2 143 wwwwwwwwwwwwpwwwwwwwwwwwwwwwpwwwwwwwwpwwwwwpwwwwwe +2 144 wwwwwwpwwwpwwwwwpwwwwwwpwwwwwwwwwpwwwwwe +2 145 wwwwwwwwwwpwwwwpwwwwwpwwwwwwwwwpwwwwe +2 146 wwwwwwwpwwwwwwwe +2 147 wwwpwwwwe +2 148 wwwwpwwpwwwwwwwpwwwwwwe +2 149 wwwwwwwwpwwwwpwwwwwe +2 150 wwwwwwwwpwwwwwwwwwwwwwwwwwwwwwwwe +2 151 wwwwwwwwwwwwwwwwwe +2 152 wwwwwwe +2 153 wwwwwwpwwwwe +2 154 wwwwwwwwpwwwwwe +2 155 wwwwwwwwwwpwwe +2 156 wwwwwwwwwwe +2 157 wwwwwwpwwwe +2 158 hwwwwwwpwwwwwwwwwwwpwwwwwwwe +2 159 wwwwwwwwwwwwwwwpwwwwwe +2 160 wwwwwwwwpwwwe +2 161 wwwwwwwwwwwwwe +2 162 wwpwwwwwwwe +2 163 wwwpwwwwwwe +2 164 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +2 165 wwwwwwwwwwwpwwwwwpwwwwwwwwwwwwwwwe +2 166 wwwwwwwwwwwwe +2 167 wwwwwwwwwwwwpwwwwwwpwwwwwe +2 168 wwwwwwwwwwwwpwwwwe +2 169 wwwwwwwwwwwe +2 170 wwwwwwwwwwwwwwpwwwwwwwwe +2 171 wwwwwwwwwwwwpwwwwwwe +2 172 wwwwwwwwwwwwwwe +2 173 wwwwwwwwwwwwpwwwwwwwwwpwwwwe +2 174 wwwwwwwwwwwwpwwwwwwwwwwwwwwwwwe +2 175 wwwwwwwpwwwwe +2 176 wwwwwwpwwwwwwwwe +2 177 hwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwpwwwpwwwe +2 178 wwwwwwwwpwwwwwwpwwwwwwwwwwwpwwwwwpwwwwwwwe +2 179 wwwwwwwwe +2 180 wwwwwwwwwwwwwpwwwe +2 181 wwwwwwwwwwpwwwwe +2 182 wwwwwwwwwwwwpwwwwe +2 183 wwwwwwwwwwwwwwe +2 184 wwpwwwwwwwwwwwpwwwwwwpwwwwwwpwwwwpwwwe +2 185 wwwwwwwwwwwwpwwwwwpwwwwwwwwwwpwwwwwwwwwwwwwwwwwe +2 186 wwwwwwpwwwwwpwwwwwwe +2 187 wwwwwwwpwwwwwwpwwwwwwwwwwpwwwwwwwpwwwwwwwwwwwwpwwwwwpwwwwwwpwwwwwpwwwwwwwe +2 188 wwwwwwwwwwwwwwwwwe +2 189 hwwwpwwwwwpwwwwwwwwwwwpwwwwpwwwwe +2 190 wwwwwwwwpwwwwwe +2 191 wwwwwwwpwwwwpwwwwwwwwpwwwpwwwe +2 192 wwwwwwe +2 193 wwwwwwwwpwwwwwwwe +2 194 wwwwwwpwwwwwwwwwpwwwwwwwe +2 195 wwwwwwwwwpwpwwwwe +2 196 wwwwpwwwwwwpwwwwwwwpwwwwwwwwwwwwwwwwpwwwwwwwwwwwpwwwwwwwwwwwpwwwpwwwwwwwwpwwwwwwwe +2 197 wwwpwwwwwwwwwwwwpwwwwwwpwwwwwpwwwe +2 198 wwwwwwwwpwwwwwwwwwpwwwwwwwwwe +2 199 wwwwwwwwpwwwwe +2 200 wwwwwwwwwwpwwwwwwwwwwwwwwe +2 201 wwwwwwwwwwwwwwe +2 202 wwwwwpwwwe +2 203 hwwwwwpwwwwwwwwwwwwpwwpwwwwwwe +2 204 wwwwwwwwwwwwwwwwwe +2 205 wwwwwwwwwwpwwwwe +2 206 wwwwwwwwpwwpwwe +2 207 wwwwwwwwpwwwe +2 208 wwwwwwwwwwwpwwwwe +2 209 wwwwwwwwwwwwe +2 210 wwwwwwwwwwwwwpwwwwe +2 211 wwwwwwwwpwwwwwwwwwwwwe +2 212 wwwwwwwwwpwwwwwpwwwwwwe +2 213 wwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwpwwwwwwwwwwpwwwwwwwe +2 214 wwwwwwwwwwwwpwwwwwwwwwwwwwpwwwwwe +2 215 wwwpwwwwwwwwwwwpwwwwwwwwe +2 216 wwwwwwpwwwwwwwpwwwwwwwpwwwwwe +2 217 wwwwwwpwwwwpwwwwwwwwwwwwwwpwwwwpwwwwwwwwwpwwwwwwwwwwwwwwpwwwpwwwe +2 218 wwwwwwwwwwwwwpwwwe +2 219 hwwwwpwwwwwwwwwwpwwwwwpwwwwwwwe +2 220 wwwpwwwpwwwwpwwwpwwwwwpwwwwpwwwwe +2 221 wwwwwpwwwwwwwpwwwwwpwwwwwwwpwwwwpwwwwwwpwwwwwe +2 222 wwwpwwwwwwwpwwwwpwwwwwwwpwwwwwwe +2 223 wwwwwwwpwwpwwwwwpwwe +2 224 wwwwwwwwwwwpwwwe +2 225 wwwwwwwwwwwpwwwe +2 226 wwwwwwwpwwwwwwe +2 227 wwwwwwwe +2 228 wwwwwpwwwwwwwwwwwwwwwwpwwwwwwwwpwwwwwpwwwpwwwe +2 229 wwpwwwwwpwwwwwwwwwwwwwwwpwwwwwwwwwwwwpwwwwwpwwwwwwwe +2 230 wwwwwwwwwwwpwwwwwwwwwwwwwpwwwwwwe +2 231 wwwwwwwwwwpwwwwpwwwwwwpwwwwwpwwwwwwwwwwwwpwwwwwwwwe +2 232 wwwwwwwwwwwwwwpwwwwwwwwwwpwwwwpwwwwwe +2 233 hwwwwwpwwwwwpwwwwwwpwwwwwpwwwwwwwwpwwwwpwwwwwwwwwwpwwwwwwwwwwwwwpwwwwwwwwe +2 234 wwwwwwwwwwpwwwwwwwwwwwpwwwwe +2 235 wwwwwwwwwwwwwpwwwwwwwwwwwwwpwwwwwwwwpwwwwwwwwpwwwwwe +2 236 wwwwwwwwwwwwwpwwwwwwwwwpwwwe +2 237 wwwwwwwwwwwwwwwwwwwwwwpwwwwpwwwwpwwwwwe +2 238 wwwwwwwwe +2 239 wwwwwpwwwwwwwwwwe +2 240 wwwwwwwwwwwwpwwwwwwwwwwwwpwwwe +2 241 wwwpwwwe +2 242 wwwwwwwe +2 243 hwwwwwwwwwwwwwwwwwpwwwwwwwwwwwe +2 244 wwwwwwwwwe +2 245 wwwwwwwwwwwpwwwwwe +2 246 wwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwpwwwwwwwwwwwwwpwwwwwwwwpwwwe +2 247 wwwwwwwwwwpwwwwwwwwwwwwwwwpwwwwwwwwwwpwwwwwpwwwe +2 248 wwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwe +2 249 wwwwwwwwwwwwwwwwwwwwwwwwpwwwwwpwwwwwwwwwwwwwpwwwwwwwwwwwwwwwpwwwe +2 250 wwwwwwwwwwwwwwwe +2 251 wwwwwwwwwwwwwpwwwwwwwwwwwwwwe +2 252 wwwwwwpwwwe +2 253 hwwwwwwpwwwwpwwwpwwwwwwwwpwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwe +2 254 wwwwwwwwwwwwwwwwwwpwwwe +2 255 wwwwwwwpwwwwwpwwwwwwwpwwwwwwwpwwwwwwpwwwwwwwwpwwwwpwwwpwwwe +2 256 wwwwpwwwwwpwwwwwwwwwwwwpwwwe +2 257 wwwwwwwwwpwwwwwwwwwpwwwpwwwe +2 258 wwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwpwwwwwe +2 259 wwwwwwwwwwwwwwwwpwwwwwwpwwwpwwwwwwpwwwwwwwwwwwpwwwwwwpwwwwwwwwpwwwwwwwwwwwe +2 260 wwwwwwwwpwwwpwwwwwpwwwwwwwwwwwwwwwwwwpwwwwwe +2 261 wwwwwwwwwwwwwwwwwpwwwwpwwwe +2 262 wwwwwwwwwwwwwwpwwwwwwwwwwe +2 263 hwwwwwwwwpwwwe +2 264 wwwwwwwwwwwwwwwwwwpwwwwwwwwwpwwwwwwpwwwwwe +2 265 wwwwwwwwwwwwwwwwwwwwwwwpwwwwe +2 266 wwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwe +2 267 wwwwwwwwwwwwwpwwwwwwwwwwwpwwwwwe +2 268 wwwwwpwwwwwpwwwe +2 269 wwwwpwwwwwwwpwwwwwe +2 270 wwwwwwwwwwwpwwwwe +2 271 wwwwwpwwwwwwwpwwwwpwwwwe +2 272 hwwwwwwwwpwwwwwpwwwwwwpwwwwwwwwwe +2 273 wwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwe +2 274 wwwwwwwwwwwwwwwwwe +2 275 wwwwwwwwwwwwwpwwwwwwwpwwwwwpwwwwwwwwwwwwpwwwwwpwwwe +2 276 wwwwwpwwwwwwe +2 277 wwwwwwwwwwwwwwwwwwwe +2 278 wwwwwwwwwwwwwe +2 279 wwwwwwwwpwwwwwwwwwe +2 280 wwwwwwwpwwwwpwwwe +2 281 wwwwwwpwwwwwwwwwe +2 282 wwwwwwwwwwpwwwwpwwwwwwwwpwwwwwwwwwwwwpwwwwwwwwwwwwwwwwwpwwwwpwwwwwwwwwwwwwwwwpwwwwwwpwwwwwwwwwpwwwwwwwwwpwwwwwwwwwwwwpwwwpwwwwwpwwwwwpwwpwwpwwwwe +2 283 hwwwwwwwwwpwwwwwwwwwwwpwwwpwwwwwpwwwwe +2 284 wwwwwwwpwwwwwwwwwwpwwwwwwpwwwwwe +2 285 wwwwwwwwpwwwwwwwwwwwwpwwwpwwwwe +2 286 wwwwwwpwwwwwwpwwwwwwwpwwwwwwwwwwwpwwwwwwwwpwwwwwpwwwwwwe +3 1 we +3 2 wwwwwwwe +3 3 wwwwwwwwwwwe +3 4 wwwwwwpwwwwwwwwpwwwwe +3 5 wwwwwwwwwwwe +3 6 wwwwwwwpwwwwwwe +3 7 wwwwwwwwwwwwwpwwwwwwwwwwwwwpwwwwwpwwwwwwwwwwpwwwwwe +3 8 wwwwwwwwwwwwpwwwe +3 9 wwwwwwwwpwwwwwe +3 10 wwwwwwwwwwwwpwwwwe +3 11 wwwwwwpwwwwwpwwwe +3 12 wwwwwwwpwwe +3 13 wwwwwwwpwwwwwwwwwwwpwwwwwpwwwwwwe +3 14 wwwwwwwwwwwwwwwwpwwwwpwwwwe +3 15 hwwwwwpwwwwwwwwwwwwwwwwpwwwe +3 16 wwwwwwwwwwwe +3 17 wwwwwwe +3 18 wwwwwwwwwwwwpwwwwwwe +3 19 wwwwwpwwwwwwwwwwwwwpwwwwwwwwe +3 20 wwwwwwwwpwwwwwwpwwwwpwwwwwpwwwe +3 21 wwwwwwwwwwwwwwwwwwe +3 22 wwwwwwwwwwwe +3 23 wwwwwwwwwwwwwwwwwwwwe +3 24 wwwwwwwwwpwwwwwwe +3 25 wwwwwwwwwwwwwwwe +3 26 wwwwwwwwwwwwwwwwwwpwwpwwwwwe +3 27 wwwwwwwwpwwwwwwwwpwwwwwe +3 28 wwwwwwwwpwwwwwwwwwwwwwpwwwpwwwe +3 29 wwwwwwwwwwpwwwwwwwpwwwwwe +3 30 wwwwwwwwwwwwwwwwwwwwpwwwpwwwe +3 31 wwwwwwwwwwwpwwwe +3 32 wwwwpwwwwwwwe +3 33 hwwwwwwwwwwwe +3 34 wwwwpwwwe +3 35 wwwwwwwwwwwwwwpwwwwe +3 36 wwwwwwwwwwwwwwpwwwwwwwwwwe +3 37 wwwwwwwwwpwwwwwwwwpwwwwwpwwwwwpwwwwwwwe +3 38 wwwwpwwwwwwwwpwwwe +3 39 wwwwwwwwwwwwwwwwwwwwe +3 40 wwwwwwwwwwwpwwwwwwe +3 41 wwwwwpwwwwwwwwwpwwwwwwe +3 42 wwwwwwwwwwwwe +3 43 wwwwwwwe +3 44 wwwwwwpwwwwwwwwwwwwwwe +3 45 wwwwwwwwwwwwwwwwwwwwe +3 46 wwwwwwwe +3 47 wwwwwwwwwpwwwwwwpwwwwwwwwe +3 48 wwwwwe +3 49 wwwwwwwwwwpwwwwwwwwwwwwwpwwwwwwwpwwwwwwwpwwwwwwwwe +3 50 wwwwwwwwwwwwpwwwwwwwe +3 51 wwwwwpwwwe +3 52 hwwwwwwwwwwpwwwwwwwwwwe +3 53 wwwwwwwwwe +3 54 wwwpwwwe +3 55 wwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwe +3 56 wwwwwwwwwwwwwe +3 57 wwwwwwwpwwwwe +3 58 wwwwwwwe +3 59 wwwwwwwpwwwwwwwwe +3 60 wwwwwwwe +3 61 wwwwwwwwwwwwwwwwwwwwwwwwwe +3 62 wwwwwpwwwwwpwwwwwe +3 63 wwwwwwe +3 64 wwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwe +3 65 wwwwwwwwwwwwwpwwe +3 66 wwwwwwwwwwwwwwpwwwwwe +3 67 wwwwwwwwwwwwwwe +3 68 wwwwwwwwwwpwwwe +3 69 wwwwwwwwwwwwwe +3 70 wwwwwwwwe +3 71 wwwwwwwwwwe +3 72 wwwwwwwwwwwwwwwwwe +3 73 wwwwwwwwwwwwwwwwwwwwwpwwwwwwwwpwwwe +3 74 wwwwpwwwwe +3 75 hwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwe +3 76 wwwwwwwwwe +3 77 wwwwwwwwwwwwwwwwwwwwwwwwwwwe +3 78 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +3 79 wwwwwwwwwwwwwwwwwwwwwwwwwwwwe +3 80 wwwwwwwpwwwwwwe +3 81 wwwwwwwwwwwwwwwwwwwpwwwwwwpwwpwwwwwwe +3 82 wwwwwwwe +3 83 wwwwwwwwwwwwwwe +3 84 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +3 85 wwwwwwwwwwwwwe +3 86 wwwwwwwwwwwwwpwwwwwe +3 87 wwwwwwwwwe +3 88 wwwwwwwwwe +3 89 wwwwwwwwwwwe +3 90 wwwwwwwwwwwwwwe +3 91 wwwwwwwwwwwwwwwwpwwwwwwwwe +3 92 wwwwwwwpwwwwwwwwe +3 93 hwwwwwwwwwwwwwwwwwpwwwwwwwe +3 94 wwwwwwwwwwwe +3 95 wwwpwwwwwwwwe +3 96 wwwwwwwwwwe +3 97 wwwwwpwwwwpwwwwwwwwwpwwwwwwwe +3 98 wwwwwwwwwwwwe +3 99 wwwwwwwwwwwwwwpwwwwwe +3 100 wwwwwwwwwwwwwwe +3 101 wwwwwwwwwpwwwwwwwwe +3 102 wwwwwwwwwwwwe +3 103 wwwwwwpwwwwwwwwwwwwwwwwwwwwwpwwwwwwwe +3 104 wwwwwwwwwwwpwwwe +3 105 wwwwwwwwwwpwwwwe +3 106 wwwwwpwwwwwwwwwwwwe +3 107 wwwwwwwwwwe +3 108 wwwwwwpwwwwwe +3 109 wwwwwwwpwwwwe +3 110 wwwwwwwwwwwwpwwwwwwwpwwwwe +3 111 wwwwpwwwwwwwe +3 112 wwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwpwwwwwe +3 113 hwwpwwwwwwwwwwwwe +3 114 wwwwwwwwwwwwwwwe +3 115 wwwwwwpwwwe +3 116 wwwwwwwwwwwwpwwwpwwwe +3 117 wwwwwwwwwwwwwwwwwpwwwwwwe +3 118 wwwwwwwwwwwwwwwwwwwwwwwpwwwwpwwwe +3 119 wwwwwwwwwwwwwwwwwwwpwwwpwwwwwe +3 120 wwwwwwwwwpwwwwwwwpwwwwwe +3 121 wwwwwwwwpwwwe +3 122 wwwwwwwwpwwwwe +3 123 wwwwwwpwwwwe +3 124 wwwwwwwwwwwwwe +3 125 wpwwwwwwwwwwwwwwe +3 126 wwwwwwwwwpwwwwwwwwe +3 127 wwwwwwwwwe +3 128 wwwwwwwwwwwwe +3 129 wwwwwwwpwwwwwwpwwwe +3 130 wwwwwwwwpwwwwe +3 131 wwwwwe +3 132 wwwwwe +3 133 hwwwwwwwwwwwe +3 134 wwwwwwwwwwpwwwe +3 135 wwwwwwwwwwwwwwwwwwwwwwwe +3 136 wwwwwwwwwwwwpwwwe +3 137 wwwwwwwwwwwwwe +3 138 wwwwwwe +3 139 wwwwwwwwwe +3 140 wwwwwwwwpwwwwwwwwwwwwpwwwwe +3 141 wwwwwwe +3 142 wwwwwwwwwwwwwe +3 143 wwwwwwwwwwwwe +3 144 wwwwwwwwwpwwwwwwwpwwwwwwwwpwwwe +3 145 wwwwwwwwwwpwwwwwwwwwwwwpwwe +3 146 wwwwwwwwwwwwwwwwwwpwwwe +3 147 wwwwwwwwwwwwwwwwwwwe +3 148 wwwwwwwpwwwe +3 149 wwwwwwwwwwwwe +3 150 wwwpwwwe +3 151 wwwwwwwwwwwwwwpwwpwwwe +3 152 wwwwwwwpwwwwwwwwwwwwwpwwwwwwwwpwwwwpwwwpwwwwwe +3 153 hwwwwwwwwwwwwwwwwwwwwwpwwwwe +3 154 wwwwwwwwwwwpwwwwwwwwwwpwwwwwwwpwwwwwpwwwwwwwpwwwwwwwwwwpwwwwwwwwwwwwpwwwwwwwwwpwwwwe +3 155 wwwwwwwwwwwwwpwwwwpwwwwe +3 156 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwpwwwwe +3 157 wwwwwwwwwwwwwwe +3 158 wwwwwwwe +3 159 wwwwwwpwwwwwwwwpwwwwwwwpwwwwwpwwwwe +3 160 wwwwwwpwwwwwwwwpwwwwe +3 161 wwwwwpwwwwwwwpwwwwwwwwwe +3 162 wwwwwwwwwwwpwwe +3 163 wwwwpwwwwe +3 164 wwwwwwwwwwwwwwwwwwwwwwwwwe +3 165 wwwwwwwwwpwwwwwpwwwwwwe +3 166 wwwwwwwwwe +3 167 wwwpwwwwwwwwwpwwwwwpwwwwwwpwwwwwwpwwwwe +3 168 wwwwwwwwpwwwwwwwwe +3 169 wwwwwwwwpwwwwwe +3 170 wwwwwwwwwwwwwwwwwwwe +3 171 hwwwwwwwwwwwe +3 172 wwwwwwwwwpwwwwwwe +3 173 wwwwwwwwwwwwwwwwwe +3 174 wwwwwwwwwwwpwwwwe +3 175 wwwwwwwwwwwe +3 176 wwwwwwpwwwwwpwwwwwwwwpwwwe +3 177 wwwwwwwwwwwwe +3 178 wwwwwwwwwpwwwwwpwwwe +3 179 wwwwwwwwwwwwwwpwwwwwwwwwwwwwpwwwpwwwwwwe +3 180 wwwwwwwwwwwwpwwwwpwwwwwwpwwwwpwwwwe +3 181 wwwwwwwwwwwpwwwwwwwwwwwe +3 182 wwwwwwwwwe +3 183 wwwwwwwwwwwwwwpwwwwwwwwwwwwwwe +3 184 wwwwwwwwwwwwe +3 185 wwwwpwwwwwpwwwwwwwwpwwwwwwe +3 186 hwwwwwwwwwwwwwwwwpwwwwwwwwe +3 187 wwwwwwwwwwwwwwwwwwpwwwe +3 188 wwwwwwwwwwwwwwwwwpwwwe +3 189 wwwwpwwwwwe +3 190 wwwwwwwwwwwe +3 191 wwwwwwwwwwwwwwwwwwwwwe +3 192 wwwwwwwpwwwwe +3 193 wwwwwwwwwwpwwwwwwwwwwe +3 194 wwwwwwwwwwpwwwwe +3 195 wwwwwwwwwwwwwpwwwpwwwwwwwwwwwwwwwwwwwwwwwpwwwwe +3 196 wwwwwwwe +3 197 wwwwwpwwe +3 198 wwwwwwwwwwwwwwwwpwwwwwe +3 199 wwwwwwwwwwwwwwwwwwwwwpwwwwwpwwwwe +3 200 wwwwwwwwwwe +4 1 wwwwwwwwwwwwwwwwwpwwwwwwpwwwwwe +4 2 wwwpwwwwpwwwwwpwwwwe +4 3 wwwwwwwwwwwwwwwpwwwwwwwwwpwwwwe +4 4 wwwwpwwwwwwwwwwe +4 5 wwwwwwwwwwwwwwwwe +4 6 wwwwwwwwwwwwwpwwwwwwpwwwwpwwwwwpwwwwwwpwwwe +4 7 wwwwwwwwwwwwwwwwwpwwe +4 8 wwwwwwwwwwwwwe +4 9 wwwwwwwwwwwwwwwe +4 10 wwwwwwwwwwwpwwe +4 11 wwwwpwwwwpwwwwwwwwwpwwwwwpwwwwwwwwwwwpwwwwwwwwwpwwwwwwpwwwwwwwpwwwwwwwwpwwwpwwwwwe +4 12 hwwwwwwwwwwpwwwwwwwwpwwwwwwwpwwwwwwwwwpwwwwwwwwpwwwwwwwpwwwwwwwwwwwwwwwpwwwwwwwwwpwwwwwwwwwpwwwpwwwe +4 13 wwwpwwwwwwwwwwwwpwwwe +4 14 wwwwwwwwwwwwwe +4 15 wwwwwwwwwpwwwwwwwwwwwwwe +4 16 wwwwpwwwwwpwwwwwe +4 17 wwwwwwwwwwwwwwwwpwwwwe +4 18 wwwwwwwwwwwwwwwwwwwpwwwwwe +4 19 wwwwwwwwwwpwwwwwwwwwwwpwwpwwwwwwwwwwwe +4 20 wwwwwwwwwwwwwpwwwwe +4 21 wwwwwwwwwwwe +4 22 wwwwwwwwwwwpwwwwwwe +4 23 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwe +4 24 hwwwwwwwpwwwpwwwwwwwwwwwpwwwwwwwpwwwwwwwwwpwwwwwe +4 25 wwwwwwwwwwwwwwwwpwwwpwwwpwwwwwwwwwwwwpwwwwwwwwwwwwpwwwwwpwwwwpwwwe +4 26 wwwwwwwwwwwpwwwe +4 27 wwwwwwwwwwwwwe +4 28 wwwwwpwwwe +4 29 wwwwwwwwwwwwwwwpwwwpwwwwwe +4 30 wwwwwwwwpwwwwwe +4 31 wwwwwwwwwwwwe +4 32 wwwwwwwwwpwwwwpwwwwpwwwwpwwwwwwe +4 33 wwwwwwwpwwwwwpwwwwwwwe +4 34 wwwwwwwwwwwwwwpwwwwwwwpwwwwwwwwpwwwwwwpwwwwwe +4 35 wwwwwwwwwwwwwwwwwpwwwwwe +4 36 hwwwwwwpwwwwwwwwwwwwwwwwwwpwwwwwwwwe +4 37 wwwwwwwwwwwpwwwwe +4 38 wwwwwwwwwwwpwwwwwwwe +4 39 wwwwwwwwwwwpwwwwe +4 40 wwwwwwpwwwwwwwwwe +4 41 wwwwwwwwwwwwe +4 42 wwwwwwwwwwwwwwe +4 43 wwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwe +4 44 wwwwwwwwwwwwwwe +4 45 wwwpwwwwwwe +4 46 wwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwwwwwe +4 47 wwwwwwwwwwwwwwwwwwwwwwwwpwwwwe +4 48 wwwwwwwwwwwwwpwwwwwwwe +4 49 wwwwwwpwwwwwwwwe +4 50 wwwwwwpwwwwe +4 51 wwwwwwwwwwwwwwwwwwwwe +4 52 wwwwpwwwwwwwe +4 53 wwwwwwwwwwe +4 54 wwwwwwwwwpwwwwwwwwwe +4 55 wwwwwwwwpwwwe +4 56 wwwwwwwwwwwwwwwpwwwwwe +4 57 wwwwwwwwwwwwwpwwwwpwwwe +4 58 hwwwwwwwwwwwwwwwpwwwwwpwwwwwe +4 59 wwwwwwwwwwpwwwwwwwwwwwwwwpwwwwe +4 60 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +4 61 wwwwwwwwwwwwwwwe +4 62 wwwwwwwwwwwwwwwwe +4 63 wwwwwwwwwwwwwwwwe +4 64 wwwwwwwwpwwwwwwwwwwwwwwwe +4 65 wwwwwwwwwwwwwwwwwwwe +4 66 wwwwwwwwwwwwwwwwpwwwwwwwwwwwe +4 67 wwwwwwe +4 68 wwwe +4 69 wwwwwwwwwwwwwwwpwwwe +4 70 wwwwpwwwe +4 71 wwwwwwwwwwe +4 72 wwwwwwwwwwwwwwwwwe +4 73 wwwwwwwwwwwwwwwwwwe +4 74 hwwwwwwwwwpwwwwwwwwwwwwe +4 75 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +4 76 wwwwwwpwwwwwwwwwpwwwwwe +4 77 wwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwpwwwwwwwwwwwe +4 78 wwwwwwwwwpwwwwwwwwpwwwwwwwpwwwwwpwwwwwwwe +4 79 wwwwwwpwwwwwwpwwwpwwwe +4 80 wwwwwwpwwwwwwe +4 81 wwwwwwwwwwwwpwwwwpwwwwwpwwwe +4 82 wwwpwwwwwwwwwwe +4 83 wwwwwwwwwpwwwwwwwwwwwwpwwwwwwwwwe +4 84 wwwwwwwwpwwpwwwwwwwpwwwwwe +4 85 wwwwwwwwpwwwwwwwwpwwwwwwe +4 86 wwwwwwwwpwwwwwwwe +4 87 wwwwwpwwwwwwwpwwwwwe +4 88 hwwwwwwwwwpwwwwwwpwwwwwwwe +4 89 wwwwwwwpwwwwwwwwwpwwwwwwpwwwwwwe +4 90 wwwwwwwwwwwwwwwwwpwwwwwwpwwwwwwwwwwwwwe +4 91 wwwwwwwwwwwwwwpwwwwwwwwwwwwpwwwwwwe +4 92 wwwwwwwwpwwwwwwwwwwwwwwpwwwwwwwwwwwpwwwwwwwwwwwwwwpwwwwwwwwwpwwwwe +4 93 wwwwwwwwwwwwwwwwe +4 94 wwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwpwwwwwwe +4 95 wwwwwwwwwwwwwwpwwwwwwwwpwwwwpwwwwwwwe +4 96 wwwwpwwwwe +4 97 wwwwwwwwwpwwwwwpwwwwwwwwpwwwpwwe +4 98 wwwwwwwwwwwwe +4 99 wwwwwwpwwwwe +4 100 hwwwwwwwwwwwpwwwwwwwwwwwwwwwwpwwwwe +4 101 wwwwwwwwwwwwwwwwwpwwwwwwe +4 102 wwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwpwwwwwwwwwwwwwwwpwwpwwwwwwe +4 103 wwwwwwwwwpwwwwpwwwwwwwe +4 104 wwwwwpwwwwwwwpwwwwwwpwwwwe +4 105 wwwwwwwwwwwpwwwwe +4 106 wwpwwwwwe +4 107 wwwwwwpwwwwwwwwe +4 108 wwwwwwwwwwwwwwwwpwwwwwe +4 109 wwwwwwwwwwwwwwwwwwe +4 110 wwwwwwwwwwwwwe +4 111 wwwwwwwpwwwwe +4 112 wwwwwwwwwwwwwwe +4 113 wwwwwwwwwwwwwwpwwpwpwwwwwwwwwwwwwwwwe +4 114 hwwwwwwwwwwwwwwwwpwwwwwwwwwwe +4 115 wwwwwwwwwwwwwwwwwwpwwe +4 116 wwwwwwwwwwwwwpwwwwwwwe +4 117 wwwwwwwwwwwe +4 118 wwpwwwwwwe +4 119 wwwwwwwwwwpwwwwwwwwwwwe +4 120 wwpwwwwwe +4 121 wwwwwwwe +4 122 wwwwwwwwwwwwwpwwwpwwwwwe +4 123 wwwwwwpwwwwwwwwwwwwwwe +4 124 wwwwwwwwwwwwwwwwe +4 125 wwwwwwwwwwwwwpwwwwe +4 126 wwwwwwwpwwwwwe +4 127 wwwpwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwe +4 128 wwwwwwwwwwwwwwwpwwpwwwpwwwwwwwwwe +4 129 wwwwwwwwpwwwwwwpwwwwwwwwe +4 130 wwwwwwwpwwwwe +4 131 wwwwwwwpwwwwwwwwwwwpwwwwwwwwwwpwwwwe +4 132 wwwwwwwpwwwe +4 133 wwwwwwwpwwwwwe +4 134 wwwwwwwwwwpwwwwe +4 135 hwwwwwwwwwwwwwwpwwwwwwwwpwwwwwpwwwwwwwwwwe +4 136 wwwwwwwwwwwwwwwwpwwwwwwwwwwwwe +4 137 wwwwwwwwwwwwwwwwwwwwe +4 138 wwwwwwe +4 139 wwwwwwwpwwwwwwwe +4 140 wwwwwwwwwwwwwwwwwwwwwwpwwwpwwwwwwwwe +4 141 wwwwwwwwwwwwwwwwwwwwwwwwpwwwwwpwwwwwwwe +4 142 wwwwwwwwwwwwwwwwwwwe +4 143 wwwwwwwwwpwwwwwwwe +4 144 wwwwwwwwwwpwwwwwwwe +4 145 wwwwwwwwwwwe +4 146 wwwwwwwwwwwwpwwwwwwe +4 147 wwwwwwwpwwwwe +4 148 hwwwwwwwwwwpwwwwe +4 149 wwwwwwwwwwwwwwe +4 150 wwwwwwwwwwwwwwwwwwwwwwe +4 151 wwwwpwwwwe +4 152 wwwwwwwwwwwwwpwwwwe +4 153 wwwwwwwwwpwwwwwwwwwwwwwpwwwwwwwwwwwpwwwwe +4 154 wwwwwwwwwwwwwwwwwwwe +4 155 wwwwwwwwwwwwwpwwwwwwwwwe +4 156 wwwwwwe +4 157 wwwwwwwwwwwwwwwwpwwwwwwwpwwwwwwwwpwwwe +4 158 wwwwpwwwwe +4 159 wwwwwwwwwpwwwwwe +4 160 wwwwwwwwwwwwwwe +4 161 wwwwwwwwwpwwwwwe +4 162 wwwwwwwwwwwwwwpwwpwwwwwwwwwwe +4 163 hwwwwwwwwwwpwwwwwwwwwwwwpwwwe +4 164 wwwwwwwwwwpwwwwe +4 165 wwwwwwwwwwwpwwwwe +4 166 wwwwwwpwwpwwpwwwe +4 167 wwwwwwwwwwwe +4 168 wwwwwwwwwwwwe +4 169 wwwwwwpwwwwwe +4 170 wwwwwwwwwwwpwwwwwwwwpwwwwe +4 171 wwwwwwwwwwwwpwwwwwwwwwwwwwpwwwpwwwpwwwpwwwwpwwwwwpwwwwwwwpwwwe +4 172 wwwwwwwwwwpwwwwwwwwe +4 173 wwwwwwwwwwpwwwwwwwwwwwwwwwwe +4 174 wwwwwwwwwwwe +4 175 wwwwwwwwwwwwwwwe +4 176 wwwwwwpwwwwwwwwwwwwpwwwwwwwpwwwwwwwpwwwwwwwwwpwwwwwpwwwwe +5 1 wwwwwpwwwwwwwwwwwwwpwwwwwe +5 2 wwwwwwwwwwwwwwwwwwwwwwwpwwwpwwwwwwwwwwwpwwwwpwwwwwpwwpwwwwe +5 3 wwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwpwwwwwwwwwpwwwwwwwwwwwpwwwwwwwpwwwwe +5 4 wwwwpwwwwpwwwwwwwwwpwwwwwwwwpwwpwwwwe +5 5 wwwwpwwwwwwwwwpwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwe +5 6 wwwwwwwwwwwwwwwwwpwwwwpwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwe +5 7 wwwwwwwwwwwwpwwpwwwwwe +5 8 wwwwwwwwpwwwwwwwpwwwwpwwpwwwwwe +5 9 wwwwwwpwwwwe +5 10 wwwwwwwe +5 11 wwwwwwwwwwwwwwwwwpwwpwwwwe +5 12 hwwwwwwwwwwwpwwwwpwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwe +5 13 wwwwwwwpwwwwpwwwwwpwwwwwwwwwpwwwpwwwwe +5 14 wwwwwwwwwwwwwwwwwwwpwwwwwwe +5 15 wwwwwwwwwwwwwwwwpwwwwwwwe +5 16 wwwwwwwwwwwwwwwwwwe +5 17 wwwwwwwwwwpwwwwwwwwwwwwwwwwwwpwwwwwwpwwwpwwwwwe +5 18 wwwwwwwpwwwwpwwwwwpwwwwwwpwwwwwwpwwe +5 19 wwwwwwwwwwwwwwwwwwwpwwwwpwwwwwe +5 20 wwwwwwwwwwwwwwwwwwwwwwe +5 21 wwwwwwwwwwwwwwe +5 22 wwwwwwwwwwwwwwwwwe +5 23 wwwwwwwwwwwwwwwpwwwwwwe +5 24 wwwwwwwwwpwwwwwwwe +5 25 wwwwwwwwpwwwwwe +5 26 wwwwpwwpwwwpwwwwwe +5 27 hwwwwwwwwwwwwwwwwwwpwwwwwwe +5 28 wwwwwwwwwwwpwwwwwe +5 29 wwwwwwwwwwpwwwe +5 30 wwwwwwwwwe +5 31 wwwwwwwwwwwpwwwwwwwwwwwpwwwe +5 32 wwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwe +5 33 wwwwwwwwwwwwwwwwwwwwwwwwpwwwwwpwwwwwe +5 34 wwwwwwwwpwwwwwe +5 35 wwwwwwwwwwwwwe +5 36 wwwwwwwwwwwwwwwwwwwwwpwwwe +5 37 wwwwwwwwwpwwwe +5 38 wwwwwwwwwwpwwwe +5 39 wwwwwwwwwwpwwwwe +5 40 wwwwwwwwwwwwwwpwwwwwe +5 41 hwwwwwwwwwwwwwwwwpwwwpwwwwwwwpwwwwwpwwwwwwwwwpwwwwwwwwwwpwwwwwwwwpwwwwpwwwwwe +5 42 wwwwpwwwwwwwpwwwwwwpwwwwwpwwwwe +5 43 wwwwwwwwwwwwpwwwe +5 44 wwwwwwpwwwwwwwwwwwwwwwwwpwwwwwwwwwpwwwwwwwwwe +5 45 wwwwwwwwwwwwwwwwpwwwwwwpwwwwwwwwwe +5 46 wwwwwwwwwwwwpwwwwwwwwwwwwwwe +5 47 wwwwwwwpwwwwwwwwwe +5 48 wwwwwwwwwwwwpwwwwwpwwwwwwwpwwwwwpwwwwwwwwwwwpwwpwwwwwwwwwe +5 49 wwwwwwwwwwwwwwwwwwpwwwwwwwwwwpwwwwwe +5 50 wwwpwwwwwwwe +5 51 hwwwwwwwwpwwwpwwwwwpwwwwwwe +5 52 wwwwwwwwwwwwpwwwwwwwwwwwwwwwwe +5 53 wwwwwwwwwpwwpwwwwe +5 54 wwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwpwwwe +5 55 wwwwwwwwwwwwwe +5 56 wwwwwwwwwwwe +5 57 wwwwwwwwwwwwwwwwwwpwwwwwe +5 58 wwwwwwwpwwwwwe +5 59 wwwwwwwwwwwwwwwwwwwwe +5 60 wwwwwwwwwpwwwwwwwwwwwpwwwwwwwe +5 61 wwwwwwwwwwwpwwwwwe +5 62 wwwwwwwwwpwwwwe +5 63 wwwwwwwwwpwwwwe +5 64 wwwwwpwwwwwpwwwwwwpwwwwwwwwwwpwwwwwwwpwwwwwwpwwwwpwwwwe +5 65 wwwwwwwwwwwwe +5 66 wwwwwwwwwwwwwwwwpwwwpwwwwwe +5 67 hwwwwwwwwpwwwwwwpwwwwpwwwwwwe +5 68 wwwwwwwwwwwwwwwpwwwwwwwwwwpwwwwwe +5 69 wwwwwwwwwwwwwwwwwwwwe +5 70 wwwwwwwwpwwwwwwwwwwwe +5 71 wwwwwwwwwwwwwwwpwwwwe +5 72 wwwwwwwwwwpwwwwwwwwpwwwwwwwwwwwpwwwwe +5 73 wwwwwwwwpwwwwwwpwwwwwwwwwwwe +5 74 wwwwwpwwwe +5 75 wwwwwwwwwwwwwpwwwpwwwwwwwwwe +5 76 wwwwwwwwwwwwpwwwwe +5 77 wwwwwwwwwwwwwwwwwwwwwwwe +5 78 wwwwwwwwwwwwpwwwwwe +5 79 wwwwwwpwwwwe +5 80 wwwwwwpwwwwwwwwwwwwwe +5 81 wwwwwwwwwwwwwwwe +5 82 hwwwwwwwwwpwwwwwwwwwpwwwwwwwwe +5 83 wwwwwwwwwwwwwwwpwwwwwwe +5 84 wwwwwwwwwwwwwwwwe +5 85 wwwwwwwwwwwpwwwe +5 86 wwwwwwwe +5 87 wwwwwwwwwwwwpwwwwwe +5 88 wwwwwwpwwwwwwe +5 89 wwwwwwwwwwwpwwwwwwwwwwwwwwpwwwwwwpwwwwwpwwpwwwwwwwe +5 90 wwwwwwwwwwwwwwwe +5 91 wwwwwwwwwwwwwwwwwpwwwe +5 92 wwwwwpwwwwwwwwe +5 93 wwwwwwwwwwwwwwwwwwwwwpwwwe +5 94 wwwwwwwwwwwwwwwwpwwwwwwwe +5 95 wwwwwwwwpwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwpwwwwwpwwwwe +5 96 wwwwwwwwpwwwwwwwpwwwwwe +5 97 hwwwwwwwwwwwpwwwwwwwwwwwwwwwwe +5 98 wwwwwwwwwe +5 99 wwwwwpwwwwwwe +5 100 wwwwwwwwwpwwwwwwe +5 101 wwwwwwwwwwwwwwwwwwwwwwpwwwe +5 102 wwwwwwwwwe +5 103 wwwwwwwwwwwpwwwwwwwpwwwe +5 104 wwwwwwwwwwwwwwwwpwwwwwwwwe +5 105 wwwwwpwwwwwwpwwwwwwwwe +5 106 wwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwwpwwwwwwwwe +5 107 wwwwwwwwwwwwwwwwwwwwwwwwwwe +5 108 wwwwwwwwwwwwwwpwwwpwwwwwe +5 109 hwwwwwwwpwwwwpwwwwe +5 110 wwwwwwwwwwwwwwwwwwwwpwwwwwwpwwwwwwwwwwwwpwwwwpwwwwpwwwwwwwwwwwwwwwwwe +5 111 wwwwwwwwwwwwwe +5 112 wwwwwwwwwwwwwwwpwwwwwwe +5 113 wwwwwwwwwwwwwwwe +5 114 wwwwwwwwwwwwwwwwwwpwwwwe +5 115 wwwwwpwwwwwwwwwwwwe +5 116 wwwwwwwwwwwwwwwpwwwwwwwwwwwpwwwwwpwwwwwwwwwpwwwwe +5 117 wwwwwwwwwwwwpwwwwwwpwwwwwwpwwwwwe +5 118 wwwwpwwwwwwwe +5 119 wwwwwwwpwwwwwwwwwpwwwwwpwwwe +5 120 wwwwwwpwwwwwe +6 1 wwwwwwwwwpwwwwwe +6 2 wwwwwwwwpwwwpwwwe +6 3 wwwwwwpwwwwwwe +6 4 wwwwwwwwwwwe +6 5 wwwwwpwwwwwwwe +6 6 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +6 7 wwwwwwwwwwwwwwwwe +6 8 wwwwwpwwwwwwwwe +6 9 wwwwwwwwwe +6 10 wwwwwwwwwwwwwe +6 11 wwwwwwwwwwe +6 12 wwwwwwpwwpwwwwpwwwwwwwpwwwwwwe +6 13 hwwwwwwpwwwe +6 14 wwwwwwwwwwwwpwwwwwwwwpwwwwe +6 15 wwwwwwwwwe +6 16 wwwwwwpwwwe +6 17 wwwwwwwwwpwwwwwwwwe +6 18 wwwwpwwwe +6 19 wwwwwpwwpwwwpwwwwwwwwpwwwwwwwpwwwpwwwwwwwwwe +6 20 wwwwwwwpwwwwwwe +6 21 wwwwwwwwwwpwwwwe +6 22 wwwwwwwwwwwwe +6 23 wwwwwwwwwwwwe +6 24 wwwwwpwwwwwe +6 25 wwwwpwwwwwwwwwpwwwwwwwpwwwwwwwwwwwwe +6 26 wwwwwpwwwwwwe +6 27 wwwwwwwwwwwwwwwwe +6 28 wwwwwwwwpwwwwwwwwe +6 29 wwwwwwwwwe +6 30 wwwwwwpwwwwpwwwpwwwwwwe +6 31 wwwwwwpwwwwwwwwwwwwwwwwpwwwwe +6 32 wwwwwwpwwwwwpwwe +6 33 wwwwwwpwwwwwwwwe +6 34 wwwwwwwwwwwwwpwwwwpwwwwwe +6 35 wwwwwwwwwwwwwwwwwwpwwwwwwpwwwwe +6 36 hwwwwpwwwwwwe +6 37 wwwwwwwpwwwwwwwwwwwwe +6 38 wwwwwwwwwwwwpwwwwwwpwwwwe +6 39 wwwwwwwpwwwwwwwwwwe +6 40 wwwwwwwwwwwwwwwe +6 41 wwwwwwwwwwwwe +6 42 wwwwwwwwwwwe +6 43 wwwwwwwwwwwwwwe +6 44 wwwwwwwwwwwwwwwwwwwwe +6 45 wwwwwpwwwwe +6 46 wwwwwwwwwwwwwwwwpwwwwwwwe +6 47 wwwwwwwwwwwwwwe +6 48 wwwwwwpwwwwwwwwwe +6 49 wwwwwwwwe +6 50 wwwwwwwwwwwwwwwpwwwwwwpwwwwwpwwe +6 51 wwwwwwwwpwwwwwwwwwe +6 52 wwwwwwwwwpwwwwwwwwwwwwwwwwe +6 53 wwwwwwwwwwwpwwwwe +6 54 wwwwwwwwpwwwwwpwwwwwwwwwwwwwwe +6 55 wwwwwwe +6 56 wwwwwwwwwwpwwwwpwwwwwwwe +6 57 wwwwwwwwpwwwwwpwwwwpwwpwwwe +6 58 wwwwwwwwwwwpwwwe +6 59 hwwwwwwwpwwwwwpwwwwwwwwwwwwwwwwwwwe +6 60 wwwwwwwwwwwwwwpwwwwwwwwe +6 61 wwwwpwwwwwwwwwwwwwe +6 62 wwwwwwpwwwwwwe +6 63 wwwwwwwwwwwwwwwwwe +6 64 wwwwwwwwwwe +6 65 wwwwwwwwwwwwwwwwwwwwwpwwwwwwe +6 66 wwwwwpwwwwe +6 67 wwwpwwe +6 68 wwwwwwwwwwwwwpwwwwwwwwwwe +6 69 wwwwwwwwwwwwe +6 70 wwwwwwwwwpwwwwwwwwwwwwwwwwwwwwwwpwwwwwpwwwwwwwwwe +6 71 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwpwwwwe +6 72 wwwwpwwwwe +6 73 wwwwwwpwwwwpwwpwwwwwwpwwwpwwwe +6 74 hwwwwwwwwpwwwwwwe +6 75 wwwwwwwwwe +6 76 wwwwwwpwwwpwwwwwwe +6 77 wwwwwwwpwwwwwwwwwwwe +6 78 wwwwwwwwwpwwwwwwwwe +6 79 wwwwwwwwpwwwwe +6 80 wwpwwwwwwpwwwwwwwwwwpwwwwwpwwe +6 81 wwwwwwwwwwwwwwwpwwwwpwwwe +6 82 wwwwwwwwwwwe +6 83 wwwwwwpwwwwpwwwwe +6 84 wwwwpwwpwwwwpwwwwwwwwpwwwe +6 85 wwwwpwwwe +6 86 wwwwpwwwwe +6 87 wwwwpwwwwwe +6 88 wwwwwwwwwpwwwwwwwe +6 89 wwwwwwpwwwwwwwwwwwe +6 90 wwwwpwwpwwwwwpwwwwwe +6 91 wwwwwwwwwwwwwwpwwwwwwwwwwwpwwwwwpwwwwwwwpwwpwwwwwe +6 92 wwwwwwwwwwwwwpwwwwwpwwwwe +6 93 wwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwpwwwwwwwwwwwwwwwe +6 94 wwwwwwwwwwwwpwwwwwwwwwpwwwwwwwwe +6 95 hwwwwwpwwwwwwwwpwwpwwe +6 96 wwwwwwwwpwwwwe +6 97 wwwwwwwwwwwpwwwwwe +6 98 wwwwwwwwpwwwwwe +6 99 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwpwwwwwwe +6 100 wwwwwpwwwwwwpwwwwe +6 101 wwwpwwwwwwwwpwwwpwwwwe +6 102 wwwpwwwwpwwwwpwwwwwe +6 103 wwwwwwpwwwe +6 104 wwwwwpwwwpwwwpwwwwe +6 105 wwwwwwwwe +6 106 wwwwwwpwwwwpwwwe +6 107 wwwwwpwwwwpwwwwe +6 108 wwwwwwwwwwwwpwwwwwwwwwwwwwe +6 109 wwwwwwwwwpwwwwwpwwwwwwwe +6 110 wwwwwwwwwwwwwe +6 111 hwwwwwwwwwwwwwwwwwwwwwwe +6 112 wwwwwwwwwwwwwwwpwwwwwpwwwe +6 113 wwwwwwwwwwwwe +6 114 wwwwwwwwwwpwwwwwwwwwpwwwwe +6 115 wwwwwpwwwpwwwe +6 116 wwwwwwwwwwpwwwwwwwwe +6 117 wwwwwwwwpwwwe +6 118 wwwwwwwwwwe +6 119 wwwwwwwwwwwwwwwwwwwpwwwwwwpwwwwwe +6 120 wwwwpwwwwwwwwe +6 121 wwwwwwwwwwpwwwwwwpwwwwe +6 122 wwwwwwwwwwwwwwwwwwpwwwwwwe +6 123 wwwwwwwwwpwwwwwwe +6 124 wwwwwwwwwwwwwpwwwwwpwwwwwwwwwwwe +6 125 wwwwwwwwpwwwwwwwwwwwwpwwwwwwwwe +6 126 wwwwpwwwwwe +6 127 hwwwwwpwwwwwe +6 128 wwwwwwwwwpwwwwwwwwwwwwwpwwwwwwwwwpwwwwe +6 129 wwwwwwwwe +6 130 wwwwwwwwwwwwwwpwwwwpwwwwwwwwwe +6 131 wwwwwwwwwwe +6 132 wwwwpwwwwwe +6 133 wwwwpwwwwwwwwwwwwwwe +6 134 wwwwpwwwe +6 135 wwwwwwwpwwwwwwwpwwwwe +6 136 wwwwwwwwwwwwwwpwwwwwwwpwwwwwwwpwwwe +6 137 wwwwwwwwwwwwpwwwwwpwwwe +6 138 wwwwwwwwwwwwwwwwwwwwwwpwwwwe +6 139 wwwwwwwwwwwpwwwwwwpwwpwwwe +6 140 wwwwwwwwwwwwwwwpwwwwwe +6 141 hwwwwwwwwwwwwwwwwpwwwwwwwwwpwwpwwwwe +6 142 wwwwpwwwwwwwwpwwwwe +6 143 wwpwwwwwwpwwwwwwwwwwpwwwwwe +6 144 wwwwwwpwwwwwwwwwwpwwwwwwwpwwwwwwwwwwwpwwwwwwe +6 145 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwe +6 146 wwwwwwwpwwwwwwwwwwwwwwwwpwwwpwwe +6 147 wwwwwwwwwwwwwe +6 148 wwwwwwwwwwwwwwpwwwwwwwwpwwwwwwwpwwwwwwwwe +6 149 wwwwpwwwwe +6 150 wwwwwwwwwpwwwwwpwwwwwwwwwwwwwe +6 151 hwwwwwwwpwwwwpwwpwwwwwpwwwpwwwwwwwwpwwwwwwwwpwwwwwe +6 152 wwwwwwwwwwwpwwwwpwwwwwpwwwwwwwpwwwpwwwwwe +6 153 wwwwwpwwwwwwwpwwwwwe +6 154 wwwwwwwwwwwwwwwwwe +6 155 wwwwwwwwe +6 156 wwwwwwwwwwwwwwe +6 157 wwwwwwwwwwpwwwwwwwpwwwwwwwwpwwwwwwwwwwe +6 158 wwwwwwwwwwwwwwpwwwwwwwwwwwwwwwwwwwpwwwwe +6 159 wwwwwwwwwwpwwwwwwwwwe +6 160 wwwwwwpwwwwwwwwwwe +6 161 wwwwwwwwwwwwpwwwwe +6 162 wwwwwwwwwe +6 163 wwwpwwwwwe +6 164 wwwwwwwwwpwwwwwwpwwwwwpwwwwwwwwwe +6 165 wwwwwwwwwwwwwwpwwwwwwwe +7 1 we +7 2 wwwwwwwwwwwwwe +7 3 wwwwwwwwwwwpwwwe +7 4 wwwwwwwwwwe +7 5 wwwwwwwwwwwwe +7 6 wwwwwwe +7 7 wwwpwwwe +7 8 wwwpwwwwwwe +7 9 wwwwwwwwwwwe +7 10 wwwwwwwwpwwwe +7 11 wwwwwwwwwwwwwwwwe +7 12 wwwwwwwpwwwwwwwwwwe +7 13 wwwwwwwwwwwwwe +7 14 wwwwwe +7 15 wwwwe +7 16 wwwwwwwe +7 17 wwwwwwwwwwwpwwwwe +7 18 wwwwwpwwwwwwwe +7 19 wwwwwwwwwwwwwwwwe +7 20 wwwwwwwwwwwwwwwwwwwwwwwwwe +7 21 wwwwwe +7 22 wwpwwwwwwwwwwwwpwwwwwwwwwwwwwwe +7 23 wwwwwwwwwwwwe +7 24 wwwwwpwwwwwwwe +7 25 wwwwwwwe +7 26 wwwwwwwwwpwwwwpwwwwwwe +7 27 wwwwwwwwwwwwwwwpwwwwwwwwpwwwwwwwe +7 28 wwwwwwwwwwpwwwwwwpwwwwwwe +7 29 wwwwpwwwwwwwwwpwwwe +7 30 wwwwwwpwwwwwwwwwwe +7 31 hwwwwwwwwwwwpwwwwe +7 32 wwwwwwwwwwwpwwwwwwwwwwpwwwwwe +7 33 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +7 34 wwwpwwwwwwpwwe +7 35 wwwwwwwwwpwwwwwwwwwe +7 36 wwwwwwwwpwwwe +7 37 wwwwwwwwwwpwwwwwpwwwwwwwwwwwwwpwwwwwwwwwe +7 38 wwwwwwwwwwwwwpwwwwwpwwwwwwwwwwwwwwwwpwwwwwwe +7 39 wwwwwwwwwwwwwwe +7 40 wwwwwwwwwwwwwwwwwwwwpwwwe +7 41 wwwwwwwpwwwe +7 42 wwwwwwwwwwwwpwwwe +7 43 wwwwwwwwwwpwwwwwwwwwwwwwpwwwwwpwwwwwwwwe +7 44 wwwwwwwwwwwwwwwwwwpwwpwwwwwwwwe +7 45 wwwwwwwwwwe +7 46 wwpwwwwwwpwwwwwwpwwwwe +7 47 hwwwwwwwwwwwwwe +7 48 wwwwwwwwwwwwwwe +7 49 wwwwwwwpwwwwwwwwe +7 50 wwwwwwwwwwwwwwpwwwwwwe +7 51 wwwwwwwwpwwwwwwwwwwwe +7 52 wwwwwwwwwwe +7 53 wwwwpwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwe +7 54 wwwwwwwwwwwwwwwwwwwwwwwwpwwwwpwwwwe +7 55 wwwwpwwwwe +7 56 wwwwwwwwwpwwwwwwe +7 57 wwwwwwwwpwwwwwwwwwwwwwwwwpwwwwwe +7 58 wwwwwwpwwwwwwpwwwwwe +7 59 wwwwwwwwwwwwwwwwwwwwe +7 60 wwwwwwwwwe +7 61 wwwwwwwwwwe +7 62 wwwwwwwwwwwe +7 63 wwwwwwwwwwwwwe +7 64 wwwwwwwwwwpwwwwe +7 65 hwwwwpwwwwwwwwwpwwe +7 66 wwwwwwwwwwwwwwe +7 67 wwwwwwwwwwe +7 68 wwwwwwwe +7 69 wwwwwwwwwwpwwwwwwwwwwwwpwwwwwe +7 70 wwwwwwwwwwpwwwwwwwe +7 71 wwwwwwwwpwwwwwwwwwwwwpwwwwwe +7 72 wwwwwwwwwwpwwwe +7 73 wwwwpwwwwwwwwwpwwwwwpwwwwwpwwwwwpwwwwwwe +7 74 wwwwwwwwwwwwwwwwwpwwwwwwwwe +7 75 wwwwwwwwwwwwwwwwwpwwwwwwe +7 76 wwwwwwwwe +7 77 wwwwwwwwwwwwwwwe +7 78 wwwwwwe +7 79 wwwwwwwwwwwwwwe +7 80 wwwwwwwwwwwwwe +7 81 wwwwwwwpwwwwe +7 82 wwwwwwwwwwpwwwe +7 83 wwwwwwwe +7 84 wwwpwwwwwe +7 85 wwwwpwwwwwwwwwpwwwwwpwwwwwwwwwwwwwpwwwwwwe +7 86 wwwwwwwwwwwwwwpwwwwwpwwwwwe +7 87 wwwwwwwwwwwwwwwwpwwwe +7 88 hwwwwwwwwwwwwwwwwwpwwwwe +7 89 wwwwwwwwwwwwwwpwwwwwwwwwwwpwwwwwpwwwpwwwwwwwwwe +7 90 wwwwwwwwwwwwe +7 91 wwwwwwe +7 92 wwwwwwwpwwwwwwe +7 93 wwwwwwwwwwpwwwwwe +7 94 wwwwwwwwwwwwwe +7 95 wwwwwwwwwwwwwwwwwwe +7 96 wwwwwwwwwwwwwwwwwwe +7 97 wwwwwwwwwe +7 98 wwwwwwwwwe +7 99 wwwpwwwwwwwe +7 100 wwwwwwwwwwwwwpwwwwwwe +7 101 wwwwwwpwwwwwwwwwwwpwwwwwwe +7 102 wwwwwpwwwwe +7 103 wwwwwwwwwwwpwwwwwe +7 104 wwwwwwwwe +7 105 wwwwwwwwwpwwwwwwwwwe +7 106 wwwwwwwwwwwe +7 107 wwwwwwe +7 108 wwwwwwe +7 109 wwwwwwwwwe +7 110 wwwwwpwwe +7 111 wwwwwwwe +7 112 wwwwe +7 113 wwwwwwwwwwwe +7 114 wwwwwe +7 115 wwwwwwwwwwe +7 116 wwpwwwwwwwwwe +7 117 hwwwwwwpwwwwwe +7 118 wwwwwwe +7 119 wwwwe +7 120 wwwe +7 121 wwwwe +7 122 wwwe +7 123 wwwwwwwwpwwwwwwwwwpwwe +7 124 wwwwwwwwe +7 125 wwwwwe +7 126 wwwwwwwwwwpwwwwwwe +7 127 wwwwwwwwwwwwwpwwwwwwwwe +7 128 wwwwwwpwwwwwwwwpwwe +7 129 wwwwwwwwwwpwwwwwwwwwwwwe +7 130 wwwwwwwwwwe +7 131 wwwwwwpwwwwwwwpwwwwwwwwwe +7 132 wwwwwwwwwwwwe +7 133 wwwwwwwwwwwwwe +7 134 wwwwwwwwwwwwpwwwwwwwwwwe +7 135 wwwwwwwwwwwe +7 136 wwwwwwwwwwwe +7 137 wwwwwwwwwwwpwwwwwwwwwpwwwwwwwwwe +7 138 wwwwwwwwwwwpwwwwwwwwpwwwwe +7 139 wwwwwwwwwwe +7 140 wwwwwwwwwe +7 141 wwwwwwwwpwwwwpwwwwwwe +7 142 hwwwwwwwwwwwpwwwwwwwwwwwwe +7 143 wwwwwwwwwwwpwwwwwwwwwwwwpwwwwwwwwwpwwwwwwwwwe +7 144 wwwwwwwwwwwwwwe +7 145 wwwwwwwwwwwwwwwwwpwwwe +7 146 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwe +7 147 wwwwwwwpwwwwwwe +7 148 wwwwwwwwwwwpwwwwwwwwpwwwe +7 149 wwwwwwwwwwwwwwwwwwe +7 150 wwwwwwwwwwwwpwwwpwwwwwwwpwwwwwwwwwwwwwwwwwe +7 151 wwwwwwwwpwwwe +7 152 wwwwwwwwwwwwpwwwe +7 153 wwwwwwwwwwwwwwe +7 154 wwwwwwwpwwwwwwwwe +7 155 wwwwwwpwwwwwwwwwwwpwwwwwpwwwwwwwwwwwpwwwwwpwwwe +7 156 hwwwwwwwwwwwpwwwwwwpwwwwpwwwwwwwwwe +7 157 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwpwwwe +7 158 wwwwwwwwwwwwwpwwwwwwpwwwwwwwwwwwwe +7 159 wwwwwwwwe +7 160 wwwwwpwwwwwwwwwwpwwwwwpwwwwwpwwwwwwwpwwwwwpwwwwwwe +7 161 wwwwwwwwwwwwwwwwwwpwwe +7 162 wwwwwwwwwwwwwwwwwe +7 163 wwwwwwwwwwwwwwwwwwwwpwwpwwwwwe +7 164 wwwwwwwpwwwwwwpwwwwwwe +7 165 wwwwwwwwwwwwwwwwwwe +7 166 wwwwwwwwwwwe +7 167 wwwwwwwwwwwwpwwwwpwwwe +7 168 wwwwpwwwwwpwwwwwe +7 169 wwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwpwwwwwpwwe +7 170 wwwwwwwwwwe +7 171 hwwwwwwwwwwwwwwwwwwwe +7 172 wwwwwwwwwwwwwwpwwpwpwwwwwwwwwe +7 173 wwwwwwwwwwwpwwwwe +7 174 wwwwwe +7 175 wwwwwwwwwwwwwe +7 176 wwwwwwwwwwpwwwwwwwwwwpwwwwwwpwwwwe +7 177 wwwwwwwwwe +7 178 wwwwwpwwwwwe +7 179 wwwwwwwpwwwwwwwwwwwwwwwpwwwwwpwwwe +7 180 wwwwwpwwwwwpwwwwe +7 181 wwwwwwwe +7 182 wwwwwwwwe +7 183 wwpwwwe +7 184 wwpwwwwpwwwwwe +7 185 wwwwwwwwwwwwwwwwwwpwwwwe +7 186 wwwwwwpwwwwe +7 187 wwwwwpwwwwwpwwwwwpwwwwpwwwwpwwwwpwwwwwwwwwwe +7 188 wwwwwwwwwwwpwwwwwwwwwwpwwwwwwwe +7 189 hwwwwwwwwwwwpwwwwwwwpwwwwwwwwwwwe +7 190 wwwwwwwwpwwwwe +7 191 wwwwwwwe +7 192 wwwwwwwe +7 193 wwwwwwpwwwwwwe +7 194 wwwwwwwwpwwwwwwe +7 195 wwwwpwwwwwpwwwwwpwwwwwpwwwwwwwe +7 196 wwwwwwpwwwe +7 197 wwwwwwwwwwe +7 198 wwwwwwpwwwwwwe +7 199 wwwwwwwe +7 200 wwwwwwwpwwwe +7 201 wwwwwwwwwwwwe +7 202 wwwwwwwe +7 203 wwwwwwwpwwwwwwwwpwwwwwwwwe +7 204 wwwwwwwwe +7 205 wwwwwwwwwwwwwwwwe +7 206 wwwwwwwwwwwse +8 1 wwwpwwwwpwwwwwpwwwwwwe +8 2 wwwwwwwwwwwwwwwwwe +8 3 wwwwwwe +8 4 wwwwpwwwwwwwe +8 5 wwwwwwwwwwwe +8 6 wwwwwwwwwwwwe +8 7 wwwwwwwwwwwwwwwwwwwwwwwe +8 8 wwwwwwwe +8 9 wwwwwwwwwwwe +8 10 wwwwwwwwpwwwwwwpwwwwe +8 11 wwwwwwwwwwwwwwwwwwwwwwe +8 12 wwwwwwwwwwpwwwwwwwwwwwwwe +8 13 wwwwwpwwwwwwwwe +8 14 wwwwwwe +8 15 wwwwwwwwwwwe +8 16 wwwwwwwwwwwwwwwwwwpwwe +8 17 wwwwwpwwwwwwwpwwwwwpwwwwe +8 18 wwwwwwe +8 19 wwwwwpwwwwwpwwwwwwwwwwwwwwe +8 20 wwwwwwwwwwwe +8 21 wwwwwwwwe +8 22 hwwwwwwwwwwe +8 23 wwwwwwpwwwwwe +8 24 wwwwwwwwwwpwwwwwwwwwwe +8 25 wwwwwwwwpwwwwwe +8 26 wwwwwwwwwwwwwwwwwwwe +8 27 wwwwwwwwwwwe +8 28 wwwwwwwwwwe +8 29 wwwwwwwwwwwwwwpwwwwe +8 30 wwwwwwwwwwpwwwpwwwe +8 31 wwwwwwwwwwwwpwwwwwe +8 32 wwwwwwwwwwwwwwwwwwwe +8 33 wwwwwwpwwwwwwe +8 34 wwwwwwwwwwwwwpwwwwwwwwe +8 35 wwwwwwwwpwwwwwe +8 36 wwwwwwwwwpwwwwwwwpwwwwwe +8 37 wwwwwwwwwwwwwwwpwwwe +8 38 wwwwwwwwwwwwwwwwe +8 39 wwwwwwwwwpwwwwwwwe +8 40 wwwwwwpwwwwe +8 41 hwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwe +8 42 wwwwwwwwwwpwwwwwpwwwwwwwwwwwwwwwwpwwwwe +8 43 wwwwwwpwwwwwwwwwwpwwwwe +8 44 wwwwwwwwwwwwwwwpwwwwe +8 45 wwwwwwwwwwwwe +8 46 wwwwwwwwpwpwwwwe +8 47 wwwwwwwwwwwwwpwwwwe +8 48 wwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwwwwpwwwe +8 49 wwwwwwwwwwpwwwwwwwwe +8 50 wwwwwwpwwwwwwwe +8 51 wwwwwwwwwe +8 52 wwwpwwwpwwwwwwpwwwwwe +8 53 wwwwwwwwwwwwwwpwwwwe +8 54 wwwpwwwpwwwwwwwwpwwwe +8 55 wwwwwwwwwwe +8 56 wwwwwwwwwwwwe +8 57 wwwwwwwwwwe +8 58 wwwwwwwwwpwwwwwe +8 59 wwwwwpwwwe +8 60 wwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwe +8 61 hwwwwwwwwpwwwwe +8 62 wwwwwwwpwwwwwe +8 63 wwwpwwwwwwwwwwwwwwpwwwe +8 64 wwwwwwwwe +8 65 wwwwwwpwwwwwwwpwwwwwwwwwwwwwe +8 66 wwwwwwwwpwwwwwwwpwwwwwwwwpwwwe +8 67 wwwwwwwwwwwpwwwwwwpwwwe +8 68 wwwwwwwwwwe +8 69 wwwwwpwwpwwwwe +8 70 wwwwwwwwwwwwwwwwwwwwwpwwwe +8 71 wwwwwwwwwwpwwwe +8 72 wwwwwwwwwwwwwwwwwpwwwwwwwwwwwwpwwwwwwwwwwwwpwwwwe +8 73 wwwwwpwwwwwwwwe +8 74 wwwwwwwwwwwwwwpwwwwe +8 75 wwwwwwwwwpwwwwwwwwpwwwwwe +9 1 wwwwwwwwwe +9 2 wwwwwwwwwwpwwwwe +9 3 wwwwwwwwwwwwwwpwpwwwwwpwwwwwwwpwwwwwe +9 4 wwwwwwwwwwwwwwwwwwpwwwwe +9 5 wwwwwwwwwwwwwwpwwwwwwwwpwwwwe +9 6 wwwwwwwwwwwwwpwwwwwe +9 7 wwwwwwwwwwwwwwpwwwwwpwwwwe +9 8 wwwwwwwwwwpwwwwwwe +9 9 wwwwwwwwpwwwwwe +9 10 wwwwwwwpwwwe +9 11 wwwwwwwwwpwwwwe +9 12 wwwwwwwwwwwwpwwwwwwe +9 13 wwwwwwwwwwwwpwpwwwwwwwe +9 14 wwwwwwwwwwwe +9 15 wwwpwwwwwpwwwe +9 16 wwwwwwwwwwwwwwwwwwwwpwwwwe +9 17 wwwwwwwwwwwpwwwwwwwe +9 18 wwwwwwwwwwwwwwwwwpwwwwwwe +9 19 hwwwwwwwwwwwwwwwpwwwwpwwwwwe +9 20 wwwwwwwwwwwwwpwwwe +9 21 wwwwwwwwwwe +9 22 wwwpwwwwwe +9 23 wwwwwwwwwwwwwpwwwwwwe +9 24 wwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwe +9 25 wwwwwwpwwpwwwwwwwwwwwwwwwe +9 26 wwwwwwwwwwwwwwwpwwwe +9 27 wwwwwwwwwpwwwe +9 28 wwwwwwwwwwwwwpwwwwwwwwwwpwwwwe +9 29 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +9 30 wwwwwwwwwwpwwwpwwwwwwpwwpwwe +9 31 wwwwwwwwwwwwwwwwpwwwwpwwwe +9 32 wwwwwwwwwwwwwwwe +9 33 wwwwwwwwwwwwwwe +9 34 hwwwwwwwwwwwwwwwwpwwwwwwwwwwwwe +9 35 wwwwwwwwwwwpwwwwwwwwe +9 36 wwwwwwwwwwwwwwwwwwpwwwpwwwwpwwwwwwpwwwwwe +9 37 wwwwwpwwwwwwwwwwwwwwwwwpwwwwpwwwwwe +9 38 wwwwwwwwwwwwwwwpwwwwwpwwwwwwwwe +9 39 wwwwwwwwwwwpwwwwwe +9 40 wwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwpwwwwpwwwe +9 41 wwwwwwwwwpwwwwwwe +9 42 wwwwwwwwwwwpwwwwwwwwwwwwe +9 43 wwwwwwwwwwwwwe +9 44 wwwwwwwwwwwpwwwe +9 45 wwwwwwwwwwwwwwe +9 46 hwwwwwwwwwwwwwwwe +9 47 wwwwwwwwwwwwwwpwwwe +9 48 wwwwwwwwwwwwwwwwe +9 49 wwwwwwwpwwwwpwwwwe +9 50 wwwwpwwwwwwwwwwwwe +9 51 wwwwwwwwwwpwwwwe +9 52 wwwwwwwpwwwwwwwwwwwpwwwwe +9 53 wwwwwwwwpwwwwe +9 54 wwwwwwwwwwwwwwwwwwwwwwe +9 55 wwwwwpwwwwwwwwwwwwe +9 56 wwwwwwwwwwe +9 57 wwwwwwwwwwwe +9 58 wwwwwwwwwwwwwwwwe +9 59 wwwwwwwwwwwwwwwwwwwe +9 60 hwwwwwwwwwwwwwwwwpwwwpwwwe +9 61 wwwwwwwpwwwwwwwwwwwwpwwwwwwwe +9 62 wwwwwwwwwwwwe +9 63 wwwwwwwwwwwwwpwwwe +9 64 wwwwwwwwwwpwwwwwwwe +9 65 wwwwwwwpwwwwwwe +9 66 wwwwwwpwwwwwwwwwwe +9 67 wwwwwpwwwwwwwpwwwpwwwwe +9 68 wwwwwwwwwpwwpwwpwwwe +9 69 wwwwwwwwwwwwwwwwwwwwwwwpwwwwwwpwwwe +9 70 wwwwwwwwwwwwwwwpwwwpwwwwwwwwe +9 71 wwwwwpwwwwwwwwwwwwpwwwpwwwwe +9 72 wwwwwwwwwwwwwwwwpwwwwpwwwwe +9 73 wwwwwwwpwwpwwe +9 74 wwwwwwwwwwwwwwwpwwwwwwwwwpwwwwwpwwwwwwwwwpwwwwwwwwe +9 75 hwwwwwwwwwwwwe +9 76 wwwwwwwwwe +9 77 wwwwwwwwwwwwwwwe +9 78 wwwwwwwwwwwe +9 79 wwwwwwwwwwwwwwpwwwwwwe +9 80 wwwwwwwwwwwwwwwpwwwwwpwwwwwe +9 81 wwwwwwwwwwwwwwwwwwwpwwwwwpwwwe +9 82 wwwwwwwwe +9 83 wwwwwwwwwwwwwwwwwpwwwwwwwwe +9 84 wwwwwwwwwwwpwwwwwwwe +9 85 wwwwpwwwwwwwwwwwwe +9 86 wwwwwwwwwwwwwwwwwwe +9 87 wwwwwwwwwwwe +9 88 wwwwwwwwpwwwpwwwe +9 89 wwwwwwwwwwpwwwe +9 90 wwwwwwwwwwwpwwwwwwe +9 91 wwwwwwwwwwwwwwwwwwpwwwwwpwwwe +9 92 wwwwwwwwwwwwwwwwwwwwwwwe +9 93 hwwwwwwwpwwwwwwwwwwwwe +9 94 wwwwwpwwwwwwwwwwwpwwwwwwwwwwwwwwe +9 95 wwwwwwwwpwwpwwpwwwwwwe +9 96 wwwwpwwwwwwwwwwe +9 97 wwwwwwwwwwwwwpwwwe +9 98 wwwwwwwwwwpwwwpwwwe +9 99 wwwwwwwwwwwwwwwpwwwwpwwwwpwwwwe +9 100 wwwwwwwwwwwwwwwwwwwwwwpwwwe +9 101 wwwwwpwwwpwwwwwpwwpwwwwwwwe +9 102 wwwwwwwwwwwwwpwwwwe +9 103 wwwwwwwwwpwwwwpwwwe +9 104 wwwwwwwwwwwwwwwwe +9 105 wwwwwwwpwwwwwwwwwe +9 106 wwwwwwwwwpwwwe +9 107 wwwwwwwwwwwwwwwpwwwwwpwwwwe +9 108 wwwwpwwwwwwwwwwwpwwwwwpwwwe +9 109 wwwwwwwwwwwwwwwwwwwwwwpwwwwwe +9 110 wwwwwwwwwwwwpwwwe +9 111 hwwwwwwwwwwpwwwwwwpwwwwwwwpwwwwwpwwwwwpwwwwe +9 112 wwwwwwwwwwwwwwpwwe +9 113 wwwwwwwwwwwwwwwwwwwwe +9 114 wwwwwwwwwwwwwwwwwwpwwwwe +9 115 wwwwwwwwwwwwwpwwwwwe +9 116 wwwwwwpwwpwwwwwwwwwe +9 117 wwwwwwwwwwwwwwwwwwwwwwwpwwwwe +9 118 wwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwe +9 119 wwwwwwwwe +9 120 wwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwe +9 121 wwwwwwwwwwwwwwwwwwe +9 122 hwwwwwpwwwwwwwwwwwwwwwwwe +9 123 wwwwwwwwwwwpwwwwwe +9 124 wwwwwwwwwwwpwwwwwwwe +9 125 wwwwwwwwwwwwe +9 126 wwwwwwwwwwwwwwwwe +9 127 wwwwwwwwwwwwwwpwwwwwwwe +9 128 wwwwwwwwwwwwwwe +9 129 wwwwpwwwwwwwpwwwwe +10 1 wpwwwwe +10 2 wwwwwwwwwwwwwwwwwwwwpwwwwwwe +10 3 wwwwwwwwwwwwwwpwwpwwwwwwwpwwwwpwwe +10 4 wwwpwwwpwwwwwwwwwwwpwwwwwwwwwwwe +10 5 wwwwwwwwwwwwwpwwwwwwpwwwwe +10 6 wwwwwwwwwwwwwwe +10 7 wwwwwwwwwwwwwwwe +10 8 wwwwwwe +10 9 wwwwwwwwpwwwwwwwe +10 10 wwwwwwwpwwwwwwwe +10 11 hwwwwwwwwwwpwwwwwwwwe +10 12 wwwwwwwwwwwwwwwwwwwwwpwwwwwwe +10 13 wwwwwwwpwwwwwwpwwwwe +10 14 wwwwwwwwwwe +10 15 wwwwwpwwwwwwwwwwwpwwwwwwwwwpwwwwwwpwwwwwwwwe +10 16 wwwwwwwwwwpwwwwwwpwwe +10 17 wwwwwwwwwwpwwwwe +10 18 wwwwwwwwwwwwwwpwwwwwwwwwwwpwwwwe +10 19 wwwwwwwpwwwwwwwwwwe +10 20 wwwwwwwpwwwwwwwwwe +10 21 wwwwwwwwwwwwwpwwwwpwwwwwe +10 22 wwwwwwpwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwe +10 23 wwwwwwwwwpwwwwwwpwwwpwwwwwwwe +10 24 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwe +10 25 wwwwwwwwwwwe +10 26 hwwwwpwwwwwwpwwwpwwwe +10 27 wwwwwwwwpwwwwwwpwwwwwwwpwwwpwwwe +10 28 wwwwwwwwwwpwwpwwwwwwe +10 29 wwwwwwwwwwe +10 30 wwwwwwpwwwwwpwwwwwe +10 31 wwwwwwwwwwwwwwwwwwwwwwpwwpwwwe +10 32 wwwwpwwwwwpwwe +10 33 wwwwwwwwwwe +10 34 wwwwwwwwwpwwwwwwpwwe +10 35 wwwwwwwwpwwwwpwwwwwwwwwwwwwpwwwwe +10 36 wwwwwpwwwwwwwpwwwwwe +10 37 wwwwwwwwwwwwwwwwwwwwwwe +10 38 wwwpwwwwwwwwwwwwwe +10 39 wwwwwwwwwpwwwwwpwwwwwe +10 40 wwwwwwwwwpwwwe +10 41 wwwwwwwpwwwwwwwwe +10 42 wwwwpwwwwwwwe +10 43 wwwwpwwwwwwwe +10 44 wwwwwwwwwwe +10 45 wwwwwwwwwwwpwwwwwwwwwe +10 46 wwwwwwwwwwwwwwwe +10 47 wwwpwwwwwwwwwe +10 48 wwwwwwwe +10 49 wwwwwwwwwwwpwwwpwwwwwwpwwe +10 50 wwwwwwwwwwwwe +10 51 wwwwwwpwwwwwe +10 52 wwwwwwwwwwwwwe +10 53 hwwwpwwwwwpwwwe +10 54 wwwwwwwwwwpwwwwwpwwwpwwwe +10 55 wwwwwwwpwwwwwwwwwe +10 56 wwwwwe +10 57 wwwwwwwwwwwwwwe +10 58 wwwwwwwwwwe +10 59 wwwwwwwwwwwwwwwwpwwwwe +10 60 wwwwwwwwwpwwwwwwwwwwe +10 61 wwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwwwwwwwwe +10 62 wwwwwwwwwwe +10 63 wwwwe +10 64 wwwwwwwpwwwwpwwwwe +10 65 wwwpwwwwpwwwe +10 66 wwwwwwwwwpwwwwwwwwpwwwwwwwwe +10 67 wwwwwwwwwpwwwwwwe +10 68 wwwwpwpwwpwwwwwwwpwwwwwpwwwwwwe +10 69 wwwwwwwwwe +10 70 wwwwwwwwwwwwwe +10 71 hwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +10 72 wwwwwwpwwwwwpwwwwwe +10 73 wwwwwwwwwwwwpwwwwwe +10 74 wwwwwwwwwwwwwwwwwpwwwwwe +10 75 wwwwwwwwwwwwwwe +10 76 wwwwwwwwwwe +10 77 wwwwwwpwwwwwe +10 78 wwwwwwwwwwwwwwwwe +10 79 wwwwwwe +10 80 wwwwwwwwwwe +10 81 wwwwwwwwpwwwpwwwwwwe +10 82 wwwwwwwe +10 83 wwwwwwwwwwwwwwpwwwwwwwwe +10 84 wwwwwwwwwwwwe +10 85 wwwwwwwwwwe +10 86 wwwwwe +10 87 wwwwwwwwwwwwwwpwwe +10 88 wwwwwwwwwwwwwwwwpwwwwwwwwwwwwwe +10 89 wwwwwwwwwwwe +10 90 hwwwwwwwwwpwwwwwwwwwwwwwwwwwwe +10 91 wwwwwwwe +10 92 wwwwwwwpwwwwwwwe +10 93 wwwwwwwwwwwwwwpwwwwwwwwwwe +10 94 wwwwwwwwwwwwwpwwwwwwwwwe +10 95 wwwwwwwwwwe +10 96 wwwwwwwwe +10 97 wwwwwwwwe +10 98 wwwwwwwwwwwwwwwwwwwwwe +10 99 wwwwwwwwwpwwwwwwe +10 100 wwwwwwwwpwwwwwwe +10 101 wwwwwwpwwwwwwwwe +10 102 wwwwwwwwwpwwwwwwe +10 103 wwwwwpwwwwwe +10 104 wwwwwwwwwwwwwwwwwwwwwpwwwwwe +10 105 wwwwwwwwwe +10 106 wwwwwwwwwwpwwwwwwe +10 107 wwwwwwwwwpwwwwwwpwwwwwwpwwwe +10 108 wwwwwwwwpwwwwwpwwwwwpwwwwe +10 109 wwwwwwwwpwwwe +11 1 wpwwwwwwwwwe +11 2 wwwwpwwwwwe +11 3 wwwwwwwwwwwwwwwwwpwwwwwwwwe +11 4 wwwpwwwwwe +11 5 wwwwwwpwwwwwwwwwpwwwwe +11 6 hwwwwwwwwwwwwpwwwwe +11 7 wwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwe +11 8 wwwwwwwwwwpwwwwwwwwwwwwe +11 9 wwwwwwwwwwwe +11 10 wwwwwwwwwwpwwwe +11 11 wwwwwwwwwwe +11 12 wwwwwwwwwwwwwwwwwwwpwwwpwwwwwe +11 13 wwwpwwwwwwwwwwwwwwwe +11 14 wwwwwwwwwwwwwpwwwe +11 15 wwwwwwwwwwwwwwe +11 16 wwwwwwwwpwwwwwwwwe +11 17 wwwwwwwwwwwwwwwpwwwpwwwwwwwpwwwwwpwwwwwwwwwe +11 18 wwwwwwwpwwwwwwwwwwwpwwwwwe +11 19 wwwwwwwwwwwe +11 20 wwwwwwwwwwwwwwpwwwpwwwwwwwe +11 21 wwwwwwwwwe +11 22 wwwwwwwe +11 23 wwwwwwwwwwwpwwwe +11 24 hwwwwwwpwwwpwwe +11 25 wwwwwwwwwe +11 26 wwwwwpwwwwwwe +11 27 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +11 28 wwwwwwwwwwwwwwwwwwwe +11 29 wwwwwpwwwwwpwwwwwpwwwwwwwe +11 30 wwwwwwwpwwe +11 31 wwwwwwwwwwwwwwwwwwwwwwpwwwwwpwwwwe +11 32 wwwwwwwwwwwwwe +11 33 wwwwwwwwwwe +11 34 wwwwwwwwwwwwwwpwwwwe +11 35 wwwpwwwwwwwwwe +11 36 wwwwwwwwwwwwwwwwwe +11 37 wwwwwwwwwpwwe +11 38 wwwwwwwwwwpwwwwwwwwwe +11 39 wwwwwwwwwwe +11 40 wwwwwwwwwwwwwwwwwwwwwpwwwwwe +11 41 hwwwwwwwpwwwwe +11 42 wwwwwwwwwwwwwwwwwwwe +11 43 wwwwwwwpwwwwwwwwwwpwwwwwwe +11 44 wwwwwwwwwwwwwpwwwwe +11 45 wwwwwwwwwwwwwwwe +11 46 wwwwwwpwwwwpwwwwwwwpwwwwwwe +11 47 wwwwwwwwwwwwpwwwwwwwe +11 48 wwwwwwwwwwwpwwwwwwwe +11 49 wwwwwwpwwwwwwwwwpwpwwwe +11 50 wwwwpwwwwwwwwwpwwwwe +11 51 wwwwwpwwwwwwpwwe +11 52 wwwwwwwwwwwwwwwwwe +11 53 wwwwwwwwwwwwwwwe +11 54 wwwwwwwpwwwwwwwwwe +11 55 wwpwwwwwe +11 56 wwwwwwpwwwwwwwpwwwwwe +11 57 wwwwwwwwpwwwwwwwpwwwwwwe +11 58 wwwwwwwwwwwwwwe +11 59 wwpwwwwwwwwwwe +11 60 wwwwwwwpwwwwwpwwwwwe +11 61 hwwwwpwwwwwwwwwpwwwwwwwwwwpwwwwe +11 62 wwwwwwwwpwwwwwwwwwwwwwe +11 63 wwwwwwwwwwwwwwwwwwpwwwwe +11 64 wwwwwwwwwwwwwwwwwe +11 65 wwwwwwwpwwwwe +11 66 wwwwwwwwwwwwwpwwwwwe +11 67 wwwwwwwwe +11 68 wwwwpwwwwwpwwwe +11 69 wwwwwwwpwwpwwwwwwe +11 70 wwwwwwwwwwpwwwwwwwwe +11 71 wwwwwwwwwe +11 72 wwwwwwwwpwwwwe +11 73 wwwwwpwwwwwwpwwwe +11 74 wwwwwwwwwwwe +11 75 wwwwwe +11 76 wwwwpwwwwwpwwwwwe +11 77 wwwwwwwwwwwwwe +11 78 wwwwwwwwwpwwwwwwwpwwwwwwpwwwwe +11 79 wwwwwwwwwwwwwe +11 80 wwwwwwwwwwwe +11 81 wwwwwwwwpwwwwwwwwwwwpwwwwpwwwpwwwe +11 82 wwwwwwwwwwwwe +11 83 wwwpwwwwwe +11 84 hwwwwpwwwwwwwwwpwwwwpwwwwwwwwwe +11 85 wwwwwpwwwwwwwwwe +11 86 wwwwwwwpwwwwe +11 87 wwwwwwwwwwwwwwwwpwwwwe +11 88 wwwwwwwwwwwwwpwwwwwwwwpwwwwwwpwwwwpwwwwe +11 89 wwwwwwwwwwwwwwwwwpwwwwwe +11 90 wwwwwpwwwwe +11 91 wwwwwwwwwwwpwwwpwwwwe +11 92 wwwwwwwwwwpwwwwwe +11 93 wwwwwwpwwwwwwwwwpwwwwe +11 94 wwwwwwwwwwwwwwwwwwe +11 95 wwwwpwwwwwwe +11 96 wwwwwwe +11 97 wwwwwwpwwwwe +11 98 wwwwwwpwwwe +11 99 wwwwwwpwwwe +11 100 wwwwwwpwwwe +11 101 wwwwwpwwwwwwwwwwwwwwwpwwwwe +11 102 wwwwwwwwpwwwwe +11 103 wwwwwwwwpwwwwwwwwe +11 104 wwwwwe +11 105 wwwwwwwpwwwe +11 106 wwwwwwwwwe +11 107 wwwwwwwwwwpwwwwwe +11 108 hwwwwwwwwwwwwwwwpwwwe +11 109 wwwwwwwpwwwwwwwwpwwwwwe +11 110 wwwwwwpwwwwwwwpwwwwwe +11 111 wwwwwwpwwwwe +11 112 wwwwwwwwpwwwwe +11 113 wwwwwwwwwwwwwwwwwe +11 114 wwwwwwwpwwwwpwwwe +11 115 wwwwwwwe +11 116 wwwwwwwwwwwwwwwwwwpwwwwwwwwe +11 117 wwwwwwwwe +11 118 wwwwwwwpwwwe +11 119 wwwwpwwpwwwwwwwwwe +11 120 wwwwwwwwwwpwwwwwwwe +11 121 wwwwwwwwwe +11 122 wwwe +11 123 wwwwwwwwwwwpwwwwwe +12 1 wpwwwwe +12 2 wwwwwwe +12 3 wwwwwwwwwwwwwwwwe +12 4 wwwwwwwwwwwwwwwe +12 5 wwwwwwwwwwpwwwwwe +12 6 wwwwwwwwwwwwwwwwwwwwwpwwwwe +12 7 hwwwwwwwe +12 8 wwwwwwwwwwwwwwwe +12 9 wwwwwwwwwwwwwwe +12 10 wwwwwwwwwwwwwwwwe +12 11 wwwwwwwwwwwe +12 12 wwwwwwwwe +12 13 wwwwwwwwwwwwwe +12 14 wwwwwwwwwe +12 15 wwwwwwwwwpwwwwwwwwe +12 16 wwwwe +12 17 wwwwwwwwwwwpwwwwwwwe +12 18 wwwwwpwwwwwwpwwpwwwwwe +12 19 wwwwwwpwwwwpwwpwwwwe +12 20 wwwwwwwwwe +12 21 wwwwwwwwwwwwwwpwwwwwwwwwpwwwwwwwwwe +12 22 wwwwwwpwwwe +12 23 wwwwwwwwwwwwpwwwpwwwwpwwwwe +12 24 wwwpwwwwwwwpwwwwwpwwwwe +12 25 wwwwwwwwwwpwwwwwwwwwwwwwe +12 26 wwwwwpwwwwwwwwwwwwwwe +12 27 wwwwwwwwwwe +12 28 wwwwwwwwwwpwwwe +12 29 wwwwpwwpwwwwe +12 30 hwwwwwwwwwwpwwwpwwwwwe +12 31 wwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwwe +12 32 wwwwwpwwwwwpwwwwwwwwwe +12 33 wwwwwwwwpwwwwwwwwwe +12 34 wwwwwwpwwwwe +12 35 wwwwwwwwwwwe +12 36 wwwwpwwwwwwpwwwwwwwwwwwpwwpwwwwe +12 37 wwwwwwwwwwwpwwwwpwwwwwwwwwwwe +12 38 wwwwwwpwwwwwwwwpwwwwwwwwwwwwe +12 39 wwwwwwwwwe +12 40 wwwwwwwwwwwwwwwpwwwwpwwwwwpwwwwwwwwe +12 41 wwwwwwwpwwwwwwwpwwwwwe +12 42 wwwwwwwwwwwwwwwwwwe +12 43 wwwwwwwwwwwwwwwpwwwwwwwwwe +12 44 wwwpwwwwwe +12 45 wwwwwwwwwwwe +12 46 wwwwwwwwwwwwwwwwwwwwwwe +12 47 wwwwwwwwwwwwwwe +12 48 wwwwwwwwwwwwwwwe +12 49 wwwwwwwwwwwe +12 50 wwwwpwwwwwwwwwwwwwwpwwwwe +12 51 wwwwwwwwpwwwwwwwwpwwwwwwwwwwwwwe +12 52 wwwwwwwwwwwwe +12 53 hwwwpwwwwwwwwpwwwwe +12 54 wwwwwwpwwwwwwwwe +12 55 wwwwwpwwwe +12 56 wwwwwwwwwpwwwwpwwwwe +12 57 wwwwwwwe +12 58 wwwwwwwwwe +12 59 wwwwwwwwwpwwwwwwwwe +12 60 wwwwwwwwwwe +12 61 wwwwwwe +12 62 wwwwwwwwwwwwwwe +12 63 wwwwwwwwwwwwwwwwe +12 64 wwwwwwwwwwwpwwwpwwwe +12 65 wwwwwwwpwwwwpwwwwpwwwwwwwpwwwe +12 66 wwwwwwwwwwwwwwwpwwwwwwwwwe +12 67 wwwwwwwwwwwpwwwwwwwpwwwwpwwpwwwe +12 68 wwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwe +12 69 wwwwwwwpwwwwwwwwwe +12 70 wwwwwwwwwwwwwwwe +12 71 wwwwwe +12 72 wwwwwwwwwwwwe +12 73 wwwwwwwwwwwwe +12 74 wwwwwwe +12 75 wwwwwwwwpwwwe +12 76 wwwwwwwwwwpwwwpwwwwwwwwwwwpwwwwpwwwwwe +12 77 hwwwwwwwwwpwwwwwwwpwwwwpwwwwe +12 78 wwwwwwwwwwwpwwwwe +12 79 wwwwwwwwwwwwwe +12 80 wwwwwpwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwpwwwe +12 81 wwwwwwwwwwwwwwwwwe +12 82 wwwwwwwwwpwwe +12 83 wwwwwwpwwpwwwwwwpwwwwe +12 84 wwwwwwwwwwwwe +12 85 wwwwwwwwwwwwe +12 86 wwwwwwwwwwwwwe +12 87 wwwwwwwwwwwpwwwwwwwwwe +12 88 wwwwwwwwwwwwwwwwwpwwwwe +12 89 wwwwwwwwwwe +12 90 wwwwpwwwwwpwwwwpwwwwwwwwwwe +12 91 wwwwwwwwwe +12 92 wwwwwpwwwpwwwe +12 93 wwwwwwwwwwwwe +12 94 wwwwwwwwwpwwwe +12 95 wwwwwwe +12 96 wwwwwwwwwpwwwwwwwwwwwe +12 97 wwwwwwwwe +12 98 wwwwwpwwwwe +12 99 wwwwwwwwwwwwwwe +12 100 wwwwwwwpwwwwwwwwwwwpwwwwwwwwwwwwwwwwwwwpwwwwwpwwwwe +12 101 hwwwwwwwwwpwwwwwwwwpwwwwe +12 102 wwwwwwpwwwwwwwwe +12 103 wwwwwwe +12 104 wwwwwpwwwwwe +12 105 wwwwwwwwwwwe +12 106 wwwwwwwe +12 107 wwwwwwwwwwwwwwe +12 108 wwwwwwpwwwwwpwwwwwwe +12 109 wwwwwwwwwwwpwwwwwwwwwwwpwwwwwpwwe +12 110 wwwwwwwwwwwwwpwwwwwwe +12 111 wwwwwwwpwwwwwwwwwwwwwwwwe +13 1 wpwwwpwwwwwwwwwwwe +13 2 wwwwwwwpwwwwpwwwpwwwwpwwwwwwwwe +13 3 wwwwwwwwpwwwwwwwpwwwpwwwwwwe +13 4 wwwwwwwwwwwwwwwwwwwwwpwwwwwwe +13 5 hwwwwwwwwwwwpwwwwpwwwwpwwwpwwwe +13 6 wwwwwwwwwpwwwwwwwpwwwwe +13 7 wwwwwwwwwpwwwpwwwe +13 8 wwwwwwwwwwwpwwwwe +13 9 wwwwwe +13 10 wwwwwwwwwwwwwwe +13 11 wwwwwwwwwwwpwwwwwwwwwwpwwwwwwwwpwwwwwwe +13 12 wwwwwwwwwe +13 13 wwwwwwwwwwwwwwwwwwwe +13 14 wwwpwwwwwwwwwwwwwwwwwwpwwwwwwe +13 15 wwwwwwwwwwwse +13 16 wwwwwwwpwwwwwwwwwwwpwwwwwwwwwwpwwwwwwwwwpwwwwwwwwe +13 17 wwwwwwwwwwwpwwwwwwwwwwwpwwwwwpwwwwpwwwwwwwpwwwwe +13 18 wwwwpwwwwwwwwwwwwwwwpwwwwwwpwwe +13 19 hwwwwwwwwwwwpwwwwe +13 20 wwwwwwwe +13 21 wwwwwwwwwwwwwe +13 22 wwwwwwwwwwwwwwwwwwwe +13 23 wwwwwwwwwpwwwwwwe +13 24 wwwwpwwwe +13 25 wwwwwwwwwwwwwwwwwpwwwwwwe +13 26 wwwwwwpwwwwwwwwwwe +13 27 wwwwwwwwwpwwwwwwwwwwe +13 28 wwwwwwpwwwwwe +13 29 wwwwwwwwe +13 30 wwwwwwwwwwwwwwwwwpwwwwwwwwwwwe +13 31 wwwwwwwwwwwwwwpwwwwpwwwwwwwwwwwpwwwwwwwwwwwwwwwwwpwwwwwe +13 32 wwwwwwwwwwpwwwe +13 33 wwwwwwwwpwwwwwpwwwwwwwwwwwpwwwwwwwwpwwwwwwwe +13 34 wwwwwpwwwpwwwwwwe +13 35 hwwwwwpwwwwpwwwpwwwwpwwwe +13 36 wwwwwwwpwwwwwpwwwwwwwwwpwwwwe +13 37 wwwwwwwwwwwwwwwwwwwwe +13 38 wwwwwwwwwpwwwwwwwwwpwwwe +13 39 wwwwwpwwwe +13 40 wwwwwwwwwwwwwe +13 41 wwwwwwwwpwwwwwpwwwe +13 42 wwwwwwwwpwwwwwpwwwwwe +13 43 wwwwwpwwwwwwwwwwe +14 1 wpwwwwwwwwwwwwwwwe +14 2 wwwwwwwwwpwwwwwe +14 3 wwwwwwwwwwwwpwwwwe +14 4 wwwwwwwwwpwwwwwwwpwwwe +14 5 wwwwwwwwwwwwwwpwwwwwwwe +14 6 wwwwwwwwwwwwwwwwwwwwpwwwwwwe +14 7 wwwwwwpwwwwwe +14 8 wwwwwwwwwwwwwe +14 9 wwwwwwwwwwpwwwpwwwwpwwwwwwwwwwwwwwwwwwwwe +14 10 hwwwwwwwwpwwwwwwwwwpwwwwwwwwwwwwwwwwe +14 11 wwwwwwwwwwwwwwwwpwwwwwwwwwpwwwwe +14 12 wwwwwwwwwpwwwwpwwwwe +14 13 wwwwwwwwwwwpwwwwwe +14 14 wwwwpwwwwwwe +14 15 wwwwwe +14 16 wwwwwwwe +14 17 wwwwwwwwwwwwpwwwwe +14 18 wwwwpwwwwwwwwpwwwwwwpwwwwe +14 19 wwwwwwwwpwwwwwwe +14 20 wwwwwe +14 21 wwwwwwwwwwwwwwwwwwwwpwwwwwpwwwwwwwwwe +14 22 wwwwwwwwwwwwpwwwwwwwwwwwpwwwwpwwwwwwpwwwwwwpwwwwwe +14 23 wwwwwwwwwwwwwwpwwwe +14 24 wwwwwwwwwwwwwwwe +14 25 wwwwwwpwwwwwwe +14 26 wwwwwwwwwwwwwe +14 27 wwwwwwwwwwwpwwwpwwwwe +14 28 hwwwwwwwwwwwwe +14 29 wwpwwe +14 30 wwwwwwpwwwwwwe +14 31 wwwwwwwwwwwwwwwwwwwwwe +14 32 wwwwwwwwwwwwwwwpwwwwwwwpwwwe +14 33 wwwwwpwwwwe +14 34 wwwwwpwwwwwwpwwwwe +14 35 wwwwwwwwwwwwwe +14 36 wwwwwwpwwwwpwwwwwe +14 37 wwwwwwwwwwwwwwwwwwwwwwwwwwe +14 38 wwwwwwwpwwwwwwwwwwwe +14 39 wwwwwwwwwpwwwwe +14 40 wwwwwwpwwwe +14 41 wwwwwwwwe +14 42 wwwwwwwpwwwwwwe +14 43 wwwwwwwpwwe +14 44 wwwwwwwwwwwwwwwwwpwwwwwwwwwe +14 45 wwwwwwwwwwwwwwe +14 46 wwwwwwwwwwwwe +14 47 wwwwwwpwwwwwe +14 48 wwwwwwpwwwwe +14 49 wwwwwwe +14 50 wwwwwwe +14 51 wwwwwwpwwwwe +14 52 wwwwwwwwwwwwwe +15 1 wpwwwwwe +15 2 wwwwwwwe +15 3 wwwwwpwwe +15 4 wwwwwwwwe +15 5 wwwwwwwe +15 6 wwwwwwwwe +15 7 wwwwwwwwe +15 8 wwwwwwwwwe +15 9 wwwwwwwe +15 10 wwwwwwwe +15 11 wwwwwwwwe +15 12 wwwwwe +15 13 wwwpwwwwe +15 14 wwwwwwwwwe +15 15 wwwwwwwwe +15 16 wwwwwwwe +15 17 wwwwwe +15 18 wwwwwwwe +15 19 wwwwwwwwwwwe +15 20 wwwwwwwwe +15 21 wwwwwwwwwwwe +15 22 wwwwwwwwwwwwe +15 23 wwwwwwe +15 24 wwwwwwwe +15 25 wwwwpwwwe +15 26 wwwwwwwwe +15 27 wwwwwwwe +15 28 wwwwwwwwwwwwe +15 29 wwwwwwwwwe +15 30 wwwwe +15 31 wwwwwwwe +15 32 wwwwwwwwe +15 33 wwwwwwwwwwwe +15 34 wwwwwe +15 35 wwwwwwe +15 36 wwwwwwe +15 37 wwwwe +15 38 wwwwe +15 39 wwwwwwwwwwe +15 40 wwwwe +15 41 wwwwwe +15 42 wwwwwwwwwwwe +15 43 wwwwe +15 44 wwwwwwwwe +15 45 wwwwwe +15 46 wwwe +15 47 wwwwwwwwwwe +15 48 wwwwwwwwe +15 49 hwwwwwwe +15 50 wwwwwe +15 51 wwwwe +15 52 wwwwwwwwwe +15 53 wwwwwwwe +15 54 wwwwwwwwe +15 55 wwwwwwwe +15 56 wwwwwwwwe +15 57 wwwwwe +15 58 wwwwwwe +15 59 wwwwwwe +15 60 wwwpwwwe +15 61 wwwwwe +15 62 wwwwe +15 63 wwwwwwwe +15 64 wwwwe +15 65 wwwwwwwwwwwwwwe +15 66 wwwwwwwwwe +15 67 wwwwe +15 68 wwwwwwe +15 69 wwwwe +15 70 wwwwwe +15 71 wwwwwwe +15 72 wwwwwe +15 73 wwwe +15 74 wwwwwwwwe +15 75 wwwwwe +15 76 wwwe +15 77 wwwwwe +15 78 wwwwwe +15 79 wwwwwe +15 80 wwwwwe +15 81 wwwwwe +15 82 wwwwwwe +15 83 wwwe +15 84 wwwwwwe +15 85 wwwwwwwwpwwwpwwwe +15 86 wwwwwe +15 87 wwwwwwwe +15 88 wwwwwwwwwwwwwwwe +15 89 wwwwwe +15 90 wwwwe +15 91 wwwwe +15 92 wwwe +15 93 wwwe +15 94 wwwwwwe +15 95 wwwe +15 96 wwwwwwpwwe +15 97 wwwwwwwe +15 98 wwwwwwe +15 99 wwwwwe +16 1 wwwwwpwwwwe +16 2 wwwwwwwwwwwwwwwwwwe +16 3 wwwwpwwwe +16 4 wwwwwwwwe +16 5 wwpwwwwwwe +16 6 wwwwwwwe +16 7 wwwwwwwwwwpwwwwe +16 8 wwwwwpwwwwe +16 9 wwwwwwpwwwwe +16 10 wwwwwwpwwwwwwwe +16 11 wwwwwwwwwwpwwwwwwe +16 12 wwwwwwpwwwpwwwwwwe +16 13 wwwwwwwpwwwwwwe +16 14 wwwwwwwwwwwwwwwwwwwwwe +16 15 wwwwwwwwwwwe +16 16 wpwwwe +16 17 wwwwwpwwe +16 18 wwwwwwpwwwwe +16 19 wwwwwwe +16 20 wwwwwwwwwwe +16 21 wwwpwwwwe +16 22 wwwpwwwwwwwwe +16 23 wwwwwwwwwpwwwwe +16 24 wwwwwwpwwwe +16 25 wwwwwpwwwwwwpwwwwe +16 26 wwwwwwwwwwwwwwwwwwwwwe +16 27 wwwwwwwwwwwpwwwwwwwwwwe +16 28 wwwwwpwwwwwwwpwwwwwwwe +16 29 wwwwwpwwwe +16 30 hwwwwwwpwwpwwwwwwpwwwpwwwe +16 31 wwwwwwwpwwwwpwwwwe +16 32 wwwwpwwwwwwwwe +16 33 wwwwwwwwwwpwwwwwpwwwwwwwe +16 34 wwwwwwwwwwe +16 35 wwwwwwwwwwwwwwwwwwwwwpwwwwwpwwwwwwe +16 36 wwwwwwwwwwwpwwwwwwwwwpwwwwwwwwe +16 37 wwwwwwwwwwpwwwwe +16 38 wwwwpwwwwwpwwwwwwwwwe +16 39 wwwwwwwwwwwe +16 40 wwwwwwwwwwe +16 41 wwwwwwwwwwwwpwwwpwwwe +16 42 wwwwwe +16 43 wwwwwwwwpwwwwwwwe +16 44 wwpwwwwwwwwwwe +16 45 wwwwwwwwwwwwwwwwe +16 46 wwwwwwwe +16 47 wwwwwwwwe +16 48 wwwwwwwwwwwwwwwwwe +16 49 wwwwwwwwwwwwwwe +16 50 wwwwwwwse +16 51 hwwwwwwpwwwwpwwe +16 52 wwwwwwwwpwwwe +16 53 wwwwwwpwwwwwwe +16 54 wwwwwwwwwwe +16 55 wwwpwpwwe +16 56 wwwwwwwpwwwwwe +16 57 wwwwpwwwe +16 58 wwwwwwwwwe +16 59 wwwwwwwwpwwwwwwwpwwwwe +16 60 wwwwwwpwwwpwwwe +16 61 wwwwwwwwwwwwwwwpwwwwwwpwwe +16 62 wwwwwwwwwwpwwwwwwwe +16 63 wwwwwwwwwwwwwwwwwe +16 64 wwwwwwwwwwpwwwwe +16 65 wwwwwwwwwwpwwwwwwe +16 66 wwwwwpwwwwwwwwwwwwe +16 67 wwwwwwwwwpwwwwwwe +16 68 wwwwwwwwwwwwwe +16 69 wwwwwwwwwpwwwwwwwwwpwwwwwwe +16 70 wwwwpwwwwwwwwwwwwpwwwwe +16 71 wwwwwwwpwwwwwwwwwwwwpwwwe +16 72 wwwwwwwwwwwwwwwpwwwwwwe +16 73 wwwwwwwwwwwwwwwe +16 74 wwwwpwwwwwwe +16 75 hwwwwwwwwwwwwwwwwwwwpwwpwwpwwwwe +16 76 wwwwwwwwwwwwwwwwwwwpwwwwwwpwwwwe +16 77 wwwwpwwwwwwwwwpwwwwwwe +16 78 wwwwwwwwwwwwwpwwe +16 79 wwwwwwwwwwwwpwwwwwwe +16 80 wwwwwwwwwwwwwwwwwpwwwwwwwwe +16 81 wwwwwwwwwwwwwwwwwwwpwwwwwwe +16 82 wwwwwwe +16 83 wwwwwwwe +16 84 wwwwwwwwwwwwwwe +16 85 wwwwwwwwwwwe +16 86 wwwwwwwwwwwwwwpwwwwwe +16 87 wwwwwpwwwwwe +16 88 wwwwwwwwwwwwwe +16 89 wwwwwwwwwpwwwwwpwwwwwwwwwwe +16 90 hwwwwwwwwwwwwwpwwwe +16 91 wwwwwwwwwwwwwwwpwwwwwe +16 92 wwwwwwwwwwwwwwwwwwwwpwwwwpwwwwwwwwe +16 93 wwwwwwwwwwwwwpwwwwe +16 94 wwwwwwwwwwwwwwwwpwwwe +16 95 wwwwwwpwwwwwwwwwe +16 96 wwwpwwwwpwwwwwwwwe +16 97 wwwwwwwwwwwwpwwwwwwe +16 98 wwwwwwwwe +16 99 wwwwwwwwwwe +16 100 wwwwwwwwwe +16 101 wwwwwpwwwwwwwwpwwwwe +16 102 wwwwwwwwwwwwwe +16 103 wwwwwwwpwwwwwwwwwe +16 104 wwwwwwwwwwwwe +16 105 wwwwwwwwpwwwe +16 106 wwwwwwwwwwwwwwwwwwwwwwwwe +16 107 wwwwwwwwwwwwwe +16 108 wwwwwwwwpwwwe +16 109 wwwwwwwe +16 110 wwwwwwwwwwwwwwwwwwe +16 111 hwwwwwwwwwwwwwwwe +16 112 wwwwwwwwwwwwwwwwwwwwwwwwe +16 113 wwwwwwwwwe +16 114 wwwwwwwwwwwwwe +16 115 wwwwwwwwwwwwpwwwwwwwwwwe +16 116 wwwwwwwwwwwwwwpwwwwwwwwe +16 117 wwwwwe +16 118 wwwwwwwwwpwwwwwwe +16 119 wwwwwwwwwwwwwwwwwwwe +16 120 wwwwwwwwwwwe +16 121 wwpwwwwwe +16 122 wwwwpwwwwwe +16 123 wwwwwwwwpwwwwe +16 124 wwwwwwwpwwwwwwwwwwe +16 125 wwwwwwwpwwwwpwwwwwwwwpwwwe +16 126 wwwwwwwpwwwwwe +16 127 wwwwwpwwwwwwwwwe +16 128 wwwwwwwwe +17 1 wwwwwwwwwwwwwwwwwpwwwwe +17 2 wwwwwwwwwwwwe +17 3 wwwwwpwwwwe +17 4 wwwwwwwwwwwwwe +17 5 wwwwwwwwwwwwwwpwwwe +17 6 wwwwwwwwwwwe +17 7 wwwwpwwwpwwwwwwwwwwwwwwwwe +17 8 wwwwpwwwpwwwwe +17 9 wwwwwwwwwwwwwwwwe +17 10 wwwwwwwwwe +17 11 wwwwwpwwwe +17 12 wwwwpwwwwwwwwwwwwwwwpwwwwe +17 13 wwwwwwpwwwwwwwe +17 14 wwwwwwwe +17 15 wwwwwpwwwwwpwwwwwpwwwwwwe +17 16 wwwwwwwwwwwwwwe +17 17 wwwwwwwpwwwwwwe +17 18 wwwwwwwwwwwwwwwwwwe +17 19 wwwwwwwwwwwwe +17 20 wwwwwwwpwwwwwe +17 21 wwwwwwpwwwwwe +17 22 wwwwwwwwwe +17 23 hwwwwwwwwpwwwwwwwwwwwwwwwwwe +17 24 wwwwwwwwwwwwe +17 25 wwwwwpwwwwwwwe +17 26 wwwwwwwwwwe +17 27 wwwwwpwwwwe +17 28 wwwwwwwwwwwwe +17 29 wwwwwwwwwwwwwe +17 30 wwwwwwwpwwwwwe +17 31 wwwwwpwwwpwwwwwe +17 32 wwwpwwwwwe +17 33 wwwwwwwwpwwwwwwwwwwwpwwwe +17 34 wwwwwwwwwwwpwwpwwwwe +17 35 wwwwwwwpwwwwe +17 36 wwwwwwwpwwwwwwwwwe +17 37 wwwwwpwwwwwwwwe +17 38 wwwwwwwe +17 39 wwwwwwwpwwwwwwwwwwwe +17 40 wwwwwwwpwwwwe +17 41 wwwwwwwwwwe +17 42 wwwwwwwwwwwwwe +17 43 wwwwwwe +17 44 wwwwwwwpwwwwwwwwwwpwwwwe +17 45 wwwwwwwwwwwwe +17 46 wwwwwwwwwpwwwwwwwwwwe +17 47 wwwwwwwwwwwwwwwwwwwe +17 48 wwwwwwwwwe +17 49 wwwwwwwwwe +17 50 hwwwwwe +17 51 wwwwwwpwwwpwwwwwpwwwwwwpwwwwwe +17 52 wwwwwwwwwe +17 53 wwwwwwpwwwwpwwwwwwe +17 54 wwwpwwwwwwwpwwwwe +17 55 wwwwwwpwwwwwwpwwwe +17 56 wwwwwwwwwwwwwe +17 57 wwwwwwwwwwwwwpwwwwwe +17 58 wwwwwwwwwwwwwpwwwwwe +17 59 wwwwwwwwwwpwwwwwwpwwwwwe +17 60 wwwwwwwpwwwwwwwwwwwwpwwwwwwe +17 61 wwwwwwwwwwwwwe +17 62 wwwwwwwwwwwwwwwe +17 63 wwwwwwwwwwe +17 64 wwwwwwwwwwwwwwpwwwwwe +17 65 wwwwwwpwwwe +17 66 wwwwwwwwwwpwwwwe +17 67 wwwwwwwwwwpwwwwwpwwwe +17 68 wwwwwwwwwwwwwwwe +17 69 wwwwwwwwwwwwwwwpwwwwwwwe +17 70 hwwwwwwwwwwwwwwwwwe +17 71 wwwwwpwwwwwwwwwwe +17 72 wwwwwwwwwwwe +17 73 wwwwwwwwwwpwwwe +17 74 wwwwwwwwwe +17 75 wwwwwwwwwwwwe +17 76 wwwwwwwpwwwwwwe +17 77 wwwwwwwpwwwwe +17 78 wwwwwwwwwpwwwwwe +17 79 wwwwwwwwwwwwe +17 80 wwwwwwwwwwwwwwe +17 81 wwwwwpwwwwe +17 82 wwwwwwwwpwwwwwe +17 83 wwwwwwwpwwwwwe +17 84 wwwwwwwwwwwe +17 85 wwwpwwwwwwwwwwwe +17 86 wwwwwwwwwwwwwe +17 87 wwwwpwwwwwe +17 88 wwwwwwwwwwwwwwwwwwwe +17 89 wwwwwwwwwwwwwwe +17 90 wwwwwwwwwwe +17 91 wwwwwwwwwwwe +17 92 wwwwwwwwwwwwe +17 93 wwwwwwwwwwwwwwwwwwpwwwwwwwwe +17 94 wwwwwwwwwwwwwwwe +17 95 wwwwwwwwwwwwwwe +17 96 wwwwwwpwwwwwe +17 97 wwwwwpwwwwwwwwpwwwwwwwwpwwpwwwwe +17 98 wwwwwwwwwwwwwwe +17 99 hwwwwwwwwwwwwwwwwwwwwwwwe +17 100 wwwwwwwwwwwpwwwe +17 101 wwwwwwpwwwwwwwwwwwwe +17 102 wwwwwwwwwwwwwwwe +17 103 wwwwwwwwwe +17 104 wwwwwwwwwwwwwwe +17 105 wwwwpwwwwwe +17 106 wwwwwwwwwe +17 107 wwwwwwpwwwwwwwwwwwwe +17 108 wwwwwwwwe +17 109 wwwwwse +17 110 wwwwwwpwwwwwwpwwwwwwwwwwe +17 111 wwwwwwwwwwwwwwwwwwwpwwe +18 1 wwwwwwwwwwwpe +18 2 wwwwwwwwwwwwwwwe +18 3 wwwe +18 4 wwwwwwe +18 5 wwwwwwwpwwwwwpwwwwe +18 6 wwwwwwwwwwwe +18 7 wwwwwwwwwwwe +18 8 wwwwwwe +18 9 wwwwwwwwwwe +18 10 wwwwwwwwwwwwwwwwe +18 11 wwwwwwwe +18 12 wwwwwwwwwe +18 13 wwwwwpwwwwwwe +18 14 wwwwwwwwwwwwwwwpwwwwe +18 15 wwwwwwpwwwwwpwwwwwwwe +18 16 wwwwwwwwwwwwwwwwwwwe +18 17 hwwwwwwwwwwwwwwwwwwpwwwwpwwwwwpwwwwwwwe +18 18 wwwwpwwwwwpwwwwpwwwwwwwwwe +18 19 wwwwpwwwwwpwwwwwwpwwwwwwwwwwwwwwwwwwwwwwwe +18 20 wwwwwwwwwwwwwe +18 21 wwwwwwwwwwwwwwwwwpwwwwpwwwpwwwwwwwwe +18 22 wwwwwwwwwwpwwwwpwwwwwwwwpwwwwwwwwwwwe +18 23 wwwwwwwe +18 24 wwwwpwwwwwwwwwwwwwe +18 25 wwwwwwwwe +18 26 wwwwwpwwwwpwwwpwwwwwwwwwwwe +18 27 wwwwwwwpwwwwwwwwe +18 28 wwwwwwwwwwpwwwwwwwwpwwwwwwwwwwwwe +18 29 wwwwpwwwwwwpwwwwwwwpwwwwwwwpwwwwe +18 30 wwwwwwwwwwwwe +18 31 wwwwwwwwwwwwwwwwwwwwwwwwpwwwwe +18 32 hwwwwwwwwwwwwwwe +18 33 wwwwwwwwpwwwe +18 34 wwwwwwwwwwwwwe +18 35 wwwwwwwwwwwwe +18 36 wwwwwwwwwwwwe +18 37 wwwwwwwwwwwwwwwwe +18 38 wwwwwwwwe +18 39 wwwwwwwwwwwwpwwwwwwwe +18 40 wwwwwwwwwwwwwwwe +18 41 wwwwwwwwe +18 42 wwwwwwwwwwwwwwwwwwwe +18 43 wwwwwwwwwwwe +18 44 wwwwpwwwwwe +18 45 wwwwwwwwwwwwwwwwwpwwwwwwe +18 46 wwwwwpwwwwwwwwe +18 47 wwwwwwwwwwwe +18 48 wwwwwwwwwwpwwwwwwe +18 49 wwwwwwwwwwwwwwwwwwwpwwwwpwwwwe +18 50 wwwwwwwwwwwwwwwpwwwwwwwwpwwwe +18 51 hwwwwwwwwwwwwwe +18 52 wwwwwwwwwwwwwe +18 53 wwwwwwwwwwe +18 54 wwwwwwwwwpwwwwwe +18 55 wwwwwwwwwwwwwwwwwwwe +18 56 wwwwwwpwwwwwwwpwwwwwe +18 57 wwwwwwwwwwwwpwwwwwwwwwwpwwwwwwwwe +18 58 wwwwpwwwwwwwpwwwwwwwwe +18 59 wwwwwwwwe +18 60 wwwwwwwwwwwwwe +18 61 wwwwwwwwwwwe +18 62 wwwwwwwwwwwwe +18 63 wwwwwwwwwwwwwwwpwwwwwe +18 64 wwwwwpwwwwe +18 65 wwwwwwwwwwwwe +18 66 wwwwwwwwwwwe +18 67 wwwwwwe +18 68 wwwwwwwwe +18 69 wwwwwwwwwwe +18 70 wwwwwwwwwwwwe +18 71 wwwwwwwpwwwwwwwwe +18 72 wwwwwwwwe +18 73 wwwwwwwwwwe +18 74 wwwwwwwwwwwwwwwwe +18 75 hwwwwwwwwwe +18 76 wwwwwwwwpwwwwwe +18 77 wwwwwwwwwwwwwwwwwwpwwwwwwe +18 78 wwwwwpwwwwwwwe +18 79 wwwwwwwwwwwwwwwwwe +18 80 wwwwwwwwwwe +18 81 wwwwwwwwwe +18 82 wwwwwwwwwwwwwwwwwwwwwwwwpwwwwpwwwwwwwe +18 83 wwwwpwwwwwe +18 84 wwwwwwwwwwe +18 85 wwe +18 86 wwwwwwwwwwwwwpwwwwwwwwwwwe +18 87 wwwwwwwwwwwwwe +18 88 wwwwwwwwpwwwwwe +18 89 wwwe +18 90 wwwwwwwwwwwwwwwe +18 91 wwwwwwe +18 92 wwwe +18 93 wwwwwwwwwwwwwe +18 94 wwwwwwwwwwwwwwwwwwwe +18 95 wwwwwwwwwwwwe +18 96 wwwpwwwwwwwpwwwwwwwwwe +18 97 wwwwwwwwe +18 98 wwwwwpwwwwwwpwwwwe +18 99 hwwwwwwpwwwwwe +18 100 wwwwwe +18 101 wwwwwwwwwwwe +18 102 wwwwwwwwwpwwwwwe +18 103 wwwwwe +18 104 wwwwwwwwwwwe +18 105 wwwwwwwwwwwwwwe +18 106 wwwwwwwwwe +18 107 wwwwwwwwwwe +18 108 wwwwwwe +18 109 wwwwwwwwwwwwwwwwwwe +18 110 wwwwwwwwwwwpwwwwwwwwwwwwwe +19 1 we +19 2 wwwwwe +19 3 wwwwwe +19 4 wwwwwwwwwwwwwwe +19 5 wwwwwwwwwwwwwe +19 6 wwwwwpwwwe +19 7 wwwwwwwwwwwwe +19 8 wwwwwwwwwwwwwwe +19 9 wwwwwwwwwwwwwwe +19 10 wwwwwpwwwwwwwwe +19 11 wwwwwwwwwwwe +19 12 wwwwpwwwe +19 13 wwwwpwwe +19 14 wwwwwwe +19 15 wwwwwwwwwe +19 16 wwwwwwwwwwe +19 17 wwwwwwwwwwwe +19 18 wwwwwwwwe +19 19 wwwwwwwwwe +19 20 wwwwwwwwwwwe +19 21 wwwwwwwpwwwwwpwwwe +19 22 hwwwwwe +19 23 wwwwwwwwwwwwwe +19 24 wwwwwwwwwwe +19 25 wwwwwwwwe +19 26 wwwwpwwwwwwwwwwwwwwe +19 27 wwwwpwwwwwwe +19 28 wwwwwwwwwwwe +19 29 wwpwwwwwwwwe +19 30 wwwwwwwwe +19 31 wwwwwwwwwwwe +19 32 wwwwwwe +19 33 wwwwwwwwwe +19 34 wwwwpwwwwwe +19 35 wwwwwwwpwpwwwwwwwwe +19 36 wwwwwpwwwe +19 37 wwwwpwwwwwwwe +19 38 wwwwwpwwwwwwe +19 39 wwwwwwwwwwwwe +19 40 wwwwwwwwe +19 41 wwwwpwwwwe +19 42 wwwwwwwwwwwwwwwe +19 43 wwwwwwwwwwwwwe +19 44 wwwwpwwwwwe +19 45 wwwwwwwwwwwe +19 46 wwwwwwpwwwwpwwe +19 47 wwwpwwwpwwwwe +19 48 wwwwwwwwwwwwwwe +19 49 wwwwwwwwwwwpwwwe +19 50 wwwwwwwwwe +19 51 wwwwpwwwwwwe +19 52 wwwwwwwe +19 53 wwwwwwwe +19 54 wwwwpwwwwwwwe +19 55 wwwwwwwwwe +19 56 wwwwpwwwwe +19 57 wwwe +19 58 wwwwwwwwwwwwwwwwwwwwwpwwwwwwwwse +19 59 hwwwwwwwwpwwwe +19 60 wwwwwwwwwwwwe +19 61 wwwwwwwpwwwwe +19 62 wwwwwwpwwwwwe +19 63 wwwwwwwwwe +19 64 wwwwwpwwwwwwwwwpwwwwe +19 65 wwwwwwwwpwwwwe +19 66 wwwwwwwwe +19 67 wwwwwwwwwwe +19 68 wwwwwwwwe +19 69 wwwwwwwwwwe +19 70 wwwwwwwwe +19 71 wwwwpwwwwwe +19 72 wwwwwwwwe +19 73 wwwwwwwwwwwwwwwwe +19 74 wwwwwwwwwe +19 75 wwwwwwwwwpwwwwwwwwwwwwwwwwe +19 76 wwwwwpwwwwwwwwe +19 77 wwwwwwwwe +19 78 wwwwwwwe +19 79 wpwwwwwwwwe +19 80 wwwwwe +19 81 wwwwwwwwe +19 82 wpwwwwwe +19 83 wwwwwwwwwe +19 84 wwwpwwwwe +19 85 wwwwwwe +19 86 wwwwwe +19 87 wwwwwwwwwe +19 88 wwwwe +19 89 wwwwe +19 90 wwwwwwwwwe +19 91 wwwwe +19 92 wwwwwwe +19 93 wwwwwwwwwwe +19 94 wwwwe +19 95 wwwwwe +19 96 wwwwwwwwwe +19 97 wwwwwwwwwwe +19 98 wwwwwwwwwwwwwwe +20 1 we +20 2 wwwwwe +20 3 wwwwe +20 4 wwwwwwe +20 5 wwwwe +20 6 wwwwwwwwwwwwe +20 7 wwwwwwwe +20 8 wwwwwpwwwe +20 9 wwwwe +20 10 wwwwwwwwwwwwwwwwwwe +20 11 wwwwe +20 12 wwwwwpwwwwe +20 13 wwwwwe +20 14 wwwwwwwwwwwe +20 15 wwwwwwwwwwe +20 16 wwwwwwwwwwe +20 17 wwwwe +20 18 wwwwwwwwwwwwwe +20 19 wwwe +20 20 wwwwwe +20 21 wwwwpwwwe +20 22 wwwwwwwwwwwe +20 23 wwwwe +20 24 wwwwwe +20 25 wwwwwe +20 26 wwwe +20 27 wwwwe +20 28 wwe +20 29 wwwwwe +20 30 wwe +20 31 wwwe +20 32 wwwe +20 33 wwwe +20 34 wwe +20 35 wwwwe +20 36 wwwwwe +20 37 wwwwwe +20 38 wwwwwwe +20 39 wwwwwwwwwwwwwwwpwwwwwwwe +20 40 wwwwwwwwwpwwwwwwwwpwwwwwwwpwwwwwwwwwwe +20 41 wwe +20 42 wwwwwwwwe +20 43 wwwwwe +20 44 wwwwwwwwe +20 45 wwwwwwwwwwe +20 46 wwwpwwwwe +20 47 wwwwwwwwwwwpwwwwwpwwwwwe +20 48 wwwwwwwwwwe +20 49 wwwwe +20 50 wwwwwwwwwe +20 51 wwwwwe +20 52 wwwwwwpwwwwwe +20 53 wwwwwwwwwwwwwwwwwwwe +20 54 wwwpwwwwwwe +20 55 hwwwwwwwwe +20 56 wwwwwwe +20 57 wwwwwwwe +20 58 wwwwwwwwwwwwwwe +20 59 wwwwwwwwe +20 60 wwwwwwe +20 61 wwwwwwwwwwwpwwwwe +20 62 wwwwwe +20 63 wwwwwwwwwwwwwe +20 64 wwwwwpwwwwwe +20 65 wwwwwwwwwwwe +20 66 wwwpwwwwwwwwwe +20 67 wwwwwe +20 68 wwwwwwe +20 69 wwwwwwwpwwwwpwwwwwe +20 70 wwwwwwwwe +20 71 wwwwwwwpwwwwwpwwwwwwwwwwwwwwe +20 72 wwwwwwwwwwpwwwwpwwwwwe +20 73 wwwwwwwwwwwpwwwe +20 74 wwwwwwwwwwwwwe +20 75 wwwwwwwwwwe +20 76 wwwwwwwwpwwwwe +20 77 wwwwwwwwwwwwwwwwwwe +20 78 wwwwwwwwe +20 79 wwwwwe +20 80 wwwwwwwwwwwwwwe +20 81 wwwwwwwwwwwpwwwwwwe +20 82 wwwwwwwwwe +20 83 hwwwwwe +20 84 wwwwwwwwwe +20 85 wwwwwwwwwe +20 86 wwwwwwpwwwwwwwpwwwwwwwwwwwwwe +20 87 wwwwwwwwwwwwwwwe +20 88 wwwwwwwwwwwwe +20 89 wwwwwwwwwwwwe +20 90 wwwwwwwwwwpwwwwwwe +20 91 wwwwwwwwwe +20 92 wwwwwwwe +20 93 wwpwwe +20 94 wwwwwwwpwwwwwwwwwwwe +20 95 wwwwe +20 96 wwwwwwwwwwwwwwwwe +20 97 wwwwwwwwwwpwwwwwpwwwwwwwpwwwwwwe +20 98 wwwwwwwwpwwwwe +20 99 wwwwwwwwpwwwwwe +20 100 wwwwwwwwe +20 101 wwpwwwwwe +20 102 wwwwpwwwwe +20 103 wwwwwwe +20 104 wwwwwwwwwwwwe +20 105 wwwwwwwe +20 106 wwwe +20 107 wwwwwwe +20 108 wwwwwwpwwwwwwwe +20 109 wwwwwwwwwwwwe +20 110 wwwwwwwwwwe +20 111 hwwwwpwwwwwe +20 112 wwwwwwwwwwwe +20 113 wwwwwwwwwwwwwwe +20 114 wwwwpwwwwwwwwwpwwwwe +20 115 wwwwwwwwwwwe +20 116 wwwwwwwwwe +20 117 wwwwwwwwwwwwe +20 118 wwwwwwwe +20 119 wwwwwwe +20 120 wwwwwwwwwwwwwe +20 121 wwwwwwwwwwwpwwwwe +20 122 wwwwwwe +20 123 wwwwpwwwpwwwwwwwwwwwe +20 124 wwwwwwwwwwwwe +20 125 wwwwwwwwe +20 126 wwwwwpwwwe +20 127 wwwwwwwwpwwwwe +20 128 wwwwwwwwwwwpwwwwwwe +20 129 wwwwwwwwwe +20 130 wwwwwwwwwwwwpwwwwwwwwe +20 131 wwwwwwwwwwwwwwpwwwwe +20 132 wwwwwpwwwpwwpwwe +20 133 wwwwwwpwwwwwwwe +20 134 wwwwwwwwwwwwwwwwwwwe +20 135 wwwwpwwwwwwwe +21 1 wwwwwwwe +21 2 wwwwwwwwwwwe +21 3 wwpwwwwwwwwwpwwwwe +21 4 wwwwwwwpwwwe +21 5 wwwwwwwwwwwwwwe +21 6 wwwwwwpwwe +21 7 wwwwwwwpwwwwwwwe +21 8 wwwwwwwwwe +21 9 wwwwwwwwe +21 10 wwwwwwpwwe +21 11 wwwwwwwwwwe +21 12 wwwwwwwe +21 13 wwwwwwwwwwe +21 14 wwwwwe +21 15 wwwwwwwwe +21 16 wwwwwwwe +21 17 wwwwwwwwwwwe +21 18 wwwwwwwwwpwwwwe +21 19 wwwwwpwwwwwwwwe +21 20 wwwwwe +21 21 wwwwwwwe +21 22 wwwwwwwpwwwwwwe +21 23 wwwwwwe +21 24 wwwwwpwwwpwwwwwwwpwwwwwpwwe +21 25 wwwwwwwwwwwwwwwe +21 26 wwwwpwpwwwe +21 27 wwwwwwe +21 28 wwwwwwwwwwwwwwwe +21 29 hwwwwwwwwwwpwwwe +21 30 wwwwwwwwwwpwwwwwwpwwe +21 31 wwwwwwwwwwwwwe +21 32 wwwwpwwwwe +21 33 wwwwwwwpwwwwe +21 34 wwwwwwpwwwwe +21 35 wwwwpwwwwpwwe +21 36 wwwwwwwwwwwwwwwwwe +21 37 wwwwpwwwwe +21 38 wwwwwwwe +21 39 wwwwwwwwwwwwwwwwe +21 40 wwwwwwwwwwe +21 41 wwwwwwwwwwwwwe +21 42 wwwwwwwpwwwwwwe +21 43 wwwwwwpwwwwwwwwe +21 44 wwwwwwwwpwwwwwwwwpwwe +21 45 wwwwpwwwwwwwe +21 46 wwwwwwwwwwwe +21 47 wwwwwwwwwpwwwwwwwwpwwwe +21 48 wwwwwwwwe +21 49 wwwwwwwwe +21 50 wwwwpwwwe +21 51 hwwwwwwwwwe +21 52 wwwwwwwwwwwe +21 53 wwwwwe +21 54 wwwwwwwwe +21 55 wwwwwwwe +21 56 wwwwwwwwwwwwwe +21 57 wwwwwwwe +21 58 wwwwwwwwe +21 59 wwwwwwwwe +21 60 wwwwwwwe +21 61 wwwwwwwwe +21 62 wwwwwwe +21 63 wwwwwwwwwe +21 64 wwwwwwwe +21 65 wwwwwwwwwe +21 66 wwwwwwwwwwwe +21 67 wwwwwwwpwwe +21 68 wwwwwwwe +21 69 wwwwwwwe +21 70 wwwwwe +21 71 wwwwwwwwe +21 72 wwwwwpwwwe +21 73 wwwwwwwwwwwwpwwwe +21 74 wwwwwwwwwwwpwwwwwe +21 75 wwwpwwwe +21 76 wwwwwwwwwwwwe +21 77 wwwwwwpwwwwwwe +21 78 wwwwwwwwwwwwwwe +21 79 wwpwwwwpwwwwwwpwwe +21 80 wwwwwwwpwwwe +21 81 wwwwwwwwwwpwwwwe +21 82 wwwwwwwwwpwwwe +21 83 hwwwwwwwwwwe +21 84 wwwwwwwpwwwwwwwwwe +21 85 wwwwpwwwe +21 86 wwwpwwwe +21 87 wwwwwwwwwwwwwwwwwwwwwwwe +21 88 wwwwwpwwwe +21 89 wwwwwwwwwwwe +21 90 wwwwwwwwpwwwwwwwwpwwwe +21 91 wwwwwwwwwwwe +21 92 wwwwwwwwe +21 93 wwwpwwwe +21 94 wwwwwwwwwwwwe +21 95 wwwwwwwe +21 96 wwwwwwwwwwe +21 97 wwwwwwwwwwwwwwwwwwwe +21 98 wwwwwwwwwwwe +21 99 wwwwwwpwwwe +21 100 wwwwwwwe +21 101 wwwwwwwwwe +21 102 wwwpwwwwwwe +21 103 wwwwwwwwwwwe +21 104 wwwwwwpwwwwwpwwpwwwe +21 105 wwwwwwwwwwwwe +21 106 wwwwwwe +21 107 wwwwwe +21 108 wwwwwwwwpwwwe +21 109 wwwwwwpwwwwwwwe +21 110 wwwwwwwwe +21 111 wwwwwwwwe +21 112 wwwwpwwwwwwe +22 1 wwwwpwwwwwe +22 2 wwwwwwwwwwwwwwwwwwwwwwe +22 3 wwwwwwwwwwwwe +22 4 wwwwwwwwwwwe +22 5 wwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwe +22 6 wwwwwwwwwwwwwe +22 7 wwwwwwwwwwwwe +22 8 wwwwwwwwwwwwwe +22 9 wwwwwwpwwwwpwwwwwe +22 10 wwwwwwwwwe +22 11 wwwwwwwpwwwwwpwwwwwwwwwpwwwwe +22 12 wwwwwwwwwwpwwwwe +22 13 wwwwwwpwwwwe +22 14 wwwwwwwwwwwwpwwwwwe +22 15 wwwwwwwwwwwwwwwwwwwwwwe +22 16 wwwwwwwwwe +22 17 wwwwwwwwwwwwwwwwpwwwwwwe +22 18 wwwwwwwwwwwwwwwwwwwwwpwwwwpwwwwwwwpwwwwwse +22 19 hwwwwwpwwwwwwwwwwwwe +22 20 wwwwwwe +22 21 wwwwe +22 22 wwwwwwwwwwwwe +22 23 wwwwwwwwwwwwwwwwwwwpwwwe +22 24 wwwwwwwwwe +22 25 wwwwwwwwwwwwwwwwpwwwwwwwwwe +22 26 wwwwwwwwwwwwwwwwe +22 27 wwwwwwwwwwwwwwe +22 28 wwwwwwwwwwwwwwwpwwwwwe +22 29 wwwwwwwwe +22 30 wwwwwwwwwwpwwwwwwwpwwwwwwwe +22 31 wwwwwpwwwwwwwwwwwwwwwwe +22 32 wwwwwwwwwe +22 33 wwwwwwwwwwwe +22 34 wwwwwwwwwwwwwpwwwwwpwwe +22 35 wwwwwwwwwwwwwwwe +22 36 wwwwwwwwwpwwwwwpwwwwwwwwpwwwwwe +22 37 wwwwwwwwwwpwwwwwwwwpwwe +22 38 hwwwwwwpwwwwwwwe +22 39 wwwwwpwwwwwe +22 40 wwwwwwwwwwwpwwwwwwwwwwwwwwwwpwwwwpwwwwe +22 41 wwwwwwwwwwwwwwpwwwe +22 42 wwwwwwwwwe +22 43 wwwwe +22 44 wwpwwwwwwpwwwe +22 45 wwwwwwwwwwwwwwe +22 46 wwwwwwwwwwwwwpwwwwwwwwwwe +22 47 wwwwwwpwwwwwwwwe +22 48 wwwwwwwwwwwe +22 49 wwwwwwwwe +22 50 wwwwwwwwe +22 51 wwwwwwwwe +22 52 wwwwwwwwwwwwwwwwwwwwwwwwpwwwe +22 53 wwwwwwwwwwwpwwwwwe +22 54 wwwwwwwwwwwwwpwwwwwwwwe +22 55 wwwwwwwwwwwwwwwwe +22 56 wwwwwpwwwwwwwe +22 57 wwwwwwwwe +22 58 wwwwwwwwwwwwwpwwwwwe +22 59 wwwpwwwwe +22 60 hwwwwwwwwwwwwpwwwwe +22 61 wwwwwwwwwwwwwwwe +22 62 wwwwwwwwwwwwwwwwwe +22 63 wwwwwwwwwwwpwwwwe +22 64 wwwwwwwpwwwwwe +22 65 wwwwwwwwwwwwwwwwwwwwwwpwwwwwe +22 66 wwwwwwwpwwwe +22 67 wwwwwwpwwwwpwwwpwwwwe +22 68 wwwwwwwe +22 69 wwwwwwwwwe +22 70 wwwwwwwwwpwwwwpwwwwwe +22 71 wwwwwwwwwwwwwwpwwwwe +22 72 wwwwwwwwwwwpwwwwwwpwwwwwpwwwwwpwwe +22 73 wwwwwwpwwwwwwwwwwwwpwwwwwwwpwwwe +22 74 wwwwwpwwwwe +22 75 wwwwwwwpwwwwe +22 76 wwwwwwpwwwwe +22 77 wwwwwwwwwwwse +22 78 wwwwwpwwwwwwwwwpwwwpwwwwwwwwwwwwwwwpwwwwwwwwpwwwwe +23 1 wwwe +23 2 wwwwwe +23 3 wwwwwe +23 4 wwwwe +23 5 wwwwe +23 6 wwwwwwwwwwe +23 7 wwwwwwwe +23 8 wwwwwe +23 9 wwwwwe +23 10 wwwe +23 11 wwwwwwe +23 12 wwwwwwwe +23 13 wwwwwwe +23 14 wwwwwwwwwwwwwwwwwpwwwwe +23 15 wwwwwe +23 16 wwwwwe +23 17 wwwwwwwwwwe +23 18 wwwwwwwwpwwwwwe +23 19 wwwwwwwwwwwwwe +23 20 wwwwwwwwwe +23 21 wwwwwpwwwwwwwwwwe +23 22 wwwwe +23 23 wwwwwwwwwwwwwwpwwe +23 24 wwwwwwwwwwwwwwwwwwwwwwwwwwe +23 25 wwwwwwwwwwe +23 26 wwwwwe +23 27 wwwwwwwwwwwwpwwwwwwwwwwwwwpwwwwwpwwe +23 28 wwwwwwwwwwwwwwwe +23 29 wwwwwwwwe +23 30 wwwwwwwe +23 31 wwwwwwe +23 32 wwwwwwwwwwwwpwwe +23 33 wwwwwwwwwwwwwwwwwwwwwwwwwe +23 34 wwwwwwwe +23 35 wwwwwwwwwe +23 36 hwwwwe +23 37 wwwwwwwwwwe +23 38 wwwwwwwwwwwwe +23 39 wwwwwe +23 40 wwwwwe +23 41 wwwwwpwwwe +23 42 wwwwwwe +23 43 wwwwwwwe +23 44 wwwwpwwwwwwpwwwwwpwwwwe +23 45 wwwwwwwwe +23 46 wwwwwwwe +23 47 wwwwwwwe +23 48 wwwwe +23 49 wwwwwwe +23 50 wwwwwwwwwwwe +23 51 wwwwwwwpwwwwe +23 52 wwwwwwwwe +23 53 wwwwpwwwwwe +23 54 wwwwwe +23 55 wwwwwwwe +23 56 wwwwpwwwe +23 57 wwwwwwwe +23 58 wwwwwe +23 59 wwwwwe +23 60 wwwwwwwwwwe +23 61 wwwwwwwe +23 62 wwwwwpwwwwpwwwe +23 63 wwwwwwwwwwwwwwe +23 64 wwwwwwwwe +23 65 wwwpwwwwe +23 66 wwwwwwwwwe +23 67 wwwwe +23 68 wwwwwwwwwwe +23 69 wwwwwwwe +23 70 wwwwpwwwwwwe +23 71 wwwwwwwwwpwwwwwwwe +23 72 wwwwwwpwwwe +23 73 wwwwwe +23 74 wwwwwwwwe +23 75 hwwwwwwwwwwwe +23 76 wwwwwwwwe +23 77 wwwwwwwwwwwwe +23 78 wwwwwwwpwwwe +23 79 wwwwwwwe +23 80 wwwwwwwwpwwe +23 81 wwwwwwe +23 82 wwwwwwwwe +23 83 wwwwwwwwwwwwe +23 84 wwwwwwwwe +23 85 wwpwwwe +23 86 wwwwwwwwe +23 87 wwpwwwe +23 88 wwwwwwwwwwwwwwe +23 89 wwpwwwe +23 90 wwwwwe +23 91 wwwwwwwwwwpwwwwwwwwwwpwwwwe +23 92 wwwwwwe +23 93 wwwwwwe +23 94 wwwwwwe +23 95 wwwwwwwe +23 96 wwwwwpwwwwe +23 97 wwwwwwwe +23 98 wwwwwe +23 99 wwwwwwwwe +23 100 wwwwwpwpwwwwpwwwwwwe +23 101 wwwwwwwwwwe +23 102 wwwwwwe +23 103 wwwwwwwwwwe +23 104 wwwwwwe +23 105 wwwwwwwwe +23 106 wwwwwwwwe +23 107 wwwwwwwe +23 108 wwwwwe +23 109 wwwwwwwwwwwwwwe +23 110 wwwwwwwwe +23 111 wwwwwwwwe +23 112 wwwwwwwe +23 113 wwwwwwwwe +23 114 wwwwwpwwwwe +23 115 wwwwwwwwe +23 116 wwwwpwwwwwwwe +23 117 wwwwwwwwwwwwwwpwwwwe +23 118 wwwwwwwe +24 1 wwwwwwwwwe +24 2 wwwwwwwwpwwwwwwwwwwwwwpwwwwwe +24 3 wwwwwwwwwwwwwwpwwwwe +24 4 wwwwwwwwwwwwwwwwpwwwe +24 5 wwwwwwwwwwwe +24 6 wwwwwwwwwwwwwwpwwwe +24 7 wwwwwwwwwe +24 8 wwwwwwwwpwwwe +24 9 wwwwwwwwwe +24 10 wwwwwwwwwe +24 11 wwwwwwpwwwwpwwwwpwwwwwwwpwwwwwwwe +24 12 wwwwwwwwwwwwe +24 13 wwwwwpwwwwwwwwwe +24 14 wwwwwwwwwwwwwwwe +24 15 wwwwwwwwwwwwwwwwe +24 16 wwwwwwwwwwwwwwe +24 17 wwwwwwwwwe +24 18 wwwwpwwwe +24 19 wwwwwwwwwwwwwwwpwwwwwe +24 20 wwwwwwwwwe +24 21 hwwwwwwwpwwwwwwwwpwwwwwwwwwwwwwwwwpwwwe +24 22 wwwwwwwwwwwwwwwpwwpwwwwwwpwwwe +24 23 wwwwwwwwwwwwwe +24 24 wwwwwwwwwe +24 25 wwwwwwwwwwwe +24 26 wwwwpwwwwpwwwwpwwwwe +24 27 wwwwwwwwwwwwwpwwwwwe +24 28 wwwwwwwwwwpwwwwwpwwwpwwwwe +24 29 wwwwwwwwwwwpwwwwwwe +24 30 wwwwwwwpwwwpwwwwwe +24 31 wwwwwwwwwwwwwwpwwwwpwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwpwwwwwwwwe +24 32 wwwwwwwpwwwwwwwpwwwe +24 33 wwwwwwwwwwpwwwwwwwwwwwpwwwwwwpwwwwwwwwwwwwpwwwwwwwwwe +24 34 wwwwwwwwwwwwwe +24 35 hwwwwpwwwwwpwwwpwwwwwwwwwwwwwwwwwwwwpwwwpwwwwwpwwwwpwwwwe +24 36 wwwwwwwwwwwwwwe +24 37 wwwwwwwwwwwwwpwwwwwwe +24 38 wwwwwwwwpwwwwwwe +24 39 wwwwwwwwwwwwwwwwwwwpwwwe +24 40 wwwwwwwwwwwwwpwwwwwwwwwwpwwwwwwwwwwe +24 41 wwwwwwwwwwwwpwwwwwpwwwwe +24 42 wwwwpwwwe +24 43 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwe +24 44 wwwwpwwwwwwe +24 45 wwwwwwpwwwwwwwwwwwwwwwpwwwwpwwwwwwe +24 46 wwwwpwwwwwwwe +24 47 wwwwwwwwwwwwpwwwe +24 48 wwwwwwwwwwwe +24 49 wwwwwwwe +24 50 wwwwwwwwwwwwpwwwwe +24 51 wwwwwwwwwwwwwwwpwwwe +24 52 wwwwwwwwwwe +24 53 hwwwwwwwpwwwpwwpwwwwwe +24 54 wwwwwpwwwwwwwwwpwwwpwwwwwwe +24 55 wwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwpwwwwwwwe +24 56 wwwwwwwwe +24 57 wwwwwwwpwwpwwe +24 58 wwwwwwwwwwwwwwpwwwwwwwwwwwwwpwwwpwwwwwwpwwwwwpwwwwwpwwwe +24 59 wwwwwwwwwwwpwwwwwpwwwe +24 60 wwwwwwwwwwwwwwwwpwwwwpwwwe +24 61 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwpwwwwwwwwwwwwpwwwwwwwe +24 62 wwwwwwwwwwwwwwwwpwwwwwwwwpwwwwwwwwwwwpwwwwe +24 63 wwwwwwwwpwwwwwwwpwwwwwwwwwwwwe +24 64 wwwwwwwpwwwwwwwwwwwpwwwwe +25 1 wwwwwwwwwe +25 2 wwwwwwwwwwwwwwwwwwwe +25 3 wwwwwwwwwwwwwwwwwwwwwwe +25 4 wwwwwwwwwwwwpwwwwe +25 5 wwwwwwwwwe +25 6 wwwwwwwwpwwwwe +25 7 wwwwwwwwwpwwwwwwwe +25 8 wwwwwwwwwwpwwwwwwwe +25 9 wwwwwwwwwe +25 10 wwwwwwwwwwwwwwwwwe +25 11 wwwpwwwwwe +25 12 wwwwwwwwwe +25 13 wwwwwwwwwe +25 14 wwwwwwwwe +25 15 wwwwwwwwwpwwwwe +25 16 wwwwwpwwwwwe +25 17 wwwwwwwwwwwwwwwwe +25 18 wwwwwwwwwwwwwwwwwwwwwe +25 19 wwwwwwwwwpwwwwwwe +25 20 wwwwwwwwwwwwpwwwwwpwwwe +25 21 hwwwwwwwwwwwwpwwwwwwwe +25 22 wwwwwwwwwwe +25 23 wwwwwwwwwe +25 24 wwwwwwwe +25 25 wwwwwwwe +25 26 wwwwpwwwwwe +25 27 wwwwwwwwwwwe +25 28 wwwwwwe +25 29 wwwwwwwpwwwwe +25 30 wwwwwwwwwe +25 31 wwwwwwwpwwwwe +25 32 wwwwwwwwwpwwwwpwwe +25 33 wwwwwwwwe +25 34 wwwwwwwwwwwe +25 35 wwwwwwwwwe +25 36 wwwwwwwwwe +25 37 wwwwwwwwwpwwwwe +25 38 wwwwwwwwe +25 39 wwwwpwwwe +25 40 wwwwwwwwpwwwpwwwwwe +25 41 wwwwwwwwwwwe +25 42 wwwwwwwwwpwwwwwwwwe +25 43 wwwwwwwwwe +25 44 wwwwwwwpwwwwpwwwwe +25 45 wwwwwwwwwwwwwwwwe +25 46 wwwwwe +25 47 wwwwwwwwwwwe +25 48 wwwwwwwwpwwwwwe +25 49 wwwwwwwwwwe +25 50 wwwwwwwwwe +25 51 wwwwwwwe +25 52 wwwwwwwe +25 53 hwwwwwwwwwwwwwwwe +25 54 wwwwwwwwwpwwwe +25 55 wwwwwwwwwpwwwwwe +25 56 wwwwwe +25 57 wwwwwwwwwwwwwwe +25 58 wwwwwwwwpwwwwwe +25 59 wwwwwwwwwwwwwpwwwwe +25 60 wwwwwwwwwwwwwse +25 61 wwwwwwwwwwwe +25 62 wwwwwwwwwwwwwe +25 63 wwwwwwwwwwwwe +25 64 wwwwwe +25 65 wwwwwwwpwwwwe +25 66 wwwwe +25 67 wwwwwwwwwwwe +25 68 wwwwwwwwwwwwwwwwwpwwwwwe +25 69 wwwwwwwwe +25 70 wwwwwwwwwwwwpwwwwe +25 71 wwwwwwwwwe +25 72 wwwwwwwwwe +25 73 wwwwwwwwwwe +25 74 wwwwwwwwwwwwwe +25 75 wwwwwwwwwe +25 76 wwpwwwe +25 77 wwwwwwwpwwwwwe +26 1 we +26 2 wwwwe +26 3 wwwwwwe +26 4 wwwwwwwwwwwe +26 5 wwwwwwwwwwwe +26 6 wwwwwwwwe +26 7 wwwwwwwwwwwe +26 8 wwwwpwwwwe +26 9 wwwwwe +26 10 wwwwwwwwe +26 11 wwpwwe +26 12 wwwwwwe +26 13 wwwwwwwwe +26 14 wwwwwwe +26 15 wwpwwpwwwe +26 16 wwwwwwwe +26 17 wwwwwe +26 18 wwwwwwwwwwe +26 19 wwwwwwwe +26 20 wwwwwwe +26 21 wwwwwwwwwwwe +26 22 wwwwwwwwe +26 23 wwwwwe +26 24 wwwwwwpwwwe +26 25 wwwwwe +26 26 wwwwwe +26 27 wwwwwwwe +26 28 wwwwwwpwwwe +26 29 wwwwwwwwe +26 30 wwwwwe +26 31 wwwwwwwe +26 32 wwwwwwe +26 33 wwwwwwe +26 34 wwwwwwwe +26 35 wwwwwwwwe +26 36 wwwwwwwe +26 37 wwwwe +26 38 wwwwwe +26 39 wwwwwe +26 40 wwwwwwwe +26 41 wwwwwwwwwwwwe +26 42 wwwwwwe +26 43 wwwwwwwe +26 44 wwwwwwwwwe +26 45 wwwwwwwwe +26 46 wwwe +26 47 wwwwe +26 48 wwwe +26 49 wwwwwwwpwwwwwwwpwwwwwwwe +26 50 wwwpwwwwe +26 51 wwwwwwwwwwwe +26 52 hwwwwwwwwe +26 53 wwwwwe +26 54 wwwwe +26 55 wwwe +26 56 wwwe +26 57 wwwwe +26 58 wwwe +26 59 wwwwe +26 60 wwe +26 61 wwwwwwwwe +26 62 wwpwwwwe +26 63 wwwwwwwpwwwwwwe +26 64 wwwe +26 65 wwwwwe +26 66 wwwe +26 67 wwwwpwwwwe +26 68 wwwwwe +26 69 wwwwe +26 70 wwwwwwe +26 71 wwwwwwe +26 72 wwwwwe +26 73 wwwwe +26 74 wwwwwwe +26 75 wwwwwe +26 76 wwwe +26 77 wwwwwwe +26 78 wwwwe +26 79 wwwwe +26 80 wwwwe +26 81 wwwwe +26 82 wwwwwwwwe +26 83 wwwwwwe +26 84 wwwwwwe +26 85 wwwwwe +26 86 wwwwwwe +26 87 wwwwe +26 88 wwwwwwe +26 89 wwwwwwe +26 90 wwwe +26 91 wwwe +26 92 wwwwwwe +26 93 wwwwwwwe +26 94 wwwwe +26 95 wwwe +26 96 wwwwe +26 97 wwwwwwe +26 98 wwwwe +26 99 wwwwe +26 100 wwwwe +26 101 wwwe +26 102 wwwwwwwe +26 103 wwwwpwwwwe +26 104 wwwwwe +26 105 wwwwe +26 106 wwwwwwwe +26 107 wwwwe +26 108 wwwe +26 109 wwwwwpwwwwwwe +26 110 wwwe +26 111 hwwwwwe +26 112 wwwwwwe +26 113 wwwwwpwwe +26 114 wwwwe +26 115 wwwwwe +26 116 wwwwwwwwe +26 117 wwwwwe +26 118 wwwwwwwwwe +26 119 wwwwwwe +26 120 wwwwe +26 121 wwwwpwwwwe +26 122 wwwwwe +26 123 wwwe +26 124 wwwwwwwe +26 125 wwwwe +26 126 wwwe +26 127 wwwwwpwwwwwwe +26 128 wwwwwe +26 129 wwwwe +26 130 wwwwe +26 131 wwwe +26 132 wwwwwe +26 133 wwwe +26 134 wwe +26 135 wwwwwwe +26 136 wwwwwwwwwe +26 137 wwwwwe +26 138 wwwe +26 139 wwpwwwwpwwwwe +26 140 wwwwwe +26 141 wwwe +26 142 wwwwwwwe +26 143 wwwwe +26 144 wwwe +26 145 wwwwwpwwwwwwe +26 146 wwwwwe +26 147 wwwe +26 148 wwwwe +26 149 wwwwwe +26 150 wwwe +26 151 wwwwe +26 152 wwwwwwe +26 153 wwwwwe +26 154 wwwwwwwwwwwe +26 155 wwwwwwwwwe +26 156 wwwwwwwe +26 157 wwwe +26 158 wwpwwwwpwwwwe +26 159 wwwwwe +26 160 wwwwe +26 161 wwwwwwwe +26 162 wwwwe +26 163 wwwe +26 164 wwwwwpwwwwwwe +26 165 wwwwe +26 166 wwwwwwwpwwwwe +26 167 wwwwwwwwe +26 168 wwwwwe +26 169 wwwwwe +26 170 wwwe +26 171 wwwwe +26 172 wwwe +26 173 wwwpwwwe +26 174 wwwwpwwwwe +26 175 wwwwwe +26 176 wwwwe +26 177 wwwwwwe +26 178 wwwwe +26 179 wwwe +26 180 wwwwwpwwwwwwe +26 181 hwwwwwwe +26 182 wwwe +26 183 wwwwwwwwwe +26 184 wwwwwe +26 185 wwwwwe +26 186 wwwwwwwwwe +26 187 wwwwwwwwwe +26 188 wwwwwe +26 189 wwwwwpwwwwwe +26 190 wwwwpwwwwe +26 191 wwwwwe +26 192 wwwwe +26 193 wwwwe +26 194 wwwwwe +26 195 wwwe +26 196 wwwwe +26 197 wwwwwwwwwe +26 198 wwwwwe +26 199 wwwwwwe +26 200 wwwwwe +26 201 wwwwwwwe +26 202 wwwwwe +26 203 wwwwe +26 204 wwe +26 205 wwwwe +26 206 wwwwwe +26 207 wwwwwwe +26 208 wwwwwwwe +26 209 wwwwe +26 210 wwwwe +26 211 wwwwwe +26 212 wwwwe +26 213 wwwwwwwwwe +26 214 wwwe +26 215 wwwwwwe +26 216 wwwwwwwe +26 217 wwwwe +26 218 wwwwe +26 219 wwwe +26 220 wwwwe +26 221 wwwwwwe +26 222 wwwwwe +26 223 wwwwe +26 224 wwwe +26 225 wwwwwwwe +26 226 wwwwwe +26 227 wwwwwwwwwwwwwpwwwwwwe +27 1 wpwwwwwe +27 2 wwwe +27 3 wwwwwwwwwe +27 4 wwwwwwwwwwe +27 5 wwwwwwwwwwe +27 6 wwwwwwwe +27 7 wwwwwwwwwwwwwwwwe +27 8 wwwwwwwwwwwwwwe +27 9 wwwwwwe +27 10 wwpwwwwwwwwwpwwwwwwwwe +27 11 wwwwwwwwwwwe +27 12 wwwwwwwwwpwwwwwwpwwwwe +27 13 wwwwwwwwe +27 14 wwwwwwpwwwwwe +27 15 wwwwwpwwwwwwwwwwe +27 16 wwwpwwwwwwwwwwpwwwwwe +27 17 wwwwwwwwwe +27 18 wwwwwwwwwwwwwwwwwwwe +27 19 wwwwwwwwwwwwwwwwwwwwwwwwe +27 20 wwwwwwwwwwwwe +27 21 wwwwwwwwwe +27 22 wwwwwwwwwwwwwwe +27 23 wwwwwwwwwwwe +27 24 wwwwwwwwwwwwwwwwwe +27 25 wwwwwwwwwwwwwwe +27 26 wwwwwwwwse +27 27 hwwwwwwwe +27 28 wwwwwwwwwwwe +27 29 wwwwwwwwe +27 30 wwwwwwwwe +27 31 wwwwwe +27 32 wwwwwwwwwwwwe +27 33 wwwwwwwwwwwwe +27 34 wwwwwwwwwwwpwwe +27 35 wwwwwwwwe +27 36 wwwwwwwwwwwwwwwwe +27 37 wwwwwwwwwwwwwe +27 38 wwwwwwwwwwe +27 39 wwwwwwwwwwwwpwwwwe +27 40 wwwwwwwwwwwwwwpwwwwwwwwwwwwwpwwwwwpwwwwwwe +27 41 wwwwwwwwwwwwe +27 42 wwwwwpwwwpwwwwwwe +27 43 wwwwwwwpwwwwwe +27 44 wwwwpwwwwwwwpwwwwwwpwwwwwwwwwwwe +27 45 wwwwwwwwwwwwwe +27 46 wwwwwwwpwwwwwe +27 47 wwwwwpwwwwpwwwwe +27 48 wwwwwwwwwwe +27 49 wwwwwwwwwwwwwwe +27 50 wwwwwwwe +27 51 wwwwwwwwwe +27 52 wwwwwpwwwwwwe +27 53 wwwwwe +27 54 wwwwwwwwe +27 55 wwwwwwwpwwwwe +27 56 hwwwwwwwwwwwwpwwwe +27 57 wwwwwwwe +27 58 wwwpwwwe +27 59 wwwwwwwwpwwwwe +27 60 wwwwwwwwwwwwwwwwwwwwpwwwpwwwwe +27 61 wwwwwwwwwwwwwwpwwwpwwwwe +27 62 wwwwwwwwwwpwwwpwwwe +27 63 wwwwwwwwwwwwwpwwwpwwwwe +27 64 wwwwwwwwwwpwwwpwwwwwwe +27 65 wwwwwwwwwwpwwwwe +27 66 wwwwwpwwwwwpwwwwe +27 67 wwwwwwwwwe +27 68 wwwwwwwwwwwwe +27 69 wwwwwwwwwe +27 70 wwwwwwwwwe +27 71 wwwwwwwe +27 72 wwwwwwwwwe +27 73 wwwwwwwwwwe +27 74 wwwwwwwwe +27 75 wwwwwwwwwwe +27 76 wwwwwwwwwwwwe +27 77 wwwwe +27 78 wwwwwpwwwe +27 79 wwwpwwwwe +27 80 wwwwwwwwwwwe +27 81 wwwwwwpwwwwwwwwe +27 82 hwwwwwwwwwwwwwwwwe +27 83 wwwwwwwwwwwe +27 84 wwwwwwwwwwwwwe +27 85 wwwwwwwwe +27 86 wwwwwwwwwpwwwwwwe +27 87 wwwwwwwwwwwwwwwpwwwe +27 88 wwwwwwwwpwwwwwwpwwwwe +27 89 wwwwwwwwwwwe +27 90 wwwwwwwwwwwwwe +27 91 wwwwwwwwwwwwpwwwwwe +27 92 wwwpwwwwwpwwwwwwwe +27 93 wwwwwwpwwwwwe +28 1 we +28 2 wwwwe +28 3 wwwwwwwwwe +28 4 wwwwwwwwwwwwwwwpwwwwe +28 5 wwwwwwwwwwwwe +28 6 wwwwwwwwwwwwe +28 7 wwwwwwpwwwwwwwwwwpwwwwwwe +28 8 wwwwwwwpwwwwwwe +28 9 wwwwwwwpwwwwwwwwwwwe +28 10 wwwwwpwwwwwwwwwwwwe +28 11 wwwpwwwwwwwe +28 12 hwwwwwwwwwwwwwwwwe +28 13 wwwwwwwwwwwwwwwwwe +28 14 wwwwwwwpwwwe +28 15 wwwwwwwwwwwwwwwwwpwwwwwwwwwwwwpwwwwwpwwwwe +28 16 wwwwwwwwwpwwwwe +28 17 wwwwwwwwwe +28 18 wwwwwwwwwwpwwwwwwe +28 19 wwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwe +28 20 wwwwwwwwwwwwwwwwwwe +28 21 wwwwpwwwwwwe +28 22 wwwwwwwwwwwe +28 23 wwwwwwwwwwwwwwwpwwwpwwwwwwpwwwe +28 24 wwwwwwwwwwwwwwwe +28 25 wwwwwwwwwwwwwwpwwwwwwwwpwwwwe +28 26 wwwwpwwwwwwe +28 27 wwwwwwwwwwwwwpwwwwwpwwwwwpwwwwwwe +28 28 wwwwpwwwwwwpwwwwwe +28 29 hwwwwwwwwwwwwwwwwwwwwwwwwwwwe +28 30 wwwwwwwwwwwwwwwwwwwe +28 31 wwwpwwwwwwwwwpwwwwpwwwe +28 32 wwwwwwwwwwwwwwpwwwwwwwpwwwwe +28 33 wwwwwwwwwe +28 34 wwwwwwwwwwpwwwwe +28 35 wwwwwwwwwwpwwwwwe +28 36 wwwwwwwwwwwwwwwwwe +28 37 wwwwwwwwwwwwwwpwwwwe +28 38 wwwwwwwwwwwwwwwwwwwwwwwwwwwe +28 39 wwwwwwwwwwwwe +28 40 wwwwwpwwwwwe +28 41 wwwwwpwwwwe +28 42 wwwwwpwwwwwe +28 43 wwwwwwwwwwwwwwwwe +28 44 wwwwwwwwwwwwwe +28 45 wwwwwwpwwwwwwwwwwwwe +28 46 wwwwwwwwwwwwwwwwwwwwe +28 47 wwwwwwwwwwwwwwwwwwe +28 48 wwwwwwwwwwwwpwwwwwwwpwwwwwwwe +28 49 wwwwwwwwwwwwwe +28 50 wwwwwwwwpwwwwwwwwwpwwwwwwe +28 51 hwwwwwwe +28 52 wwwwwwwwe +28 53 wwwwwwwwwwwwwwwe +28 54 wwwwwwwwwwwwe +28 55 wwwwwwwwwwwwwwwe +28 56 wwwwwwwwwwpwwwe +28 57 wwwwwwwwpwwwwwwwwwwwwwwwwwe +28 58 wwwwwwpwwwwwwwwpwwwe +28 59 wwwwwwwwwwwwwpwwwwwwwe +28 60 wwwwwwwwpwwwwwpwwe +28 61 wwwwwwwwwwwwwwwwwe +28 62 wwwwwwwwe +28 63 wwwwwwwwwwwwpwwpwwwwe +28 64 wwwwwwwwwpwwwwe +28 65 wwwwwwe +28 66 wwwwwwwe +28 67 wwwwwwwwwwwe +28 68 wwwwwpwwwwpwwwwwe +28 69 wwwwwwwe +28 70 wwwwwwpwwwwwpwwwwe +28 71 wwwwwwwwwwwwwwwwwpwwe +28 72 wwwwwwwwwwwwwwwwwwwpwwe +28 73 wwwwwwwwwwwwwe +28 74 wwwwwwwwe +28 75 wwwwwwwwwwwwwwwwwe +28 76 hwwwwwwwwpwwwwwwwwwwwwwwwwpwwwwwe +28 77 wwwwwwpwwwwwpwwwwwpwwwwwpwwwwwe +28 78 wwwwwwpwwwwwwwwwwwwwwwwwpwwwwwe +28 79 wwwwwpwwwwwwwwwwwwwwwe +28 80 wwwwwwwwwwwwwwwwe +28 81 wwwwwwwwwwwwwwwwwe +28 82 wwwwwwwwwwwwwwwpwwwwwwwpwwwwe +28 83 wwwwwwwwwwwwpwwe +28 84 wwwwwwpwwwwwwwwwwwwe +28 85 wwwwwwwwpwwwwwwwwwwwe +28 86 wwwwwwwwwwwpwwwwe +28 87 wwwwwwwwwpwwwpwwwwe +28 88 wwwwwwpwwwwpwwwwwpwwwwe +29 1 we +29 2 wwwwwwwwwwe +29 3 wwwwwpwwwwwwe +29 4 wwwwwwwpwwwe +29 5 wwwwwwwwwpwwwe +29 6 wwwwwpwwwwwe +29 7 wwwwwwwwwwwwe +29 8 wwwwpwwwwwwwwwwwpwwwwwwe +29 9 wwwwwwwe +29 10 wwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwe +29 11 wwwwwwe +29 12 wwwwwwwwwwwwwwwwpwwe +29 13 wwwwwpwwwwwwe +29 14 wwwwwwwwwwwwwwwwe +29 15 wwwwwwe +29 16 wwwwwwwpwwwwwwe +29 17 wwwwwwwwpwwwwwwwwwwwwwwwwwpwwe +29 18 wwwwwwwpwwwwwwe +29 19 wwwwwwwwpwwwwwe +29 20 wwwwwwwwpwwwwwpwwwwwwe +29 21 wwwwwwpwwe +29 22 wwwwwwwwpwwwwwwwwwe +29 23 wwwwwwwwwwwwwe +29 24 wwwwwwwwwwwwwwpwwwwwwe +29 25 wwwwwwwwwwwwpwwwwwwwwwwwwwwwe +29 26 hwwwpwwwwwpwwwwe +29 27 wwwwwwwwwwwwwpwwwwwe +29 28 wwwwwwwwwwwwwwe +29 29 wwwwwwwwwpwwwwwwwwwwwwwwe +29 30 wwwwwwe +29 31 wwwwwwwwwwwpwwwwe +29 32 wwwwpwwwwwpwwwwwwwe +29 33 wwwwwwwwwwwwwwwpwwwwwwwwe +29 34 wwwwwwwwwwwwe +29 35 wwwwwwwe +29 36 wwwwwwwwwwwwwwwwe +29 37 wwwwwwwe +29 38 wwwwwwwpwwwwwwwwwe +29 39 wwwpwwwwwwwwwwe +29 40 wwwpwwwwwwwwwwwwwwwwwpwwwwwwwwe +29 41 wwwwwwwwwwwpwwwwwpwwwe +29 42 wwwwwwwwwpwwwe +29 43 wwwwpwwwwe +29 44 wwwwwpwwwwwe +29 45 wwwwwwwwpwwwwwwpwwwpwwwwe +29 46 hwwwwwwwwwwwwpwwwwwwwwwwwwwe +29 47 wwwwpwwwwwpwwwwwpwwwwwe +29 48 wwwwwwwwwwpwwwe +29 49 wwwwwwwwwpwwwwwe +29 50 wwwwwwwpwwwwwwwwwe +29 51 wwwwwwwwpwwwwwwwe +29 52 wwwwwwpwwwwwpwwwwwwwwe +29 53 wwpwwwwwwwwwwe +29 54 wwwwwwe +29 55 wwwwwwwwwwwwwe +29 56 wwwwwwwwe +29 57 wwwwpwwwe +29 58 wwwwwwwwwwwwwwpwwwe +29 59 wwwwwe +29 60 wwwwwwwwwpwwwe +29 61 wwwwwwwwwwwpwwe +29 62 wwwwwwwwwpwwwwwe +29 63 wwwwwwwwwwwwwwwpwwwpwwwwe +29 64 wwwwwwwpwwwwwpwwwe +29 65 wwwwwwwwwwwwwwwwe +29 66 wwwwpwwe +29 67 wwwwwwwwwwpwwwwwe +29 68 wwwwwwwwwwwwpwwwwwe +29 69 wwwwwpwwwwe +30 1 we +30 2 wwe +30 3 wwwwwwwwe +30 4 wwwpwwwwwwpwwwe +30 5 wwpwwwpwwwe +30 6 wwpwwwwwwwwwe +30 7 wwwwwwwwwwe +30 8 wwwwpwwwwwwwwwwwpwwwwwwwe +30 9 wwwwwwwwwwwpwwwwwwwwwwwwwpwwwwwwwwe +30 10 wwwwwwwwwwwwwe +30 11 wwwwwwwwe +30 12 wwwwwe +30 13 wwwwwwwwwe +30 14 wwwwwe +30 15 wwwwwwwwwe +30 16 wwwwwwwwwwwe +30 17 wwwwwwe +30 18 wwwwwwwwe +30 19 wwwwwwwwwwwwpwwe +30 20 wwwwwwwwwwwe +30 21 wwwwwwwwwwwwwwpwwwwwwe +30 22 wwwwwwwwpwwwwwe +30 23 wwwwwwwwpwwwwwwe +30 24 wwwwwwwwwwwwwwwpwwwwwwe +30 25 wwwwwwwpwwwwwwwwwe +30 26 wwwwwpwwwe +30 27 wwwwwwwwwpwwwwwwpwwwe +30 28 wwwwwpwwwwwwwwwwwwwwwwwpwwwwwe +30 29 wwwwwwwpwwwwwpwwwwe +30 30 wwwwpwwwwwwpwwwwpwwwwwwwwe +30 31 hwwwwwwwwwe +30 32 wwwwwwpwwwwwe +30 33 wwwwwwwwwwwwwwwwwwe +30 34 wwwpwwwe +30 35 wwwwwwwwwwe +30 36 wwwwwwpwwwwwwwwwe +30 37 wwwwwwwwwpwwwwwwe +30 38 wwwwwwwpwwwwwwpwwwe +30 39 wwwwwwwwwwwwpwwwwwwwwwwe +30 40 wwwwwwwwwpwwwwwwwwwpwwwwe +30 41 wwwwwwwwwwwwwwwe +30 42 wwwwwwwwwwwpwwwe +30 43 wwwwwwwwwwwwwwpwwe +30 44 wwwwpwwwwwe +30 45 wwwwwwwpwwwwe +30 46 wwwwwwwwwwwwwwwwwe +30 47 wwwwwwwwwwwwwpwwwwwe +30 48 wwwwwwwwwwwwwwwwwwpwwwwwwwwwwe +30 49 wwwwwwwwwwe +30 50 wwwwwwwwwwpwwwwpwwwwwe +30 51 wwwwwwwwwe +30 52 wwwwwwwwwwwe +30 53 wwwwwwpwwwwwwwwe +30 54 hwwwwwwwwwwwwwwwwwwpwwwpwwwe +30 55 wwwwwwwwwpwwwe +30 56 wwwwwwwwwwwwwpwwwwwwwe +30 57 wwwwwwwwwe +30 58 wwwwwwwwwpwwwwwwwwwwe +30 59 wwwwwwwwe +30 60 wwwwwpwwwwwe +31 1 we +31 2 wwwwe +31 3 wwwe +31 4 wwwwwwwwwe +31 5 wwwwwpwwwe +31 6 wwwwwwwwwwwwwwpwwwwe +31 7 wwwwwwwwwwwwwpwwwe +31 8 wwwwwwwwe +31 9 wwpwwwpwwwe +31 10 wwwwwpwwwwwwwwwwwwpwwwwwwwwwwe +31 11 wwwwwwwwwpwwwwwe +31 12 wwwwwwwpwwwwwpwwwwwwe +31 13 wwwwwwwwwwpwwwwe +31 14 wwwwwwwwwwwwwwwwwe +31 15 wwwwwwwwwwwwwpwwwwpwwwwwpwwwwwwwe +31 16 wwwwwwwwwwwwwwwwwwwwpwwwwe +31 17 wwwwwwwwwwwwpwwwwwe +31 18 wwwwwwwwwpwwwwwwwe +31 19 wwwwwwpwwwwwe +31 20 wwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwe +31 21 wwwwwwwwwwwwwwpwwwwwwwe +31 22 hwwwwwwwwwwwpwwwwe +31 23 wwwwwpwwwwwpwwwwwe +31 24 wwwwwwwe +31 25 wwwwwwwwpwwwpwwwwe +31 26 wwwwwpwwwwwe +31 27 wwwwwwwwwwwwwwwwwpwwwwe +31 28 wwwwwwwpwwwwe +31 29 wwwwwwwwwwwwwwwwwwwwwwwwwe +31 30 wwwwwwwwwwwwwwwwe +31 31 wwwwwwwwwwwwpwwwwwwwe +31 32 wwwwwwwwwwwwwwwpwwwwwwwe +31 33 wwwwwwwwwwwwwwwwwwpwwwwpwwwwwwwwe +31 34 wwwwwwwwwwwpwwwwwwpwwwwwwpwwwwe +32 1 we +32 2 wwwwwwwwe +32 3 wwwpwwwwwwwwwwwwwwwe +32 4 wwwwwwwwwwwwwwpwwwwwwwwpwwe +32 5 wwwwwwwwwwwwwwwwwe +32 6 wwwwwwe +32 7 wwwwwpwwwwwe +32 8 wwwwwwwwe +32 9 wwwwwwpwwwwwpwwwe +32 10 wwwwwwwwwpwwwwwe +32 11 hwwwwwwwwwwwe +32 12 wwwwwwwwwwwwwwwwe +32 13 wwwwwwwwwwwwwwwwe +32 14 wwwwwwwwpwwwwwwe +32 15 wwwwwwwwwwwwwwwse +32 16 wwwwwwwwwwwe +32 17 wwwwwwwwwwwwwe +32 18 wwwwwwpwwe +32 19 wwwwwwwwwwwwe +32 20 wwwwwpwwwwwwwwwwwwwwwwe +32 21 wwwwwwwwwe +32 22 wwwwwwwwwpwwwwe +32 23 wwwwwwwwwwpwwwwe +32 24 wwwwwwwpwwwe +32 25 wwwwwwwwwwwe +32 26 wwwwwwwwwwwwpwwwwpwwe +32 27 wwwwwwwwwwwwwwwpwwe +32 28 wwwwwwwe +32 29 wwwwwwwwwwwe +32 30 wwwwwe +33 1 wwwwwwwwpwwwwwe +33 2 wwwwwwpwwwwwwe +33 3 wwwpwwwe +33 4 wwwwwwwwpwwwwwwwpwwwwpwwwpwwwwwwe +33 5 wwwwwwpwwwwwwwwpwwwwwwwwwwpwwwwe +33 6 wwwwwpwwpwwwwwwwwwwwwwwwwwpwwwwwe +33 7 wwwwwwwwwwwwwpwwwwe +33 8 wwwwpwwwwe +33 9 wwwwwwwwwwwwwwwwpwwwwwe +33 10 wwwwwwwwwwwwwwwwe +33 11 wwwwwwe +33 12 wwwwwwwwwwwwwe +33 13 wwwwwwwwwwpwwwwwwwwwwwpwwwwe +33 14 wwwwwwwwwwwwwwe +33 15 wwwwwwwwwpwwwwe +33 16 wwwwwwwwwwwwwwwe +33 17 wwwwwwwwwwwwwwwpwwwwwwwwwe +33 18 hwwwwwwwwwpwwwwwe +33 19 wwpwwwwwwwwwwwwwpwwwwwwwwwpwwwwwwpwwwwwe +33 20 wwwwpwwwwwwwwwwwwpwwwwwwwe +33 21 wwwwwwwwwwwwwwwwwe +33 22 wwwwwwwwwwwwwpwwwwwe +33 23 wwwwwwwwpwwwwwwwpwwwe +33 24 wwwwwwwwwwwpwwwwwe +33 25 wwwwwwwwpwwwwpwwwwe +33 26 wwwwwwwwwwwwwwwwe +33 27 wwwwwwwpwwwwwwe +33 28 wwwwwwwwwwwwwwwe +33 29 wwwwwwwwwwwwwwe +33 30 wwwwwwwwwwwpwwwwwe +33 31 hwwwwwwwwwwwwwwe +33 32 wwwwwwpwwwwwwwwwwwwwe +33 33 wwwwwwwwpwwwwwwwpwwwwwwwwwwe +33 34 wwwwwwwwwpwwwwwe +33 35 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +33 36 wwwwwwwwwwwwwwwwpwwwwwwwwe +33 37 wwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwwwwwwpwwwwe +33 38 wwwwwwwwwwpwwwwwwwpwwwwwe +33 39 wwwwwwwwwwpwwwe +33 40 wwwwwwwwwwwwpwwwwwe +33 41 wwwwwwwe +33 42 wwwe +33 43 wwwwwwwwwwpwwwe +33 44 wwwwpwwwwe +33 45 wwwwwwwe +33 46 wwwwwwe +33 47 wwwwwwwwe +33 48 wwwwwwwwwpwwwe +33 49 wwwwwwwwwwwwwwwwwwpwwwwe +33 50 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwwpwwwwe +33 51 hwwwwwwwwpwwwwwwwpwwwwwwwwwwwpwwwwwpwwwwe +33 52 wwwwwwwwwwwwwwwwwwwpwwwwwwe +33 53 wwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwpwwwwwpwwwwwwwpwwwwpwwwwwwwwwwwwwwpwwwwwwe +33 54 wwwwwwwwwwwe +33 55 wwwwwwwwwwwwwwwwwwwwwpwwpwwwwwwwe +33 56 wwwwwwpwwwwwwwe +33 57 wwwwwwwwwwwwwwe +33 58 wwwwwwwwwwwwe +33 59 wwwwwwwwwwwpwwwwwwpwwwwe +33 60 hwwwwwwwwwwwwwwwwwwwe +33 61 wpwwwwwe +33 62 wwwwwwwpwwwwwe +33 63 wwwwpwwwwwpwwwwwwe +33 64 wwwwwwwe +33 65 wwwpwwwwwe +33 66 wwwwwwwwwwwe +33 67 wwwwwwwwe +33 68 wwwwwwwwe +33 69 wwwwwwwwwwwwpwwwwe +33 70 wwwwwwwwe +33 71 wwwwwwpwwwwwwwwe +33 72 wwwwwwwwwwwwwwpwwwwe +33 73 wwwwwwwwwwwpwwwwe +34 1 wwwwwwwwwwwwwwpwwwe +34 2 wwwwwwwwwwwwwwwpwwwe +34 3 wwwwwwpwwwwwwpwwwwwwwwwwwwwwwwwwwwe +34 4 wwwwwpwwwwwe +34 5 wwwwwwwwwwwe +34 6 wwwwwwwwwwwwwwwwe +34 7 wwwwwwwwwwwwwwwwe +34 8 wwwwwwwpwwwwwwwwwe +34 9 wwwwwwwwwwwpwwwwwwwwwwwpwwwwwwwe +34 10 hwwwwwpwwwwpwwwe +34 11 wwwwwwpwwpwwwwe +34 12 wwwwwwpwwwwpwwwwwwwwpwwwwwwwwwe +34 13 wwwwwwwwwwwpwwwwpwwwwe +34 14 wwwwwwwwwwwwwpwwwwwwwwwwwwwwe +34 15 wwwwwwpwwwwpwwwwwwpwwwwe +34 16 wwwwwwwwwwwwwwwwe +34 17 wwwwpwwwwe +34 18 wwwwwwwwwwwwpwwwwwe +34 19 wwwwwwwwwwwwpwwwwwwwe +34 20 wwwwwwwwwwe +34 21 wwwwwwwwwwwwwwwwpwwwwwe +34 22 wwwwwwwpwwwwwwwwwwwwwwwwwwwe +34 23 wwwwwwwwpwwwwwwwwwpwwpwwwe +34 24 hwwwwwwpwwpwwwwwwwwwe +34 25 wwwwwwwwwe +34 26 wwwwwwwwwwwe +34 27 wwwwwwpwpwwwwwe +34 28 wwwwwwwwwwwwe +34 29 wwwwwwwe +34 30 wwwwwwwwwwe +34 31 wwwwwwwwwwwpwwwwwwwwwwwwwwwwwwwwwe +34 32 wwwwwwwwwwwwpwwwe +34 33 wwwwwwwwwwwwwwwwwpwwwwwwwwwwwpwwwwwwe +34 34 wwwwwwwwwwwwwwe +34 35 wwwwwwwwe +34 36 wwwwwwwwwwwwwe +34 37 wwwwwwwwwwwwwwwwwwwwwwwe +34 38 wwwwwwwwwe +34 39 wwwwwwwwwwwpwwwwwwpwwwe +34 40 wwwwwwwwwwe +34 41 wwwwwwpwwwwpwwwe +34 42 wwwwwwwwwwwwwwwwwwe +34 43 wwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwe +34 44 wwwwwpwwwwwwe +34 45 wwwwwwwwwwwpwwwe +34 46 hwwwwpwwwwwwwpwwwwpwwwwwwwwwe +34 47 wwwwwwwpwwwwwpwwwwwe +34 48 wwwwwwwe +34 49 wwwwwwwwe +34 50 wwwwwwwpwwwwwwpwwwe +34 51 wwwwwwwwwwe +34 52 wwwwwwwwwe +34 53 wwwwwpwwwwwe +34 54 wwwwwwwwwwpwwwwwe +35 1 wwwwwwwwwwwwwpwwwwwpwwwwwwe +35 2 wwwwwwwwwpwwwwwwwpwwwe +35 3 wwwwwwpwwwwwwwwwpwwwwpwwe +35 4 wwwwwwwpwwwwe +35 5 wwwwwwpwwwwpwwwwe +35 6 wwwwwwpwwwwwwwe +35 7 wwwwwpwwwwwwwwe +35 8 wwwwwwwpwwwwwwwwpwwwwwpwwwwwe +35 9 wwwwwwwwwwwwwwwpwwe +35 10 wwwwwwwpwwwwwwwpwwwwwwpwwwwe +35 11 wwwwwwwwwwpwwwwwwwwpwwwwwwwwwwwpwwwwwe +35 12 wwwwwwwwwwwpwwwwwwwwpwwwwwwwwwe +35 13 wwwwwwwwwwwwwwwpwwwwwpwwwwwwwwe +35 14 wwwwwwwwwwpwwwwpwwwwe +35 15 hwwwwwwpwwwwe +35 16 wwwwwwe +35 17 wwwwwe +35 18 wwwwwpwwwwwwwwwwwwwpwwwwwwwwpwwwwwpwwwe +35 19 wwwwe +35 20 wwwwe +35 21 wwwwe +35 22 wwwwwpwwwwwpwwwwwwe +35 23 wwwwe +35 24 wwwwwpwwwwwwwe +35 25 wwwwwwwwwwwwwe +35 26 wwwwpwwwe +35 27 wwwwwwwwwwwwwpwwwwwwwwwe +35 28 wwwwwwwpwwwwwwpwwwwe +35 29 wwwwwwwwwwwwwwwwe +35 30 wwwwwpwwwe +35 31 wwwwwwwwwwwpwwwwwe +35 32 wwwwwwwpwwwwwwwwwwpwwwwe +35 33 wwwwwwwwwwpwwwe +35 34 wwwwwwwpwwwwe +35 35 wwwwwwwwwwwwwwe +35 36 wwwwwwwwwwwwwwpwwwwe +35 37 wwwwwwwwwwwpwwwwwwwwwpwwwwwe +35 38 wwwwwwpwwwwe +35 39 wwwwwwpwwwwpwwwwwwwwpwwwwwwe +35 40 wwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwe +35 41 hwwwwwwwpwwwwwwwwpwwwwe +35 42 wwwwwwwwwwwwpwwwwwwwe +35 43 wwwwwpwwwwwwpwwwwwpwwwwwpwwwwwe +35 44 wwwwwwwwwwwwwwwpwwwwwwwwwwwpwwwwe +35 45 wwwwwwwwwwwwwwwwwpwwwwwwwwe +36 1 we +36 2 wwe +36 3 wwwe +36 4 wwwe +36 5 wwwe +36 6 wwwwwwwe +36 7 wwwwwwwwe +36 8 wwwwwwwwwwe +36 9 wwwwwwwwwwwwe +36 10 wwwwwwwwe +36 11 wwwwwwwwpwwwwe +36 12 wwwwwwwwpwwwwwwe +36 13 wwwwwwwwe +36 14 wwwwwwwwwwwe +36 15 wwwwwwwwwwwwwwwe +36 16 wwwwwwe +36 17 wwwwwe +36 18 wwwwpwwwwwwwwe +36 19 wwwpwwpwwwwe +36 20 wwwwwwwwwwe +36 21 wwwwwwwe +36 22 wwwwwwwwe +36 23 wwwwwwwwwwwwwwwe +36 24 wwwwwe +36 25 wwwwe +36 26 wwwpwwwwe +36 27 wwwwwwwe +36 28 hwwwwwwwwwwwwwe +36 29 wwwwwwwwe +36 30 wwwpwwwwwwwwe +36 31 wwwwwwwwwwwe +36 32 wwwwwwe +36 33 wwwwwwwwwwe +36 34 wwwwwwwwwwe +36 35 wwwwwwpwwe +36 36 wwwwwwwwwwwwwe +36 37 wwwwwwwwwe +36 38 wwwwpwwwwe +36 39 wwwwwwwe +36 40 wwwwwwwwwwwpwwwwe +36 41 wwwwwwwwe +36 42 wwwwwwe +36 43 wwwwwwwwwe +36 44 wwwwwwe +36 45 wwwwwwwwwwwe +36 46 wwwwwwwwwwwe +36 47 wwwwwwwwwwwwwwwwwwwwwwwwe +36 48 wwwwwwwe +36 49 wwwwwwwwe +36 50 wwwwwwwe +36 51 wwwwwwwwwwe +36 52 wwwwwwppwwwwwwe +36 53 wwwwwwwwwwe +36 54 wwwwwwwwwwwe +36 55 wwwwwwwe +36 56 wwwwwwwe +36 57 wwwwwwe +36 58 wwwwwe +36 59 wwwwe +36 60 hwwwwwwwwwpwwwwe +36 61 wwpwwwe +36 62 wwwwwpwwwe +36 63 wwwwwe +36 64 wwwwwe +36 65 wwwwwwwwwwwe +36 66 wwwwwwwwwe +36 67 wwwwwwwwwwe +36 68 wwwwwpwwe +36 69 wwwwwwpwwwwwwe +36 70 wwwwwwwwe +36 71 wwwwwwwwwwwwe +36 72 wwwwwwe +36 73 wwwwpwwe +36 74 wwwwwwwe +36 75 wwwwwwwe +36 76 wwwpwwwwwwe +36 77 wwwwwwwwwwwe +36 78 wwwwwpwwwwwwe +36 79 wwwwwwpwwwwe +36 80 wwwwwwwwwwwe +36 81 wwwwwwwwwwpwwwwe +36 82 wwwwwwwwwwe +36 83 wwwwwwwwe +37 1 wwe +37 2 wwe +37 3 wwe +37 4 wwwe +37 5 wwwwwwwe +37 6 wwwwwwe +37 7 wwwwwe +37 8 wwwwwwwwwe +37 9 wpwwwe +37 10 wwwwwwwe +37 11 wwwwwwwpwwwwwe +37 12 wwwe +37 13 wwwwe +37 14 wwwwe +37 15 wwwwwwe +37 16 wwwwwwwe +37 17 wwe +37 18 wwwwe +37 19 wwwwwwwe +37 20 wwwwwe +37 21 wwwwwwwe +37 22 hwwwwwwwe +37 23 wwwwwwwe +37 24 wpwwe +37 25 wwwwe +37 26 wwwwe +37 27 wwwwwe +37 28 wwwwwwe +37 29 wwwwwe +37 30 wwwwwwpwwwwe +37 31 wwwwpwwe +37 32 wwwwe +37 33 wwwwwe +37 34 wwwwe +37 35 wwwwwwwwwwe +37 36 wwwwwwe +37 37 wwwwwe +37 38 wwwwe +37 39 wwwwwwe +37 40 wwwwe +37 41 wwwwe +37 42 wpwwe +37 43 wwwe +37 44 wwwe +37 45 wwwwwe +37 46 wwwe +37 47 wwwwwwwe +37 48 wwwwe +37 49 wwwe +37 50 wwwwwe +37 51 wwwwwwwe +37 52 wwwwe +37 53 wwwwwwwe +37 54 wwwwe +37 55 wwwwwe +37 56 wwwwwe +37 57 wwwwwwe +37 58 wwwe +37 59 wwwwwwe +37 60 wwwwwe +37 61 wwwwe +37 62 wwwwwwe +37 63 wwwwe +37 64 wwwwwwe +37 65 wwwwe +37 66 wwwwwwe +37 67 wwwwwwwe +37 68 wwwwwe +37 69 wwwwe +37 70 wwwwe +37 71 wwwwwe +37 72 wwwwe +37 73 wwwwwe +37 74 wwwwe +37 75 wwwwwe +37 76 wwwwwe +37 77 wwwwe +37 78 wwwwe +37 79 wwwwwe +37 80 wwwwe +37 81 wwwwe +37 82 wwwe +37 83 hwwwwe +37 84 wwwwwe +37 85 wwwwwwe +37 86 wwwwwe +37 87 wwwwe +37 88 wwwwe +37 89 wwwe +37 90 wwwe +37 91 wwwwwwe +37 92 wwwwe +37 93 wwwwe +37 94 wwwe +37 95 wwwwe +37 96 wwwwe +37 97 wwwwwwwe +37 98 wwwwwe +37 99 wwwwwwe +37 100 wwwwwe +37 101 wwwe +37 102 wwwwwwwwwwwwwwwpwwwwwpwwwwwwe +37 103 wwwwe +37 104 wwwe +37 105 wwwpwwwwe +37 106 wwwwwe +37 107 wwwe +37 108 wwwwe +37 109 wwwe +37 110 wwwe +37 111 wwwwe +37 112 wwwwwe +37 113 wwwwpwwwwwwe +37 114 wwwwwe +37 115 wwwwwe +37 116 wwwwe +37 117 wwwe +37 118 wwwe +37 119 wwwwe +37 120 wwwwe +37 121 wwwwe +37 122 wwwwe +37 123 wwwwe +37 124 wwwwwe +37 125 wwwwwe +37 126 wwwwwe +37 127 wwwe +37 128 wwwwe +37 129 wwwwe +37 130 wwwwe +37 131 wwwwe +37 132 wwwwe +37 133 wwwwe +37 134 wwwwe +37 135 wwwwe +37 136 wwwe +37 137 wwwwe +37 138 wpwwe +37 139 wwwwe +37 140 wwwwwe +37 141 wwwwe +37 142 wwwwe +37 143 wwwwwe +37 144 wwwwwwe +37 145 hwwwwe +37 146 wwwwwe +37 147 wwwwwwe +37 148 wwwwe +37 149 wwwwwe +37 150 wwwwwwe +37 151 wwwwwe +37 152 wwwwe +37 153 wwwwe +37 154 wwwwe +37 155 wwe +37 156 wwwwe +37 157 wwwwwe +37 158 wwwwwpwwwwwe +37 159 wwwwe +37 160 wwwwe +37 161 wwwe +37 162 wwwwe +37 163 wwwwwe +37 164 wwwwwwe +37 165 wwwe +37 166 wwwe +37 167 wwwe +37 168 wwwwwwe +37 169 wwwwe +37 170 wwpwwe +37 171 wwwwwe +37 172 wwwe +37 173 wwwwe +37 174 wwwwe +37 175 wwwe +37 176 wwe +37 177 wwwwwwe +37 178 wwwwe +37 179 wwwe +37 180 wwwwwwe +37 181 wwwe +37 182 wwwwe +38 1 wpwwwe +38 2 wwwwwwe +38 3 wwwwwwwwwwe +38 4 wwwwwpwwwwwe +38 5 wwwwpwwwwe +38 6 wwwwwwwwpwwwwe +38 7 wwwwwwwwwwe +38 8 wwwwwpwwwwwwpwwwwe +38 9 wwwwwwwe +38 10 wwwwwwwpwwwe +38 11 wwwwwwe +38 12 wwwwwwwwe +38 13 wwwwwpwwe +38 14 wwwwwwwe +38 15 wwwwwwwwwwe +38 16 wwwwwwwwe +38 17 wwwwwwwwwpwwe +38 18 wwwwwwwe +38 19 wwpwwwe +38 20 wwwwwwe +38 21 hwwwwwwwe +38 22 wwwwwwpwwwpwwwwwwwwwwwwwwe +38 23 wwwwwwwwwwwwwwwe +38 24 wwwwwwwpwwwwwwwwwwwwwwwwpwwwwwwwwwse +38 25 wwwpwwwwwwe +38 26 wwwwwwwwwwwwwwwwwpwwwwwwwwwwwwwe +38 27 wwwwwwwpwwwwpwwwwwe +38 28 wwwwwwwwwwwwwe +38 29 wwwwwwwwwe +38 30 wwwpwwpwwe +38 31 wwwwwwe +38 32 wwwwwwwwwwwe +38 33 wwpwwwwe +38 34 wwwwwwwwwe +38 35 wwwwwwwwwwwwpwwwe +38 36 wwwwwwwwe +38 37 wwwwe +38 38 wwwwe +38 39 wwwwwwwe +38 40 wwwwwwe +38 41 wwwwwwwwwwwe +38 42 wwpwwwwe +38 43 wwwwwwwwwwe +38 44 wwwwwwwpwwwpwwpwwe +38 45 wwwwwwwwe +38 46 wwwwwe +38 47 wwwwwe +38 48 wwwwwpwwwe +38 49 wwpwwwwe +38 50 wwwwwe +38 51 wwwwwwwe +38 52 hwwwwe +38 53 wwwwwe +38 54 wwwwwwwe +38 55 wpwwwwe +38 56 wwwwe +38 57 wwwwe +38 58 wwwwe +38 59 wwwwpwwwpwwwe +38 60 wwwwwwpwwwpwwe +38 61 wwwwwwwwwwwe +38 62 wwwwwwwwwwe +38 63 wwwwwwe +38 64 wwwwwwe +38 65 wwwwpwwwwwwwe +38 66 wwwwwwwe +38 67 wwwwe +38 68 wwwe +38 69 wwwwwwwwwe +38 70 wwwwwwwwe +38 71 wwwwwwwwwe +38 72 wwwwwwwwwe +38 73 wwwwe +38 74 wwwwwwe +38 75 wwwwwwwwwpwwwwwe +38 76 wwwwpwwwwwwe +38 77 wwwwwe +38 78 wwwwwwe +38 79 wwwwwwe +38 80 wwwwe +38 81 wwwwe +38 82 wwwwe +38 83 wwwwe +38 84 wwwwe +38 85 wwwwwwwe +38 86 wwwwwwwwwwe +38 87 wwwwwe +38 88 wwwwe +39 1 wwwwwwe +39 2 wwwwwwwwwwe +39 3 wwwwpwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwe +39 4 wwwwwwwwwwwpwpwwwwe +39 5 wwwwpwwwwwwwwpwwwpwwwwpwwwwe +39 6 wwwwwwwwwwwwwwpwwwwwwwwwwwpwwwwwpwwwwpwwe +39 7 wwwwwwpwwwwpwwwwpwwwwwpwwwwwwwwpwwwwe +39 8 hwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwpwwwwe +39 9 wwwwwwwwwwwwpwwwwwwwwpwwwwe +39 10 wwwwwwpwwwwwwpwwwpwwwwwwe +39 11 wwwwwwwwwe +39 12 wwwwwe +39 13 wwwwwwwwwe +39 14 wwwwwwe +39 15 wwwwwpwwwwwwwwwpwwwwwe +39 16 wwwwwwwwwpwwwwwpwwe +39 17 wwwwwwwwwwpwwe +39 18 wwwwwpwwwwpwwwwe +39 19 wwwwwwwwwwe +39 20 wwwwwwwwwwwwwwpwwpwwwwe +39 21 wwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwe +39 22 wwwwwwwwwwpwwwwwwpwwwwe +39 23 wwwwwwwwwwwwwwwwwwwwpwwwwwwwpwwwwwwwe +39 24 wwwwwwwpwwwwwwe +39 25 wwwwwwwwwwe +39 26 wwwwwwpwwwpwwwe +39 27 wwwwwwwwwwwe +39 28 wwwwwwwe +39 29 wwwwwwwwwwwwwpwwpwwwwe +39 30 wwwwe +39 31 wwwwwwwe +39 32 hwwwwwwwwwwpwwwwwe +39 33 wwwwwpwwwe +39 34 wwwwwpwwwe +39 35 wwwwwwwwwwwwe +39 36 wwwwpwwwwpwwwwwwwe +39 37 wwwwwwwpwwwwwe +39 38 wwwwwwwwpwwwwwwwwwwwwwwwwwwwwwwpwwwpwwwe +39 39 wwwwwwwpwwe +39 40 wwwwwwwwe +39 41 wwwwwwpwwwpwwwwwpwwwwe +39 42 wwwwwwwwwwpwwwwwwwwwwpwwwwwwe +39 43 wwwwwwpwwwwwwwwe +39 44 wwwwpwwwwpwwwe +39 45 wwwwwwwwwwpwwwwwwwwe +39 46 wwwwwwwwwwwwwwwwwe +39 47 wwwwwwwwwwwwwwwwwpwwwwwwwwe +39 48 wwwwwwwwwwwe +39 49 wwwwwwwwwwwwwwwpwwwwwwwe +39 50 wwwwwwwwwwwe +39 51 wwwwpwwwwwwwwwwwe +39 52 wwwwwwwwwpwwwwwwe +39 53 hwwwwwwwwwwwpwwwwwpwwwwe +39 54 wwwwwwwwwwwwwe +39 55 wwwwwwwwwwwwwwwwe +39 56 wwwwwwwwwwwwwwe +39 57 wwwwwwwwwe +39 58 wwwwwwwwwwwwe +39 59 wwwwwwwwwwe +39 60 wwwwwwwwwpwwwwwe +39 61 wwwwwwwwwwwe +39 62 wwwwpwwwwwe +39 63 wwwwpwwwwwwwe +39 64 wwwwwwwe +39 65 wwwwwwwwwwwwwwe +39 66 wwwwwwe +39 67 wwwwwwwwwwwwwpwwwwe +39 68 wwwwwwwwwwwwwwpwwwwwwwwe +39 69 wwwwwwwwwwwwwwwe +39 70 wwwwwwwwwe +39 71 wwwwwwpwwwwwwwwwwwwwwwwwwwwpwwwwwwwwe +39 72 wwwwwwpwwwe +39 73 wwwwwwwpwwwwwwwwwwwwwe +39 74 wwwwwwwwwwwwwpwwwe +39 75 wwwwwwwwwpwwwwwwwwe +40 1 we +40 2 wwwwwwe +40 3 wwwwwwwwpwwwwpwwe +40 4 wwwwwwwwwwwwwe +40 5 wwwwwwwpwwwwwpwwwwwwpwwwe +40 6 wwwwwwwwwwe +40 7 wwwwwwwwwwwwwwwwwwwwwwwwwwwe +40 8 wwwwwwwwwwwwpwwwwe +40 9 wwpwwwwwwpwwwwe +40 10 wwwwwwwwwwwwwwwe +40 11 wwwwwwwwwwwwwe +40 12 wwwwwwwpwwwwpwwwwe +40 13 wwwwwwwwwpwwwwwe +40 14 wwwwwwwwe +40 15 wwwwwwwwwwwwwwwwe +40 16 wwwpwwwwwwpwwwpwwwe +40 17 wwwwwwpwwwpwwwwe +40 18 wwwwwwwwpwwwwwwwe +40 19 wwwwwwe +40 20 wwwpwwwwwwwpwwwwwe +40 21 hwwwwwwwwwwwwpwwwwwwwwwwwwwwwwwwe +40 22 wwwwwwwwwpwwwwe +40 23 wwwwwwe +40 24 wwwwwwwe +40 25 wwwwwwwwwwwwwpwwwwwwe +40 26 wwwwwwwpwwwwwwwwwwwe +40 27 wwwwwwwwwwwwwe +40 28 wwwwwwwwwwwwwwwwwwwpwwwwwpwwwwwwwpwwwwwwwwe +40 29 wwwwwwwwwwwwwwpwwwwwwwwwwwwe +40 30 wwwwwwwwwwe +40 31 wwwwwwwwwpwwwwwe +40 32 wwwwwwe +40 33 wwwwwwwwwpwwwwwwwe +40 34 wwwwwwwwwwwwwpwwwwwwwwwwpwwwwwwwe +40 35 wwwwwwwwpwwwwwwwpwwwwwwwwe +40 36 wwwwwwwwwe +40 37 wwwwwwwwwpwwwwwwwwpwwwwwwe +40 38 wwwwwwwwe +40 39 wwwwwwwwwwwe +40 40 wwwwwwwpwwwwwwwwwwwwwwwwe +40 41 hwwwwwwwwwe +40 42 wwwwwwwwwwwwwwwe +40 43 wwwwwwwwwwwwwwwwwwwwwwe +40 44 wwwwpwwwwpwwwwe +40 45 wwwwwpwwwwwe +40 46 wwwwwpwwwwwwwwe +40 47 wwwwwwwwwwwwwwwwwwwe +40 48 wwwwwwwwwwwwe +40 49 wwwwwwwwwwwwwe +40 50 wwwwwwpwwpwwpwwwwwwe +40 51 wwwwwwwwwwwe +40 52 wwwwwpwwwwwe +40 53 wwwwwwwwe +40 54 wwwwe +40 55 wwwwwwwwwwwwe +40 56 wwwwwwwwwpwwwwwwwwpwwpwwwwe +40 57 wwwwwwwwwwwwe +40 58 wwwwwwwwwwpwwwe +40 59 wwwwwwwwwwwe +40 60 wwwwwpwwwwwwwwe +40 61 wwwwwwwwwpwwwwwwwwwwwe +40 62 wwwwwwwwwwpwwe +40 63 wwwwwwwe +40 64 wwwwwwwwwwwwwwpwwwpwwwwe +40 65 wwwwwwwwwwpwwwwe +40 66 hwwwwwwwwwwwwwwwwwwwwe +40 67 wwwwwwwwwwwwwwwwwwwwpwwwwwpwwwwwe +40 68 wwwwpwwwwwwwwe +40 69 wwwwwwwwwwe +40 70 wwwwwwwpwwe +40 71 wwwwwwe +40 72 wwwwwwe +40 73 wwwwwwwe +40 74 wwwpwwwwwwwwwwpwwwwe +40 75 wwwwwwwwwwwe +40 76 wwwwwpwwwe +40 77 wwwwwpwwwwwwwwwe +40 78 wwwwwwwwwwwwwwpwwwwwwwwwpwwwwwwwwwe +40 79 wwwwwwwwwe +40 80 wwwwwwwwwwwwe +40 81 wwwwwwe +40 82 wwwwwwwwwwwpwwwwwwwwwwwwwwe +40 83 wwwwwwwwwwwwwwwe +40 84 wwwwwwwwwwwwe +40 85 wwwwwwwpwwwwwwwpwwwe +41 1 we +41 2 wwwwe +41 3 wwwwwwwe +41 4 wwwwwwwe +41 5 wwwwwwwwwwwwwwwwwe +41 6 wwwwwwwwwwwwwwpwwe +41 7 wwwwwwwwe +41 8 wwwwwwwwwe +41 9 hwwwwwwwwwwwpwwwe +41 10 wwwwwwwwwwwwwwwe +41 11 wwwwwwwwwwwwwwwwe +41 12 wwwwwwwwwwpwwwwwpwwwwe +41 13 wwwwwwwwwe +41 14 wwwwwwwwwwwwpwwwwwwwwwwwe +41 15 wwwwwwwwwwwwpwwwwwwwwwwpwwwe +41 16 wwwwwwwwwwwwwpwwwpwwwe +41 17 wwwwwwwwwwwwwwe +41 18 wwwwwe +41 19 wwwwwwwwe +41 20 wwwwwwwwwwwwe +41 21 wwwwwpwwwwwwwwwwwwwe +41 22 wwwwwwwwwwwwwwwwwwwwe +41 23 wwwwwwwwwe +41 24 wwwwwpwwwwwwe +41 25 hwwwwwwwwwwwwwwwwwwwwwwpwwwe +41 26 wwwwwwwwwwwe +41 27 wwwwwwwwwwe +41 28 wwwwwpwwwwpwwwwwe +41 29 wwwwwwwwwwwwwwwwe +41 30 wwwwwwwwwwwwwwwwwwwe +41 31 wwwwwwwpwwwwwwwwwe +41 32 wwwwe +41 33 wwwwwwwwwwwwwe +41 34 wwwwwpwwwwwwwwwwwwe +41 35 wwwwwwwwwwwe +41 36 wwwwwwwpwwwwe +41 37 wwwwwwpwwwwwwwwwwwwwe +41 38 wwwwwwwwwwwwse +41 39 wwwwwwwwwwwwpwwwwwpwwwwwe +41 40 wwwwwwwwpwwwwwwwwwwwpwwwpwwwwe +41 41 wwwwwwpwwwe +41 42 wwwwwwwwwpwwwwe +41 43 wwwwwwwwwwpwwwwwwwe +41 44 wwwwwwwwpwwpwwwwwwpwwwwwwwwwpwwwwwe +41 45 wwwwwwpwwwwwwwpwwwwwe +41 46 wwwwpwwwpwwwwe +41 47 hwwwwpwwwwwwwwwwwwwwpwwwwwwwwwwe +41 48 wwwwwwwpwwwwwe +41 49 wwwwwwwwwwwe +41 50 wwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwe +41 51 wwwwwwwwwwwwwe +41 52 wwwwwwwwwwwwwwwwwe +41 53 wwwwwwwwwwwpwwwwwwwwe +41 54 wwwwwwwpwwwwwe +42 1 we +42 2 we +42 3 wwwwwwwwwwe +42 4 wwwwwwwpwwwe +42 5 wwwwwpwwwwwwwwpwwwwwwe +42 6 wwwwwwwwwwwwe +42 7 wwwwwwwwwwwwwwwwpwwwwwwe +42 8 wwwwwwwwwwwwpwwwwwwwe +42 9 wwwwwpwwwwwwwwwwwe +42 10 wwwwwwwwpwwwwwwwe +42 11 wwwpwwwwwwwwpwwpwwwpwwwe +42 12 wwwwpwwwwwpwwwwe +42 13 hwwwwwwwwwwwwwwwwwpwwwwwwpwwwwwwpwwwwwwwwwe +42 14 wwwwwwwwwwpwwwwwwwwwwpwwwwwwwwwwe +42 15 wwpwwwpwwwpwwwwwwwpwwwpwwwpwwwwpwwwwpwwwpwwe +42 16 wwwwwwwwwwwwwwwwwwe +42 17 wwwwwwpwwwwwe +42 18 wwwwwwpwwwwwwwpwwwwwwwwwe +42 19 wwwwwwpwwwe +42 20 wwwwwwwwwpwwwwwwwwwwwwwe +42 21 wwwwwwwwwwwwpwwwwwpwwwwwe +42 22 wwwwwwwwpwwwwwwwpwwwwwpwwwwe +42 23 wwwwwwwwwpwwwwwwwwwpwwwwwwwpwwwwe +42 24 wwwwwwpwwwwwwpwwwwwwpwwwwe +42 25 wwwwwwwwwwwwe +42 26 wwwwwwwwpwwwwe +42 27 hwwwwwwwwwwwwwpwwwwe +42 28 wwwwwwwwwwpwwwe +42 29 wwwwwwwwwwpwwwwwwe +42 30 wwwwwwwwwwe +42 31 wwwwwpwwwwwwwwwe +42 32 wwwwwwe +42 33 wwwwwwwwpwwwwwwwe +42 34 wwwwwwwe +42 35 wwwwwwwwwe +42 36 wwwwwwwpwwwwwwwwwwe +42 37 wwwwwwwwwwe +42 38 wwwwwwwwwwwe +42 39 wwwwwwe +42 40 wwwwpwwwwwwpwwwwe +42 41 wwwwwwwwwe +42 42 wwwwwwwwwwwpwwwwe +42 43 wwwwwwwwe +42 44 wwwwwwwwwpwwwwwwwwwwwe +42 45 wwwwwwwwwwpwwwwwwwwwwwpwwwwwwe +42 46 wwwwwwwwwpwwwwwwwe +42 47 wwwwwwwwwwwwpwwwwwwwwwe +42 48 wwwwwwpwwwwpwwwwwwwwpwwwwwwwwwe +42 49 wwwwpwwwpwwwwwwwwe +42 50 wwwwpwwwwpwwwe +42 51 hwwwwwwwwwwwwwwwwwwwpwwwe +42 52 wwwwwwpwwwwwwwwwwwwwwwwpwwwwwe +42 53 wwwwwwwwwwpwwwwwe +43 1 we +43 2 wwe +43 3 wwwwwwe +43 4 wwwwwwwe +43 5 wwwwwwwwe +43 6 wwwwwwe +43 7 wwwwwwwwe +43 8 wwwwwwwe +43 9 wwwwwwwwwwe +43 10 wwwwwwwwwwwe +43 11 wwwwwwwwwwpwwe +43 12 wwwwwwwwwwwe +43 13 wwwwwwwwwwwwwwwwwwwwe +43 14 wwwwe +43 15 wwwwwpwwwwe +43 16 wwwwwwwe +43 17 wwwwwwwwwwwwe +43 18 wwwwwwwwwe +43 19 wwwwwwwpwwpwwwe +43 20 wwwwwwpwwwwwpwwwwe +43 21 wwwwwwwwe +43 22 wwwwwwwwwwwe +43 23 wwwwwwwwwwwwwwwwwwwwwe +43 24 hwwwwwwwwpwwwwwwe +43 25 wwpwwwwwe +43 26 wwwwwwwwwe +43 27 wwwwwe +43 28 wwwwwwwe +43 29 wwwwwwwwwe +43 30 wwwwwwwwwe +43 31 wwwwwwwwwwe +43 32 wwwwpwwwwwwwpwwwwwwwwwpwwwwwe +43 33 wwwwwwwwwwwwwwwwwe +43 34 wwwwwe +43 35 wpwwwwwwwpwwwwe +43 36 wwwwwwwwwwwe +43 37 wwwwwwwe +43 38 wwwwwwwwwwwe +43 39 wwwwwwwwwe +43 40 wwwwwwwwwwwe +43 41 wwwwwwe +43 42 wwwwwwwe +43 43 wwwwpwwwwe +43 44 wwwwpwwe +43 45 wwwwwwwwwwwwwe +43 46 wwwwwwwwwwwwe +43 47 wwwwwwwe +43 48 wwwwwwwwwpwwwwe +43 49 wwwwwwwwwwwe +43 50 wwwwwwwe +43 51 wwwwwwwwwwwwwwwpwwe +43 52 wwwwwwwwwwwe +43 53 wwwwwwwwwwwe +43 54 wwwpwwwwe +43 55 wwwwwwe +43 56 wwwwe +43 57 hwwwwwwwwwe +43 58 wwwwwpwwwwwpwwwwe +43 59 wwwwwwwwwwe +43 60 wwwwwwwwe +43 61 wwwwwwwpwwwe +43 62 wwwpwwwwe +43 63 wwwwwwwwwwwwwwpwwwe +43 64 wwwwwwpwwwe +43 65 wwwwpwwwwwwwe +43 66 wwwwwwwwwwe +43 67 wwwwwwwe +43 68 wwwwwwwwe +43 69 wwwwwe +43 70 wwwwwe +43 71 wwwwwwpwwwwwwpwwwe +43 72 wwwwwwwe +43 73 wwwwwwe +43 74 wwwwwwe +43 75 wwwwwwe +43 76 wwwwwwe +43 77 wwwwwpwwwe +43 78 wwwwwwwe +43 79 wwwwwe +43 80 wwwwwwwpwwwwe +43 81 wwwwwwwwe +43 82 wwwwwwwwe +43 83 wwwwwwwwe +43 84 wwwwwwwwpwwwe +43 85 wwwwwwwwwwwwwe +43 86 wwwwwwwwwwwwwe +43 87 wwwwwwpwwe +43 88 wwwwwwwe +43 89 wwwwpwwe +44 1 we +44 2 wwe +44 3 wwwwwpwwwe +44 4 wwwwwe +44 5 wwwpwwwe +44 6 wwwpwwwwe +44 7 wwwwwpwwwe +44 8 wwwwwwpwwwwe +44 9 wwwwwe +44 10 wwwwwwe +44 11 wwpwwwe +44 12 wwwwwwe +44 13 wwwwwwwe +44 14 wwwwwwe +44 15 wwwwpwwe +44 16 wwwwwwe +44 17 hwwwwwwwwe +44 18 wwwwwpwwwwe +44 19 wwwwwpwwwwe +44 20 wwwwwwe +44 21 wwwwwe +44 22 wwwwwwe +44 23 wwwwwe +44 24 wwwpwwwe +44 25 wwwwwe +44 26 wwwe +44 27 wwwwe +44 28 wpwwwe +44 29 wwwwwwwwe +44 30 wwwwwwwe +44 31 wwpwwwwwe +44 32 wwwwwwe +44 33 wwwwwwwe +44 34 wwwe +44 35 wwwwwwwwe +44 36 wwwwwe +44 37 wwwwwwwwpwpwwwe +44 38 wwwwwwwe +44 39 wwwwwwwwe +44 40 wwwwwe +44 41 wwwwwwwwwwe +44 42 wwwwpwwwwe +44 43 wwwe +44 44 wwe +44 45 wwwwe +44 46 wwe +44 47 wwwwwe +44 48 wwwwwwwe +44 49 wwwwwe +44 50 wwwwwwe +44 51 wwwwwe +44 52 wwwe +44 53 wwwwwe +44 54 wwwwe +44 55 wwwwwe +44 56 wwwwwwwpwwwe +44 57 wwwpwwwwe +44 58 wwwwwe +44 59 wwwe +45 1 we +45 2 wwwwwwe +45 3 wwwwwwe +45 4 wwwwwwwwwe +45 5 wwwwwwwwwwwwwwwwwwwwe +45 6 wwwwwwpwwwwwwe +45 7 wwwwe +45 8 wwwwwwwwwwwpwwwe +45 9 wwwwwwwpwwwwe +45 10 wwwpwwwwwwwwwwwwwpwwwe +45 11 wwpwwwwwwwwwe +45 12 hwwwwwwwwwwwwwwe +45 13 wwwwwwwwwwpwwwwwwe +45 14 wwwwwwwwwwwwwwe +45 15 wwwwpwwwpwwwwe +45 16 wwwwwwwwwwwwwe +45 17 wwwwpwwwwwwwwwwpwwwwwwwwwwe +45 18 wwwwwwwwwwwwwe +45 19 wwwwwwwpwwwwwpwwwe +45 20 wwwwwwwe +45 21 wwwwwwwwwwwwwwpwwwe +45 22 wwwwwwwwwwwwwe +45 23 wwwwwwwwwwwwwwwwwwwwwwpwwe +45 24 wwwwwwwwwwwwpwwwwwpwwwwe +45 25 wwwwwwwwwwwwwwwwe +45 26 wwwwwwwwwwwwwwwwwwe +45 27 wwwwpwwwwwwe +45 28 wwwwpwwwwwwwwwwe +45 29 wwwwwpwwwwwwe +45 30 wwwwwwwwwpwwwwe +45 31 wwwwwwwwwwwwe +45 32 wwwwwwwwwwwwwwwwwwwwwwe +45 33 wwwwwwwwwwwe +45 34 wwwwwwwwwwwwwwe +45 35 wwwwwwwwwpwwwwwwwe +45 36 wwwwwwwwe +45 37 wwwwwpwwwe +46 1 we +46 2 wwwwwwe +46 3 wwwwwwwwwwpwwwwwe +46 4 wwwwwwwwwwwwwwwwwpwwwwwwwwwwwwe +46 5 wwwwwwwwwwwwwwwwwwe +46 6 wwwwwwwwwe +46 7 wwwwwwwwwwwwwwe +46 8 wwwpwwwwwwwwwpwwwwwpwwwwwpwwwe +46 9 wwwwwwwwwwwwwpwwwwwwwwwwwe +46 10 wwwwwwwwwwwwwwwwwwpwwwwwwe +46 11 wwwwwwwwwwwpwwwwwwwwe +46 12 wwwwwwpwwwwwwwwwwe +46 13 wwwwwwwwwwwwwe +46 14 wwwwwwwwwe +46 15 wwwwpwwwwwpwwwwpwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwe +46 16 wwwwwwwwwwwwwpwwwwwe +46 17 wwwwwwwwwwwwwwwwwwwwwwwwwwwwe +46 18 wwwwwwwwwwwwwwpwwwe +46 19 wwwwpwwwwwe +46 20 wwwwwwwwwwwwwwwwwwwwwwwwwwwe +46 21 hwwwwwwwwwwwwwwwwwwwwwwwwwe +46 22 wwwwwwwwwwwwe +46 23 wwwwwwwwwwwwwe +46 24 wwwwwwwwwpwwwwwpwwwwe +46 25 wwwwwwwwwwpwwwwe +46 26 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +46 27 wwwwwwwwwwe +46 28 wwwwwwwwwpwwwpwwwwwe +46 29 wwwwwwwwwwwwpwwwwwwe +46 30 wwwwwwwwwwwwwwwwwwwe +46 31 wwwwwwwwwwwwwwe +46 32 wwwwwwwwwwwwwwpwwwwe +46 33 wwwwwwwwwwwwwwwwpwwwwwwe +46 34 wwwwwwwwwpwwwpwwwwwwe +46 35 wwwwwwwwwwpwwwwwwwwwwwpwpwwwwwe +47 1 wwwwwwwwe +47 2 wwwwwwwwwwwwwpwwwwwe +47 3 wwwwwwwwwwwwwpwwwwwe +47 4 wwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwpwwwwwwwwe +47 5 wwwe +47 6 wwwwe +47 7 wwwwwwwwwe +47 8 wwwwwwe +47 9 wwwwwwwwe +47 10 hwwwwwwwwwwwpwwwpwwe +47 11 wwwwwwwwwwwe +47 12 wwwwwwwwwwwwpwwwwwwwwwwe +47 13 wwwwwwwwwwwwwwe +47 14 wwwwwwwwwwwwwe +47 15 wwwwwpwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwpwwwwwwwwwwe +47 16 wwwwwwwwwwwwwwwwpwwwwwwwwe +47 17 wwwwwwe +47 18 wwwwwwwpwwwpwwwwwe +47 19 wwwwwwwwwwpwwwwe +47 20 wwwwwwpwwwwwwwpwwwwwwwwwwwwpwwe +47 21 wwwpwwwwwwwwwe +47 22 wwwwwwwwwwe +47 23 wwwwwwwe +47 24 wwwwwwwe +47 25 wwwwwwwwwwwpwwwwwe +47 26 wwwwwwwwwwwwpwwwe +47 27 wwwwwwwe +47 28 wwwwwwwwwwe +47 29 wwwwwwwwwwwe +47 30 wwwwwpwwwwpwwwe +47 31 wwwwwwwwe +47 32 wwwwwwwwwwwwwwwwwwwwwe +47 33 hwwwwwwwwwwe +47 34 wwwwwwwwwwwwwwwe +47 35 wwwwwwwwwwwwe +47 36 wwwwwpwwwwwwwwe +47 37 wwwwwwe +47 38 wwwwwwwwwwpwwwwwwpwwwwpwwwwwwwwwe +48 1 wwwwwe +48 2 wwwwwwwwwwwwwwwe +48 3 wwwwe +48 4 wwwwwwwwwwwpwwwwpwwwwe +48 5 wwwwwwwwwwwwwpwwwwwwe +48 6 wwwwwwwwwpwwwpwwwwwwwpwwe +48 7 wwwwpwwwwe +48 8 wwwwwe +48 9 wwwwwwwwe +48 10 wwwwwwwwwwpwwwwwwpwwwwwwwwwe +48 11 wwwwwwwwwwpwwwwwwpwwwwwwwwwwwwwwwpwwwwwwe +48 12 wwwwwwwwwwwwwwwwwwwwe +48 13 wwwwwwwwwe +48 14 wwwwpwwwwwwpwwwwe +48 15 wwwwwwwwwpwwwwwpwwwwwwwwpwwwpwwwwwwe +48 16 wwwwwwwwwwwwwpwwwwwwpwwwwwwwwwe +48 17 wwwwwwwwwwwwpwwwwwwwwwwpwwwwwe +48 18 hwwwwwwwwwwwwwwwwwwwe +48 19 wwwpwwwwe +48 20 wwwwwwwwwwwwwwwwwwe +48 21 wwwwwwwwpwwwwwwe +48 22 wwwwwwwwwwwwe +48 23 wwwwwwwpwwwwwe +48 24 wwwwwwwwwwwwwwpwwwwwe +48 25 wwwwwwwwwwwwpwwwwwwwwwwwwwwpwwwwwwpwwwwwwwwe +48 26 wwwwwwwwwwwwwwwwwwwwwwwpwwwwwe +48 27 wwwwwwpwwwwwwwwwwwwpwwwwwwwwwwe +48 28 wwwwwwwwwwwpwwwe +48 29 wwwpwwwwwwwpwwwwwwwwpwwwwwwpwwwwpwwwwwwwwwwwwwwwwpwwwwwwwwwwe +49 1 wwwwwwwwwpwwpwwwwe +49 2 wwwwwwwwwwwwwwwwwwwwwwe +49 3 wwwwwwwwwwwwwpwwwwe +49 4 wwwwwwwwwe +49 5 wwwwwwwwwpwwwe +49 6 wwwwwwwwwwwwwwwwwe +49 7 wwwwwpwwwwwwwwwwwwwwwwwwwwpwwwe +49 8 wwwwpwwwe +49 9 wwwwwwwpwwwwwwwwwwwwwpwwwwwwpwwwwe +49 10 wwwwwwpwwwwe +49 11 wwwwwwwwwwwwwwwwwwwwwwpwwwwwwpwwwwwpwwwwwwe +49 12 wwwwwwwwwwwpwwwwwwpwwwwwwwwpwwpwwwwe +49 13 wwwwwwwwwwwpwwwwwpwwwwe +49 14 hwwwpwwwwwwwwwwwpwwwwwwwwwpwwwwe +49 15 wwwwwwwwwwwwwwwpwwwe +49 16 wwwwwwwwwwwwpwwwwe +49 17 wwwwpwwwwwpwwwwwwwwwwe +49 18 wwwwwwpwwwwe +50 1 wpwwe +50 2 wwwwwwwwwwwe +50 3 wwwwpwwwe +50 4 wwwwwwpwwwe +50 5 wwwwwwwwwe +50 6 wwwwwwwwwwwwe +50 7 wwwwwwwwwwwe +50 8 wwwwwe +50 9 wwwwwwwwwwe +50 10 wwwwwe +50 11 wwpwwwwpwwe +50 12 wwwwwwwe +50 13 wwwwe +50 14 wwwwpwwwwwe +50 15 wwwpwwwwwwwe +50 16 wwwwwwwwpwwwwwwe +50 17 wwwwwwwwe +50 18 wwwwwwwwe +50 19 wwwwpwwwwwe +50 20 wwwpwwwe +50 21 wwwwwwe +50 22 wwwwwwwwwwwwe +50 23 wwwwwwe +50 24 wwwwwwe +50 25 wwwwe +50 26 wwwwwwwwwwe +50 27 hwwwwwwwwwwe +50 28 wwwwwwwwe +50 29 wwwwwwwwe +50 30 wwwwwwwwwe +50 31 wwwwwe +50 32 wwwwwwe +50 33 wwwwwwwe +50 34 wwpwwwe +50 35 wwwwwwe +50 36 wwwwwwwwwwwwwwwe +50 37 wwwwwwwwwwwwwe +50 38 wwwwwwwwwwwwwe +50 39 wwwwwwwwwwwwe +50 40 wwwwwe +50 41 wwwwwwwe +50 42 wwwwpwwwe +50 43 wwwwwwe +50 44 wwwwwpwwwwe +50 45 wwwwpwwwwpwwwwwe +51 1 wwe +51 2 wwe +51 3 wwe +51 4 wwe +51 5 wwwe +51 6 wwwe +51 7 wwwe +51 8 wwwwe +51 9 wwwwe +51 10 wwe +51 11 wwwwwe +51 12 wwwwe +51 13 wwwwwe +51 14 wwwwwwwe +51 15 wwwwwe +51 16 wwwwpwwwwwe +51 17 wwwwwwe +51 18 wwwe +51 19 wwwwwe +51 20 wwwwe +51 21 wwpwwe +51 22 wwwwwe +51 23 wwwwwwwwwe +51 24 wwwwwwe +51 25 wwwwwpwwwwe +51 26 wwwwwwe +51 27 wwwwwe +51 28 wwwpwwwpwwwe +51 29 wwwwwwwwwe +51 30 wwwwpwwwwe +51 31 hwwwwwe +51 32 wwwwwwe +51 33 wwwwwe +51 34 wwwwe +51 35 wwwwwwe +51 36 wwwwwwwe +51 37 wwwwwwwe +51 38 wwwwwwwwe +51 39 wwwwwwe +51 40 wwwwwwwe +51 41 wwwwwwwe +51 42 wwwwwwwwwe +51 43 wwwwwwwwe +51 44 wwwwwwwwe +51 45 wwwwwwwe +51 46 wwwwpwwwwe +51 47 wwwwwe +51 48 wwwwe +51 49 wwwwwwwe +51 50 wwwpwwwwwe +51 51 wwwwwwpwwwwwe +51 52 wwwwwwwwwwwwwe +51 53 wwpwwwwe +51 54 wwwwwe +51 55 wwwwwe +51 56 wwwwwwe +51 57 wwwwwwwwwe +51 58 wwwwwwwe +51 59 wwwwwwwwwe +51 60 wwwwwwwe +52 1 we +52 2 wwe +52 3 wwwe +52 4 wwe +52 5 wwe +52 6 wwe +52 7 wwwwe +52 8 wwwwe +52 9 wwwwe +52 10 wwwe +52 11 wwwe +52 12 wwwwwe +52 13 wwwwwwe +52 14 wwwwwwe +52 15 wwwwwwe +52 16 wwwwwwwpwwwwwe +52 17 wwwwwe +52 18 wwwwwwwwe +52 19 wwwwwwe +52 20 wwwwpwwwe +52 21 wwwwwwwwwwwwwwpwwwwwe +52 22 wwwwwe +52 23 wwwwwwwwe +52 24 hwwwwwwwe +52 25 wwwwwe +52 26 wwwwwwwe +52 27 wwwwwwe +52 28 wwwwwpwwwwe +52 29 wwwwwwwwe +52 30 wwwwwwwe +52 31 wwwwwwe +52 32 wwwwpwwwwe +52 33 wwwpwwwe +52 34 wwwwwwe +52 35 wwwwwwwwe +52 36 wwwwpwwwe +52 37 wwwwwwwe +52 38 wwwwwpwwwwe +52 39 wwwwwe +52 40 wwwwwwwe +52 41 wwwwwe +52 42 wwwpwwwwe +52 43 wwwwwpwwwwe +52 44 wwwwwwwwwe +52 45 wwwwwwwe +52 46 wwwwwwwwwe +52 47 wwwwwwwwwwe +52 48 wwwwwpwwwwwe +52 49 wwwwwe +53 1 wwwe +53 2 wwwwwe +53 3 wwwwe +53 4 wwwwwe +53 5 wwwe +53 6 wwwe +53 7 wwwe +53 8 wwwe +53 9 wwwwwe +53 10 wwwwwe +53 11 wwwwwe +53 12 wwwwe +53 13 wwwwe +53 14 wwwe +53 15 wwwe +53 16 wwwwwe +53 17 wwwwwe +53 18 wwwwwwe +53 19 wwwe +53 20 wwwe +53 21 wwwwe +53 22 wwwwe +53 23 wwwwwwwwwwwwwpwwwwwwwpwwwwwe +53 24 wwwwe +53 25 wwwe +53 26 hwwwwwwwwwwwwwwwwwwe +53 27 wwwwwwwwwe +53 28 wwwwwpwwwwpwwwwwwwe +53 29 wwwwwwwwwwwe +53 30 wwwwpwwwwwwwwwwwwe +53 31 wwwwwwwwwwwwwwwwe +53 32 wwwwwwwpwwwwpwwwwwwwwwwwwwpwwwpwwwwe +53 33 wwwe +53 34 wwwe +53 35 wwwwwe +53 36 wwwwwwwe +53 37 wwwe +53 38 wwwwwe +53 39 wwwwwwe +53 40 wwwwe +53 41 wwwwe +53 42 wwwwe +53 43 wwwwe +53 44 wwwwe +53 45 wwwwwe +53 46 wwwwe +53 47 wwwwe +53 48 wwwwe +53 49 wwwwe +53 50 wwwwe +53 51 wwwe +53 52 wwwwpwwwwwe +53 53 wwe +53 54 wwwe +53 55 wwwwe +53 56 wwwwwe +53 57 wwe +53 58 wwwwwwe +53 59 wwwwe +53 60 wwwe +53 61 wwe +53 62 wwwse +54 1 wwwwe +54 2 wwwwwwwe +54 3 wwwpwwwe +54 4 wwwwwwwe +54 5 wwpwwwe +54 6 wwpwwwwwwe +54 7 wwwwwwwwe +54 8 wwwpwwwwwe +54 9 hwwwwwwwwwe +54 10 wwwwwe +54 11 wwwwwe +54 12 wwwwwwwwwe +54 13 wwwwwe +54 14 wwwwwwe +54 15 wwwwwwe +54 16 wwwwe +54 17 wwwwwwwe +54 18 wwwwwwe +54 19 wwwwwwwwwe +54 20 wwwwwwe +54 21 wwwwe +54 22 wwwwwwwe +54 23 wwwe +54 24 wwwwwwwwwwe +54 25 wwwwwwwwwe +54 26 wwwwwe +54 27 wwwwwwwe +54 28 wwwwwpwwwe +54 29 wwwwe +54 30 wwwwe +54 31 wwwwwwwwe +54 32 wwwwwwwe +54 33 wwwwe +54 34 wwwwwwwpwwe +54 35 wwwpwwwwe +54 36 wwwwwe +54 37 wwwwwwwwwe +54 38 wwwwwe +54 39 wwwe +54 40 wwwwwwwe +54 41 wwwwwe +54 42 wwwwwwwe +54 43 wwwwwwwwwe +54 44 wwwwwe +54 45 wwwwe +54 46 wwwwwwe +54 47 wwwwwe +54 48 wwwwwwwwwe +54 49 wwwwwe +54 50 wwwwwwe +54 51 wwwwwwe +54 52 wwwwwe +54 53 wwwwe +54 54 wwwwwe +54 55 wwwwwwe +55 1 we +55 2 wwe +55 3 wwe +55 4 wwe +55 5 wwwe +55 6 wwwe +55 7 wwwwe +55 8 wwwwe +55 9 wwwwwwe +55 10 wwwe +55 11 wwwwwe +55 12 wwwwe +55 13 wwwwe +55 14 wwwwwe +55 15 wwwwwwe +55 16 wwwwe +55 17 wwwwe +55 18 wwwwe +55 19 wwwe +55 20 wwwwe +55 21 wwwwe +55 22 wwwwe +55 23 wwwwe +55 24 wwwwwwe +55 25 wwwwe +55 26 wwwwe +55 27 wwwwwwe +55 28 wwwwe +55 29 wwwwwpwwwwwe +55 30 wwwwe +55 31 wwwwe +55 32 wwwwe +55 33 wwwwwwwwwwwwpwwwwe +55 34 wwwwe +55 35 wwwwwwwwe +55 36 wwwwe +55 37 wwwwwwe +55 38 wwwwe +55 39 wwwwwwwwe +55 40 wwwwe +55 41 wwwwwwe +55 42 wwwwe +55 43 wwwwwwe +55 44 wwwwwe +55 45 wwwwe +55 46 wwwwwe +55 47 wwwwe +55 48 wwe +55 49 wwwwe +55 50 wwwe +55 51 wwwwe +55 52 wwwwwe +55 53 wwwwe +55 54 wwwwwwpwwwe +55 55 wwwwe +55 56 wwwwwwwwwe +55 57 wwwwe +55 58 wwwe +55 59 wwwwe +55 60 wwwwwe +55 61 wwwwe +55 62 wwwe +55 63 wwwwe +55 64 we +55 65 wwwwe +55 66 wwwe +55 67 wwwwe +55 68 wwwwe +55 69 wwwwe +55 70 wwwe +55 71 wwwwe +55 72 wwwwe +55 73 wwwwe +55 74 wwwwwwe +55 75 wwwwe +55 76 wwwwwwe +55 77 wwwwe +55 78 wwwwwwe +56 1 wwwe +56 2 wwwe +56 3 wwe +56 4 wwwwe +56 5 wwwe +56 6 wwwe +56 7 wwwe +56 8 wwwwwe +56 9 wwwwwe +56 10 wwe +56 11 wwe +56 12 wwwe +56 13 wwwe +56 14 wwwe +56 15 wwwe +56 16 wwwe +56 17 wwwwe +56 18 wwwwwe +56 19 wwwwwe +56 20 wwwe +56 21 wwwwe +56 22 wwe +56 23 wwwe +56 24 wwwwe +56 25 wwwwwwe +56 26 wwwwe +56 27 wwwwwe +56 28 wwwe +56 29 wwe +56 30 wwe +56 31 wwe +56 32 wwe +56 33 wwwwe +56 34 wwe +56 35 wwwe +56 36 wwe +56 37 wwe +56 38 wwe +56 39 wwwe +56 40 wwwe +56 41 wwwwwe +56 42 wwwe +56 43 wwwe +56 44 wwwwe +56 45 wwwwwe +56 46 wwwwwe +56 47 wwwwwwwwwe +56 48 wwe +56 49 wwwwe +56 50 wwwwwe +56 51 wwwwwe +56 52 wwwwwe +56 53 wwwe +56 54 wwwwe +56 55 wwwe +56 56 wwwwe +56 57 wwwwe +56 58 wwwe +56 59 wwwwwe +56 60 wwwwwwwe +56 61 wwwwwwwwwe +56 62 wwwwwwe +56 63 wwwe +56 64 wwwwwe +56 65 wwwwwwe +56 66 wwe +56 67 wwwe +56 68 wwwwe +56 69 wwwwwwwe +56 70 wwwwwwe +56 71 wwwwe +56 72 wwwwwwe +56 73 wwwwwe +56 74 wwwwe +56 75 hwwwwe +56 76 wwwwwe +56 77 wwwe +56 78 wwwe +56 79 wwwwe +56 80 wwwwe +56 81 wwwwe +56 82 wwwwe +56 83 wwwwe +56 84 wwwe +56 85 wwwwwwwe +56 86 wwwwwe +56 87 wwwwe +56 88 wwwwwe +56 89 wwwwe +56 90 wwwwwwe +56 91 wwwwwe +56 92 wwwwwwe +56 93 wwwe +56 94 wwe +56 95 wwwwwe +56 96 wwwwe +57 1 wwwwwwpwwwe +57 2 wwwwpwwpwwwwwe +57 3 wwwwwpwwwwe +57 4 wwwwwwwwwwwwpwwwwwwwwwwwwwwwpwwwwwpwwwwe +57 5 wwwwpwwwwe +57 6 wwwwwwwwpwwwwe +57 7 wwwwwwwwpwwwwwwwe +57 8 wwwwwpwwwwwwwwwwe +57 9 wwwwwwwwwwwwpwwwwwe +57 10 wwwwwwwwwwwpwwwwwwwwwpwwwwwwwwwpwwwwpwwwwe +57 11 wwwwwwwwwwwwe +57 12 wwwwwwwwwwwwwwwwwwpwwwwe +57 13 wwwwwwwwwwwwwwwwwwwwwwwwwwwe +57 14 wwwwpwwwwwwwwwwwwwwwwe +57 15 wwwwwwwwwpwwpwwpwwe +57 16 hwwwwwwwwwwwwwwwwwwwwwwwwwpwwwe +57 17 wwwwwwwpwwwwwwe +57 18 wwwwwwwwwwwwe +57 19 wwwwwwwpwwwwwwpwwwwwwwe +57 20 wwwwwwwwwwwwwpwwwwwwwwwwwwpwwwwwwwwpwwwwwwe +57 21 wwwwwwwwwwwwwwwpwwwwwwpwwwwe +57 22 wwwwwwwwwwwwwwwwpwwwwwe +57 23 wwwwwwwwwpwwwwwwe +57 24 wwwwwpwwwwwwwe +57 25 wwwwwwwwwwwpwwwwwwwwwwwwwpwwwwe +57 26 wwwwwwwwwpwwpwwwe +57 27 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwpwwwe +57 28 wwwwwwwwwwwwwwwwwwpwwwe +57 29 wwwwwwwwwwwpwwwwwwwpwwwwe +58 1 wwwwwwwwwwwwwwpwwwwe +58 2 wwwwwwwwpwwwwwpwwwwwwpwwwwe +58 3 wwwwwwwwwwwwwwpwwwpwwwwe +58 4 wwwwwwwwwwpwwwwwwpwwwwpwwwpwwwe +58 5 wwwwwwwwwwwpwwwwpwwwe +58 6 wwwwwwwpwwwpwwwwwe +58 7 wwwwwwwwwwwpwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwpwwwwwe +58 8 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwpwwe +58 9 wwwwwwwwwwwwwwpwwwwwe +58 10 wwwwwwwwwwwwwpwwwwe +58 11 wwwwwwwwwwwwwpwwwwwwwwwwwwwpwwwwe +58 12 wwwwwwwwwwwpwwwwpwwwwwwwe +58 13 wwwwwwwpwwwwwwwwwwwwwpwwwwe +58 14 hwwwwwwwwwwwwwwwwwwwe +58 15 wwwwwpwwwwwe +58 16 wwwwwwwwwwe +58 17 wwwwwwwwwpwwwpwwwe +58 18 wwwwwwwwwpwwwwpwwwwe +58 19 wwwwwwpwwwpwwwwwwe +58 20 wwwwwwwwe +58 21 wwwwwpwwwwe +58 22 wwwwwwwwwwwwwwwwwwwwwpwwwwwwwwpwwwwwwwwpwwwwwpwwwpwwwwwwe +59 1 wwwwwwwwpwwwe +59 2 wwwwwwwwwwwwpwwwwpwwwwwwwwwwwwpwwwwpwwwwwwwwe +59 3 wwwwwwwwwpwwwwwe +59 4 wwwwwpwwwwwwwe +59 5 wwwwwwwwwwwwwe +59 6 wwwwwwwwwwwwwwwwwwwwpwwwwwe +59 7 wwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwpwwpwwwwe +59 8 wwwwwwwwwwwwwwwpwwwe +59 9 wwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwe +59 10 wwwwwwwwwwwwwwwwwwwwwwwe +59 11 hwwwwwwwwwwwwwwwwwwwwwwwwwwwwe +59 12 wwwwwwwwwwwwwwwwe +59 13 wwwwwwwpwwwwwe +59 14 wwwwwwwwwwwpwwwpwwwwpwwwwwe +59 15 wwwwwpwwwwwwe +59 16 wwwwwwwwwwwwwwwwwe +59 17 wwwwwwwpwwwe +59 18 wwwwwwwwwwpwwpwwwwwe +59 19 wwwwwwwpwwwe +59 20 wwwwwwpwwwwe +59 21 wwwwwwwwwwwwpwwwwwwe +59 22 wwwwwwwpwwwpwwwe +59 23 wwwwwwwwwwwwwwwpwwwwe +59 24 wwwwwpwwwpwwwwwwpwwwe +60 1 wwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwpwwwwwwwwwpwwwwwwwe +60 2 wwwwwwwwwwwwwe +60 3 wwwwwpwwwwpwwwwe +60 4 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwe +60 5 wwwwwwwwwpwwwwe +60 6 wwwwwwwwwwwwpwwwwwwwe +60 7 hwwwwwwwwwwpwwpwwwe +60 8 wwwwwwwwwwwwwwwwwpwwwwe +60 9 wwwwwwwwwwwwwwwwpwwwwwe +60 10 wwwwwwwwpwwwpwwwwwwwpwwwwwwwwpwwwpwwwwwwwwpwwwwwwwwwwpwwwpwwpwwwe +60 11 wwwwwwwwwwwwwwwpwwwwwwe +60 12 wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwpwwwwe +60 13 wwwwwwwwwwwwwwwwwwwe +61 1 wwwwwwwwpwwwe +61 2 wwwwwwwwe +61 3 wwwwwwwwwe +61 4 wwwwwwwwwwwe +61 5 wwwwwwwwwwwwwpwwwwwpwwwwwe +61 6 wwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwe +61 7 wwwwwwwwwwwpwwwwwe +61 8 wwwwwwwwwwwe +61 9 wwwwwwwwwwwwwwe +61 10 wwwwwwwwwwwe +61 11 wwwwwwwwwpwwwwwwe +61 12 wwwwwwwwwwwwwwpwwwe +61 13 wwpwwwwwpwwe +61 14 wwwwwwwwwwwwwwwwpwwwwwpwwwwwwwpwwwwwwwe +62 1 wwwwwwwwwwwwe +62 2 wwwwwwwwwwwwwwwwwwwwwe +62 3 wwwwwpwwwe +62 4 wwwwwwpwwwwe +62 5 wwwwwwwwwwwpwwwwwwwpwwwwwe +62 6 wwwwwwwwwwwwwwwwwe +62 7 wwwwwwpwwwe +62 8 wwwwwwwwpwwwwwwwwwwe +62 9 wwwwwwwwwwwwwwwpwwwwwwe +62 10 wwwwwwwwwwwwwwwe +62 11 wwwwwwwwwpwwwwwwwwwpwwwe +63 1 wwwwwwwwpwwwwwwwwwe +63 2 wwwwwwwpwwwwwe +63 3 wwwwwwwwwwwe +63 4 hwwwwpwwwwpwwwpwwwwpwwwpwwpwwe +63 5 wwwwwwwwwwwwwwe +63 6 wwwwwwwwwwwwpwwwwwwe +63 7 wwwwwwwwwwwwpwwwwwwwwe +63 8 wwwwwwwwwpwwwwwwwwe +63 9 wwwwwwwwwwwpwwwwwwe +63 10 wwwwwwwwwwwwwwwwwwwwwe +63 11 wwwwwwwpwwwwe +64 1 wwwwwwwwpwwwwpwwwwwe +64 2 wwwwwwwpwwwwe +64 3 wwwwwwwpwwe +64 4 wwwwwwwwwwpwwwwe +64 5 wwwwwwwwwwwwwe +64 6 wwwwwwwwwwwpwwpwwwe +64 7 wwwwwwpwwwwwwwwpwwwwe +64 8 wwwwwwpwwwwe +64 9 wwwwpwwwpwwwwwwwwwwwwwwwwwpwwwe +64 10 wwwwwwwwwpwwe +64 11 wwwwwwwpwwwwwpwwwwe +64 12 wwwwpwwwwwwwe +64 13 wwwwwpwwwwe +64 14 wwwwwwwwwwpwwwwwwwwe +64 15 wwwwpwwwwe +64 16 wwwwwwwwwpwwwwwwwe +64 17 wwwwwwwwwpwwwe +64 18 wwwwwe +65 1 wwwwwwwwwpwwwpwwwwwwwwwwwpwwwpwwwwwwwpwwwwwwwwe +65 2 wwwwwwwwwwwwwwwpwwwwwwwwwpwwwwwwe +65 3 wwwwwpwwwwwwpwwwwpwwwwwwe +65 4 wwwwwwwwwwwwwwpwwwwwwpwwwwwwwwe +65 5 wwwwwpwwwwwwwwwe +65 6 wwwwwwwwwwpwwwwwwwwwpwwwwwpwwwpwwwwwe +65 7 wwwwwpwwwwwwwwpwwwwwwwpwwwwwe +65 8 wwwwwwwwwwwwwwe +65 9 wwwwwwwe +65 10 wwwwwpwwwwwwpwwwwwe +65 11 wwwwwwwwwwwwwwwpwwwwwwwwwwwwwwpwwwwwe +65 12 wwwwwwwwwwwwwwwwwwwwwwwwwe +66 1 wwwwwwwwpwwwpwwwe +66 2 wwwwwwpwwpwwwe +66 3 wwwwwwwwwwwwwwwwwwpwwwwwwwpwwwwe +66 4 wwwwwwwpwwwwwwwwwwpwwwwe +66 5 wwwwwwwwwwwwwwwwwe +66 6 wwwwwwwwwwwwwwwwwwwwwwe +66 7 wwwwwwpwwwwwe +66 8 wwwwwwwwwwwwwwwwwwwwwwwwwwwwpwwwwwwwwwwwwpwwwwwe +66 9 wwwwwwwpwwpwwe +66 10 wwwwwwwwwpwwwwwwwwwwwwwwwwwwe +66 11 wwwwwwwwwwwwwwwwwwwwwwwwe +66 12 wwwwwwwwwwwwwwwwwe +67 1 wwwwwwwwwe +67 2 wwwwwwwwpwwwe +67 3 wwwwwpwwwwwwwpwwwwwwe +67 4 wwwwwwwwwwe +67 5 wwwwwwwwpwwwwe +67 6 wwwwwpwwe +67 7 wwwwwwwwe +67 8 wwwwpwwwwwwwwwe +67 9 wwwwwwwwwwwwwwwwwwe +67 10 wwwwwwwwwwwe +67 11 wwwwwe +67 12 wwwwwwwwwe +67 13 wwwwwpwwwwe +67 14 wwwwwwwe +67 15 wwwwwwwwwwwwpwwe +67 16 wwwwwwwwwwwe +67 17 wwwwwwwwwpwwwe +67 18 wwwwwwwwe +67 19 wwwwwwwpwwwwpwwwwe +67 20 wwwwwwwwwwpwwwwwe +67 21 wwwwwwwpwwwwwe +67 22 wwwwwwwwwwwwe +67 23 wwwwwwwwwpwwwe +67 24 wwwwwwwwe +67 25 wwwwwwwe +67 26 wwwwwwwwwe +67 27 wwwwwwwwwwwwwe +67 28 wwwwwwwwwwwwwwwe +67 29 wwwwwwwpwwwwwwe +67 30 wwwwwwwwwwe +68 1 wpwwwe +68 2 wwwwwe +68 3 wwwwwe +68 4 wwwwe +68 5 wwe +68 6 wwe +68 7 wwwwwwwwwwwe +68 8 wwwe +68 9 wwwwe +68 10 wwwwwe +68 11 wwwe +68 12 wwwwe +68 13 wwwwe +68 14 wwwwwe +68 15 wwwwwwwe +68 16 wwwe +68 17 wwwwwwwwwwe +68 18 wwe +68 19 wwwwwwwe +68 20 wwe +68 21 wwe +68 22 wwwwwwwe +68 23 wwwe +68 24 wwwwwwe +68 25 wwwwe +68 26 wwwwwe +68 27 wwwe +68 28 wwwwwwwe +68 29 wwwwwwe +68 30 wwwwwe +68 31 wwwwwe +68 32 wwwwwwwwwwe +68 33 wwpwwwpwwwe +68 34 wwwwwwe +68 35 wwwe +68 36 wwwwe +68 37 wwwwwe +68 38 wwwwwe +68 39 wwwwwwwwpwwwwe +68 40 wwwwe +68 41 wwwwwwwwe +68 42 wwwwwwwwwe +68 43 wwwwpwwwwwwwe +68 44 wwwwwpwwwwwe +68 45 wwpwwwe +68 46 wwwwwwwe +68 47 wwwwwe +68 48 wwwwwwwwwwwe +68 49 wwwwwwwwwwe +68 50 wwwwwe +68 51 wwwwwwwwwwwwe +68 52 wwwwwe +69 1 we +69 2 wwe +69 3 wwwwe +69 4 wwwwe +69 5 wwwwe +69 6 wwwwwwe +69 7 wwwwwwwwwwwwwwwe +69 8 wwwwwe +69 9 wwwwwwe +69 10 wwwwwwe +69 11 wwwwwwwe +69 12 wwwwwwe +69 13 wwwwwwe +69 14 wwwwwwe +69 15 wwwe +69 16 wwwwwe +69 17 wwwpwwwwwwe +69 18 wwwwwwe +69 19 wwwwwwwwwe +69 20 wwwwwe +69 21 wwwwe +69 22 wwwe +69 23 wwe +69 24 wwwwwwwwe +69 25 wwwwwwwwwwe +69 26 wwwwe +69 27 wwwe +69 28 wwwwpe +69 29 wwwe +69 30 wwe +69 31 wwwe +69 32 wwwwwwwe +69 33 wwwwwwe +69 34 wwwwwe +69 35 wwwwwe +69 36 wwwwwe +69 37 wwwwe +69 38 wwwwe +69 39 wwwe +69 40 wwwwe +69 41 wwwwpwwwe +69 42 wwwpwwwe +69 43 wwwwe +69 44 wwwwwe +69 45 wwwe +69 46 wwwwe +69 47 wwwwwwe +69 48 wwwe +69 49 wwwwwe +69 50 wwwwe +69 51 wwwe +69 52 wwwwe +70 1 wwwwe +70 2 wwwwe +70 3 wwwwe +70 4 wwwwwwwwwwwe +70 5 wwwe +70 6 wwwe +70 7 wwe +70 8 wwwwe +70 9 wwwe +70 10 wwwwe +70 11 wpwwwwwwwwe +70 12 wwe +70 13 wwwe +70 14 wwwwwwe +70 15 wpwwe +70 16 wwe +70 17 wwwwe +70 18 wwe +70 19 hwwwwe +70 20 wwwwe +70 21 wwwwe +70 22 wwe +70 23 wwwwwe +70 24 wwwwwe +70 25 wwe +70 26 wwwwe +70 27 wwwwwwe +70 28 wwwwwe +70 29 wwwwe +70 30 wwwwwwwwwwe +70 31 wwwwwwwe +70 32 wwwwwe +70 33 wwwwe +70 34 wwwwwe +70 35 wwwwe +70 36 wwwwwe +70 37 wwwwwe +70 38 wwwwwwwwe +70 39 wpwwwwe +70 40 wwwwwwwe +70 41 wwwwwwwwe +70 42 wwwwwwwwe +70 43 wwwwwwwwwe +70 44 wwwwpwwwwwe +71 1 wwwwwwwwwwwwwwe +71 2 wwwwwwe +71 3 wwwwwe +71 4 wwwwwwwwpwwwwwwwpwwwe +71 5 wwwwwwwe +71 6 wwwwwe +71 7 wwwwwwwwwwwwwwe +71 8 wwwwe +71 9 wwwwwwwe +71 10 wwwwwwe +71 11 wwwwe +71 12 wwwwwwwwwe +71 13 wwwwwwe +71 14 wwwe +71 15 wwwwwwwwe +71 16 wwwwwwwe +71 17 wwwwwe +71 18 wwwwwe +71 19 wwwwwe +71 20 wwwwe +71 21 wwwwwwwwwwwwwe +71 22 wwwe +71 23 wwwwwwwwwwwwwe +71 24 wwwpwwwwwe +71 25 wwwwwwwwwwwwe +71 26 wwwwwwwwwwe +71 27 wwwwwwwwwwe +71 28 wwwwwwwwwwwwwwwe +72 1 wwwwwwwwwwwwwe +72 2 wwwwwpwwwwe +72 3 wwwwwwwwwe +72 4 wwwwwwwe +72 5 wwwwwwwwwwe +72 6 wwwwwwwwwwwe +72 7 wwwwwwwwwe +72 8 wwwwwwwwe +72 9 wwwwwwpwwwwwwwe +72 10 wwwwwwwwwwwwwe +72 11 wwwwwwpwwwe +72 12 wwwwwwwwwwwe +72 13 wwwwwwpwwwwwwwwe +72 14 wwwwwpwwwwwe +72 15 wwwwwe +72 16 wwwwwwwe +72 17 wwpwwwwwwwwe +72 18 wwwwwwwwe +72 19 wwwwwwwwwwe +72 20 wwwwwwwwe +72 21 wwwwwwwwe +72 22 wwwwwwwwwwwwe +72 23 wwwwwpwwwwwwwwwwwe +72 24 wwwwwwwwwwwe +72 25 wwwwwwwwwwwe +72 26 wwwwwwwe +72 27 wwwwwwwwwwwwwe +72 28 wwwwwwwwwwwwwe +73 1 wwe +73 2 wwwwe +73 3 wwwwwe +73 4 wwwwwwe +73 5 wwwwwe +73 6 wwwwwwwwe +73 7 wwwwwwe +73 8 wwwwwwe +73 9 wwwwwwwwwe +73 10 wwwwwwwe +73 11 wwwwwwe +73 12 wwwwe +73 13 wwwwwe +73 14 wwwwwwwwe +73 15 wwwwwwwwwwwe +73 16 wwwwwwe +73 17 wwwwwwwwe +73 18 wwwpwwwe +73 19 wwwpwwwwwwe +73 20 hwwwwwwwwwwwwwwwpwwwwpwwwwwwpwwwwwpwwwwwpwwwwwwwwpwwwwwpwwwwpwwwwwwwwpwwwwwwwwwwwwpwwpwwwwe +74 1 wwe +74 2 wwe +74 3 wwe +74 4 wwe +74 5 wwe +74 6 wwwe +74 7 wwe +74 8 wwwwe +74 9 wwwwe +74 10 wwwwe +74 11 wwwwe +74 12 wwwwe +74 13 wwe +74 14 wwwe +74 15 wwwwe +74 16 wpwwwwe +74 17 wwe +74 18 wwwe +74 19 wwwe +74 20 wwwwe +74 21 wwe +74 22 wwwe +74 23 wwwe +74 24 wwwwwwe +74 25 wwwwwe +74 26 wwe +74 27 wwwwe +74 28 wwwwe +74 29 wwe +74 30 wwwe +74 31 wwwwwwpwwwwwwwwwwwwwwwpwwwwwwpwwwwwwwwwwwpwwwwwwwwpwwwwwwpwwwwwe +74 32 wwe +74 33 wwwe +74 34 wwwe +74 35 wwwe +74 36 wwe +74 37 wwwwwwwe +74 38 wwwwwe +74 39 wwwe +74 40 wwwe +74 41 wwe +74 42 wwwwe +74 43 wwwwwe +74 44 wwwwe +74 45 wwwwe +74 46 wwwwe +74 47 wwwe +74 48 wwwwe +74 49 wwwwwe +74 50 wwwe +74 51 wwwe +74 52 wwwwwwwwwe +74 53 wpwwwwe +74 54 wwwe +74 55 wwwe +74 56 wwwwwwpwwwwwe +75 1 wwwwe +75 2 wwwwe +75 3 wwwwwe +75 4 wwwwwwe +75 5 wwwwwe +75 6 wwwwe +75 7 wwwe +75 8 wwe +75 9 wwwe +75 10 wwwwwe +75 11 wwwe +75 12 wwwwe +75 13 wwwwwwe +75 14 wwwwwe +75 15 wwwe +75 16 wwwwwwe +75 17 wwwwe +75 18 wwwwe +75 19 wwwwe +75 20 wwwwe +75 21 wwe +75 22 wwwe +75 23 wwwe +75 24 wwwe +75 25 wwwwwe +75 26 wwwwe +75 27 wwpwe +75 28 wwwe +75 29 wwwe +75 30 wwwwe +75 31 wwwwe +75 32 wwwe +75 33 wwwwwe +75 34 wwwe +75 35 wwwwe +75 36 wwwwwe +75 37 wwwwwwe +75 38 wwwwwe +75 39 wwwwwe +75 40 wwwwwwwe +76 1 wwwwwwwwwwwe +76 2 wwwwwwwwwwe +76 3 wwwwwwwe +76 4 wwwwwwe +76 5 wwwwwwwwe +76 6 wwwwwwwe +76 7 wwwwwwwe +76 8 wwwwwwwe +76 9 wwwwwwwwwwe +76 10 wwwwwwwe +76 11 wwwwwwwwe +76 12 wwwwwe +76 13 wwwwpwwwwwwe +76 14 wwwwwwe +76 15 wwwwwwwwe +76 16 wwwwwe +76 17 wwwwwwe +76 18 wwwwe +76 19 hwwwwwwwwwe +76 20 wwwwwwwe +76 21 wwwwwpwwwwwwwwe +76 22 wwwwwwwwe +76 23 wwwwwwe +76 24 wwwwwwwwwe +76 25 wwwwwe +76 26 wwwwwwwe +76 27 wwwwwwwwe +76 28 wwwwpwwwwwe +76 29 wwwpwwwwwwe +76 30 wwwwwwpwwwwwe +76 31 wwwwwpwwwwwe +77 1 wwe +77 2 wwe +77 3 wwe +77 4 wwe +77 5 wwe +77 6 wwwe +77 7 wwwe +77 8 wwwe +77 9 wwwe +77 10 wwwe +77 11 wwwe +77 12 wwwe +77 13 wwe +77 14 wwwwwe +77 15 wwwe +77 16 wwwe +77 17 wwwe +77 18 wwwe +77 19 wwwe +77 20 wwwwwe +77 21 wwwwe +77 22 wwwe +77 23 wwwe +77 24 wwwe +77 25 wwwwe +77 26 wwe +77 27 wwwwwwwe +77 28 wwwe +77 29 wwwwwwe +77 30 wwwwwwe +77 31 wwwwwwe +77 32 wwwwe +77 33 wwwe +77 34 wwwe +77 35 wwwwe +77 36 wwwwe +77 37 wwwe +77 38 wwwpwwe +77 39 wwwwwe +77 40 wwwe +77 41 wwwwwe +77 42 wwwe +77 43 wwwwwwe +77 44 wwwwe +77 45 wwwe +77 46 wwwwwe +77 47 wwwe +77 48 wwwwwwe +77 49 wwwe +77 50 wwwwe +78 1 wwe +78 2 wwwe +78 3 wwwwe +78 4 wwe +78 5 wwwe +78 6 wwwwe +78 7 wwe +78 8 wwe +78 9 wwwe +78 10 wwwe +78 11 wwwe +78 12 wwwwe +78 13 wwwe +78 14 wwwwwe +78 15 wwwwe +78 16 wwe +78 17 wwwwwe +78 18 wwwwwwe +78 19 wwwwe +78 20 wwwwe +78 21 wwwwe +78 22 wwe +78 23 wwwe +78 24 wwwwwwe +78 25 wwwe +78 26 wwe +78 27 wwwwwe +78 28 wwwe +78 29 wwwwe +78 30 wwwwwe +78 31 wwwe +78 32 wwe +78 33 wwe +78 34 wwe +78 35 wwwwwwe +78 36 wwwwwe +78 37 wwwwwwpwwwwe +78 38 wwwwwpwwwwwwwwwe +78 39 wwwpwwwwwwe +78 40 wwwwwwwwwwwwwwwe +79 1 wwe +79 2 wwe +79 3 wwe +79 4 wwe +79 5 wwe +79 6 wwwe +79 7 wwe +79 8 wwwe +79 9 wwe +79 10 wwwwwe +79 11 wwwwe +79 12 wwwwwe +79 13 wwwwe +79 14 wwwe +79 15 wwwwe +79 16 wwwwwwe +79 17 wwwwwe +79 18 wwwwwwe +79 19 wwwwe +79 20 wwwe +79 21 wwe +79 22 wwwe +79 23 wwe +79 24 wwwwe +79 25 wwwwwe +79 26 wwwwwwe +79 27 wwwwwpwe +79 28 wwwe +79 29 wwwwe +79 30 wwwwe +79 31 wwwwe +79 32 wwe +79 33 wwwe +79 34 wwwwe +79 35 wwwwwe +79 36 wwwwe +79 37 wwwe +79 38 wwwe +79 39 wwwwe +79 40 wwwwwwwwwe +79 41 wwwwe +79 42 wwwwwe +79 43 wwwwe +79 44 wwwe +79 45 wwwwwe +79 46 wwwwwwwwwe +80 1 wwe +80 2 wwwe +80 3 wwwwe +80 4 wwwwe +80 5 wwwe +80 6 wwwe +80 7 wwwwe +80 8 wwwwe +80 9 wwe +80 10 wwwe +80 11 wwwe +80 12 wwwe +80 13 wwwe +80 14 wwe +80 15 wwe +80 16 wwe +80 17 wwwwe +80 18 wwwwe +80 19 wwwwe +80 20 wwwe +80 21 wwwe +80 22 wwwwe +80 23 wwwwwe +80 24 wwwwe +80 25 wwwwe +80 26 wwwwe +80 27 wwwe +80 28 wwe +80 29 wwe +80 30 wwe +80 31 wwe +80 32 wwwe +80 33 wwwe +80 34 wwwwwe +80 35 wwe +80 36 wwe +80 37 wwwwwwe +80 38 wwwe +80 39 wwe +80 40 wwwwe +80 41 wwe +80 42 wwwwe +81 1 wwwe +81 2 wwwe +81 3 wwwe +81 4 wwwe +81 5 wwwe +81 6 wwwe +81 7 wwwe +81 8 wwwe +81 9 wwwe +81 10 wwwe +81 11 wwwe +81 12 wwwe +81 13 wwwe +81 14 wwwwe +81 15 wwwe +81 16 wwe +81 17 wwwe +81 18 wwwe +81 19 wwwwe +81 20 wwwwwwe +81 21 wwwe +81 22 wwwe +81 23 wwwwe +81 24 wwwwwe +81 25 wwwwwe +81 26 wwe +81 27 wwwwwe +81 28 wwwwwe +81 29 wwwwwwwwe +82 1 wwwe +82 2 wwwe +82 3 wwwe +82 4 wwwe +82 5 wwwwwe +82 6 wwwwwwe +82 7 wwwwe +82 8 wwwwwwe +82 9 wwwwe +82 10 wwwe +82 11 wwe +82 12 wwwe +82 13 wwwwe +82 14 wwwwe +82 15 wwwe +82 16 wwwwe +82 17 wwwwwe +82 18 wwwwwwe +82 19 wwwwwwpwwwe +83 1 wwe +83 2 wwwwwwe +83 3 wwwwwe +83 4 wwwwwe +83 5 wwe +83 6 wwwwwe +83 7 wwwwwwe +83 8 wwwwe +83 9 wwe +83 10 wwwe +83 11 wwwwe +83 12 wwwwwwwe +83 13 wwwwwwwe +83 14 wpwpwwwwwwe +83 15 wwwwwwe +83 16 wwwwe +83 17 wwwwwwwe +83 18 wwwwwwe +83 19 wwwwe +83 20 wwe +83 21 wwe +83 22 wwwwe +83 23 wwwe +83 24 wwwwwe +83 25 wwwwe +83 26 wwpwwwwe +83 27 wwwe +83 28 wwwwe +83 29 wwwwwwwwe +83 30 wwwwe +83 31 wwwwwwe +83 32 wwwwwwe +83 33 wwwwe +83 34 wwwwwwe +83 35 wwwe +83 36 wwwwwwe +84 1 wwwe +84 2 wwwe +84 3 wwwe +84 4 wwwwe +84 5 wwwe +84 6 wwwwwwwwe +84 7 wwwwwe +84 8 wwwwe +84 9 wwwwe +84 10 wwwwwwe +84 11 wwwe +84 12 wwe +84 13 wwwwwe +84 14 wwwwwe +84 15 wwwwwwe +84 16 wwwe +84 17 wwwe +84 18 wwwe +84 19 wwwwe +84 20 wwwwe +84 21 wwwwwwse +84 22 wwwwe +84 23 wwwwe +84 24 wwwe +84 25 wwwwwwwwwe +85 1 wwwe +85 2 wwe +85 3 wwe +85 4 wwwe +85 5 wwwe +85 6 wwwwe +85 7 wwwwwwe +85 8 wwwwwwwwwe +85 9 wwwwwpwwwwwe +85 10 wwwwwwwwwwwwwwe +85 11 wwwwwwwwwwwpwwwe +85 12 wwwwe +85 13 wwwwe +85 14 wwwe +85 15 wwwe +85 16 wwwe +85 17 wwwwe +85 18 wwe +85 19 wwwwwe +85 20 wwwwe +85 21 wwwwe +85 22 wwwe +86 1 wwe +86 2 wwwwe +86 3 wwe +86 4 wwwwwwe +86 5 wwwwe +86 6 wwwwe +86 7 wwwwwe +86 8 wwwwe +86 9 wwwe +86 10 wwwwwwe +86 11 wwwe +86 12 wwwe +86 13 wwwe +86 14 wwwe +86 15 wwwe +86 16 wwe +86 17 wwwwe +87 1 wwwwe +87 2 wwwe +87 3 wwwe +87 4 wwwe +87 5 wwwe +87 6 wwwe +87 7 wwwwpwwwwwe +87 8 wwe +87 9 wwwwe +87 10 wwwe +87 11 wwe +87 12 wwwwe +87 13 wwwwwwe +87 14 wwwwe +87 15 wwwwe +87 16 wwwwe +87 17 wwwe +87 18 wwwwwe +87 19 wwwe +88 1 wwwwe +88 2 wwwe +88 3 wwe +88 4 wwwe +88 5 wwwwe +88 6 wwwwwwe +88 7 wwwwwwe +88 8 wwwe +88 9 wwe +88 10 wwwe +88 11 wwwwe +88 12 wwwe +88 13 wwwe +88 14 wwe +88 15 wwe +88 16 wwe +88 17 wwwwwwe +88 18 wwwwe +88 19 wwwwe +88 20 wwwwe +88 21 wwwwe +88 22 wwwe +88 23 wwwwe +88 24 wwwwe +88 25 wwwe +88 26 wwwwe +89 1 we +89 2 wwe +89 3 wwe +89 4 wwwe +89 5 wwwwwwe +89 6 wwwwwwe +89 7 wwwe +89 8 wwwwwwe +89 9 wwwwwe +89 10 wwwe +89 11 wwwwe +89 12 wwwe +89 13 wwwwwe +89 14 wwwe +89 15 wwwwwwwwwwwe +89 16 wwwwwwwwwwe +89 17 wpwwwwe +89 18 wwwwwe +89 19 wwwwe +89 20 wwwwe +89 21 wwwwwwe +89 22 wwwwwe +89 23 wwwpwwwwwwe +89 24 wwwwe +89 25 wwwwwe +89 26 wwwwe +89 27 wwwe +89 28 wwwwwe +89 29 wwwe +89 30 wwe +90 1 wwwwe +90 2 wwwwe +90 3 wwwe +90 4 wwwwwe +90 5 wwwwwwe +90 6 wwwwe +90 7 wwwwwe +90 8 wwwwe +90 9 wwe +90 10 wwe +90 11 wwwe +90 12 wwwwe +90 13 wwe +90 14 wwwwwwe +90 15 wwwe +90 16 wwwwe +90 17 wwwwwwwwwe +90 18 wwwe +90 19 wwwwwwe +90 20 wwwe +91 1 wwe +91 2 wwwe +91 3 wwwe +91 4 wwwe +91 5 wwwe +91 6 wwwe +91 7 wwwe +91 8 wwwe +91 9 wwwwe +91 10 wwwwe +91 11 wwwe +91 12 wwwe +91 13 wwwwwwwe +91 14 wwwwwwwe +91 15 wwwe +92 1 wwwe +92 2 wwwe +92 3 wwwwe +92 4 wwwe +92 5 wwwwe +92 6 wwe +92 7 wwe +92 8 wwwwe +92 9 wwe +92 10 wwe +92 11 wwwwwwe +92 12 wwwe +92 13 wwwwe +92 14 wwwe +92 15 wwwwe +92 16 wwwe +92 17 wwe +92 18 wwwwe +92 19 wwwwwwe +92 20 wwwwwe +92 21 wwe +93 1 we +93 2 wwwe +93 3 wwwwwe +93 4 wwwwwe +93 5 wwwwe +93 6 wwwwe +93 7 wwwe +93 8 wwwe +93 9 wwwwe +93 10 wwwwe +93 11 wwwwe +94 1 wwwwe +94 2 wwwe +94 3 wwwe +94 4 wwwe +94 5 wwwwe +94 6 wwwwe +94 7 wwwe +94 8 wwwe +95 1 wwe +95 2 wwe +95 3 wwwe +95 4 wwwwwwe +95 5 wwwwe +95 6 wwwwwwwwwe +95 7 wwwwe +95 8 wwwwe +96 1 wwwwwe +96 2 wwwwe +96 3 wwwe +96 4 wwwe +96 5 wwwwwe +96 6 wwwwe +96 7 wwwe +96 8 wwwwe +96 9 wwwe +96 10 wwwe +96 11 wwwwwe +96 12 wwwe +96 13 wwwwe +96 14 wwwwwe +96 15 wwwwwwe +96 16 wwwe +96 17 wwe +96 18 wwe +96 19 wwwwwse +97 1 wwwwwe +97 2 wwwwwe +97 3 wwwwwwe +97 4 wwwwwwwwwe +97 5 wwwwwe +98 1 wwwwwwwwwwwwe +98 2 wwwwwwe +98 3 wwwe +98 4 wwwwwwwwwwwe +98 5 wwwwwwwwwwwwwpwwwe +98 6 wwwwwwwwwwwwpwwwwe +98 7 wwwwwwwwwe +98 8 wwwwwwwwwwwwpwwwwwpwwwwe +99 1 wwwwe +99 2 wwwe +99 3 wwwwe +99 4 wwwe +99 5 wwwwe +99 6 wwwwwwe +99 7 wwwwwwe +99 8 wwwwwwe +100 1 wwe +100 2 wwe +100 3 wwe +100 4 wwwe +100 5 wwwe +100 6 wwwwe +100 7 wwwwe +100 8 wwwwe +100 9 hwwwwwwwe +100 10 wwwwe +100 11 wwwwwe +101 1 we +101 2 wwe +101 3 wwwwe +101 4 wwwwwe +101 5 wwwwe +101 6 wwwwe +101 7 wwwwe +101 8 wwwwe +101 9 wwe +101 10 wwwwe +101 11 wwe +102 1 wwe +102 2 wwwe +102 3 wwwe +102 4 wwwwe +102 5 wwwwwe +102 6 wwe +102 7 wwwwe +102 8 wwwwwe +103 1 we +103 2 wwwwe +103 3 wwwwwwwwwe +104 1 wwwwe +104 2 wwwwe +104 3 wwwwe +104 4 wpwwwe +104 5 wwwwe +104 6 wwwe +104 7 wwwwe +104 8 wwwe +104 9 wwwe +105 1 wwwwwwwe +105 2 wwwwwe +105 3 wwwwe +105 4 wwwwe +105 5 wwwe +106 1 wwe +106 2 wwwwe +106 3 wwwwe +106 4 wwwwwwwe +107 1 wwwwe +107 2 wwwwe +107 3 wwwwwe +107 4 wwe +107 5 wwwwwe +107 6 wwwe +107 7 wwe +108 1 wwwe +108 2 wwwe +108 3 wwwwe +109 1 wwwe +109 2 wwwwe +109 3 wwwwwe +109 4 wwwwwe +109 5 wwwwwe +109 6 wwwwe +110 1 wwwwwe +110 2 wwwwwwwe +110 3 wwwwpwwwe +111 1 wwwwwe +111 2 wwwwwwe +111 3 wwwwe +111 4 wwwe +111 5 wwwwwe +112 1 wwwwe +112 2 wwe +112 3 wwwwe +112 4 wwwwwe +113 1 wwwwe +113 2 wwwwe +113 3 wwwwwe +113 4 wwwwwe +113 5 wwwwwe +114 1 wwwwe +114 2 wwe +114 3 wwe +114 4 wwwwe +114 5 wwwwwe +114 6 wwwe diff --git a/feature/memorize/src/main/assets/memorize/lexicon_v1.db b/feature/memorize/src/main/assets/memorize/lexicon_v1.db new file mode 100644 index 0000000000..9b50842eeb Binary files /dev/null and b/feature/memorize/src/main/assets/memorize/lexicon_v1.db differ diff --git a/feature/memorize/src/main/assets/memorize/timings/husary_muallim_wbw_v1.db b/feature/memorize/src/main/assets/memorize/timings/husary_muallim_wbw_v1.db new file mode 100644 index 0000000000..30e86136cf Binary files /dev/null and b/feature/memorize/src/main/assets/memorize/timings/husary_muallim_wbw_v1.db differ diff --git a/feature/memorize/src/main/assets/memorize/timings/husary_mujawwad_wbw_v1.db b/feature/memorize/src/main/assets/memorize/timings/husary_mujawwad_wbw_v1.db new file mode 100644 index 0000000000..4b0eb2befc Binary files /dev/null and b/feature/memorize/src/main/assets/memorize/timings/husary_mujawwad_wbw_v1.db differ diff --git a/feature/memorize/src/main/assets/memorize/timings/husary_murattal_wbw_v1.db b/feature/memorize/src/main/assets/memorize/timings/husary_murattal_wbw_v1.db new file mode 100644 index 0000000000..6f8fdb9074 Binary files /dev/null and b/feature/memorize/src/main/assets/memorize/timings/husary_murattal_wbw_v1.db differ diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/audio/CallState.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/audio/CallState.kt new file mode 100644 index 0000000000..45c14daad0 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/audio/CallState.kt @@ -0,0 +1,22 @@ +package com.quran.mobile.feature.memorize.audio + +import android.content.Context +import android.media.AudioManager + +/** Whether the phone is ringing or in a call (phone or VoIP); replaced by a fake in tests. */ +fun interface CallState { + fun isInCall(): Boolean +} + +/** + * Reads the audio mode. During a call the microphone hears nothing (or the call), so silence isn't + * the user being stuck, and a hint must not be played over the call. + */ +class AudioModeCallState(context: Context) : CallState { + private val audioManager = context.getSystemService(AudioManager::class.java) + + override fun isInCall(): Boolean = when (audioManager?.mode) { + AudioManager.MODE_RINGTONE, AudioManager.MODE_IN_CALL, AudioManager.MODE_IN_COMMUNICATION -> true + else -> false + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/audio/MicAudioSource.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/audio/MicAudioSource.kt new file mode 100644 index 0000000000..6a7a4b7bc5 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/audio/MicAudioSource.kt @@ -0,0 +1,122 @@ +package com.quran.mobile.feature.memorize.audio + +import android.annotation.SuppressLint +import android.media.AudioFormat +import android.media.AudioRecord +import android.media.MediaRecorder +import android.os.Process +import kotlin.math.max +import kotlin.math.sqrt + +/** Something that delivers 16 kHz mono audio frames (the microphone, or a fake in tests). */ +interface AudioSource { + fun start() + fun stop() +} + +fun interface AudioSourceFactory { + fun create( + onFrame: (samples: FloatArray, count: Int, speech: Boolean) -> Unit, + onError: (Throwable) -> Unit, + ): AudioSource +} + +/** + * Captures 16 kHz mono audio from the microphone in 100 ms frames on a dedicated thread. Audio + * only ever lives in memory: frames are handed to [onFrame] and then dropped. + * + * VOICE_RECOGNITION is used because it disables the device's noise suppression and automatic gain + * control by default, which keeps the signal closest to what the speech model was trained on. + */ +class MicAudioSource( + private val onFrame: (samples: FloatArray, count: Int, speech: Boolean) -> Unit, + private val onError: (Throwable) -> Unit, +) : AudioSource { + @Volatile private var running = false + private var thread: Thread? = null + + /** Requires the RECORD_AUDIO permission. */ + @SuppressLint("MissingPermission") + override fun start() { + if (running) return + running = true + thread = Thread({ capture() }, "memorize-mic").apply { start() } + } + + override fun stop() { + running = false + thread?.join(500) + thread = null + } + + @SuppressLint("MissingPermission") + private fun capture() { + Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO) + val minBuffer = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL, ENCODING) + val record = try { + AudioRecord( + MediaRecorder.AudioSource.VOICE_RECOGNITION, SAMPLE_RATE, CHANNEL, ENCODING, + max(minBuffer, FRAME_SAMPLES * 4 * Float.SIZE_BYTES) + ) + } catch (e: Exception) { + running = false + onError(e) + return + } + if (record.state != AudioRecord.STATE_INITIALIZED) { + record.release() + running = false + onError(IllegalStateException("microphone unavailable")) + return + } + + val vad = EnergyVoiceActivity() + val frame = FloatArray(FRAME_SAMPLES) + try { + record.startRecording() + while (running) { + var filled = 0 + while (filled < FRAME_SAMPLES && running) { + val read = record.read(frame, filled, FRAME_SAMPLES - filled, AudioRecord.READ_BLOCKING) + if (read < 0) throw IllegalStateException("microphone read failed: $read") + filled += read + } + if (filled > 0) onFrame(frame, filled, vad.isSpeech(frame, filled)) + } + } catch (e: Exception) { + onError(e) + } finally { + running = false + runCatching { record.stop() } + record.release() + } + } + + companion object { + const val SAMPLE_RATE = 16_000 + const val FRAME_SAMPLES = SAMPLE_RATE / 10 + private const val CHANNEL = AudioFormat.CHANNEL_IN_MONO + private const val ENCODING = AudioFormat.ENCODING_PCM_FLOAT + } +} + +/** + * A simple energy based voice activity detector with an adaptive noise floor. It only needs to + * tell "the reciter is making sound" (including long madd) from silence. + */ +internal class EnergyVoiceActivity { + private var noiseFloor = 0.003f + private var speech = false + + fun isSpeech(samples: FloatArray, count: Int): Boolean { + var sum = 0.0 + for (i in 0 until count) sum += samples[i] * samples[i] + val rms = sqrt(sum / max(count, 1)).toFloat() + // the floor follows quiet frames quickly and loud frames very slowly + noiseFloor = if (rms < noiseFloor) 0.9f * noiseFloor + 0.1f * rms else 0.999f * noiseFloor + 0.001f * rms + val on = max(noiseFloor * 4f, 0.006f) + val off = max(noiseFloor * 2.5f, 0.004f) + speech = if (speech) rms > off else rms > on + return speech + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/CheckGraph.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/CheckGraph.kt new file mode 100644 index 0000000000..47e8c3da1d --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/CheckGraph.kt @@ -0,0 +1,267 @@ +package com.quran.mobile.feature.memorize.check + +import com.quran.mobile.feature.memorize.model.ModelConverter +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.io.RandomAccessFile + +/** + * Prepares the double-check model for sherpa-onnx, on the phone, from the file as published. + * + * sherpa-onnx runs raw-audio CTC models ("omnilingual ASR") with a single input, scaled to unit + * variance. The Tilawi model takes the audio and its length, at the level it was trained on. So + * the graph input `audio_signal` is renamed `audio_raw`, and three nodes are put in front of the + * model: `audio_signal = 0.1 * audio_raw` and `length = [samples]` (a batch of one). Nothing else + * changes. + * + * This edits the ONNX protobuf directly, without parsing the weights. They are copied through as + * they are, so the 88 MB file never has to be in memory. The output is deterministic, and the store + * checks its SHA-256 (see bench/tilawi_rename.py in the lab for the same conversion with onnx). + */ +internal object CheckGraph : ModelConverter { + + override fun convert(source: File, target: File) { + RandomAccessFile(source, "r").use { input -> + val top = fields(input, 0, input.length()) + val graph = top.singleOrNull { it.number == MODEL_GRAPH && it.wire == LENGTH_DELIMITED } + ?: throw IOException("not an ONNX model") + val parts = ArrayList() + parts += Part.Bytes(frontNodes()) + var renamed = false + for (field in fields(input, graph.contentStart, graph.end)) { + if (field.number == GRAPH_INPUT && field.wire == LENGTH_DELIMITED) { + val info = input.bytes(field.contentStart, field.end) + when (name(info)) { + LENGTH -> continue + AUDIO -> { + parts += Part.Bytes(message(GRAPH_INPUT, renamed(info))) + renamed = true + continue + } + } + } + parts += Part.Range(field.start, field.end) + } + if (!renamed) throw IOException("no $AUDIO input") + val graphSize = parts.sumOf { it.size } + FileOutputStream(target).use { stream -> + val out = stream.channel + for (field in top) { + if (field === graph) { + stream.write(key(MODEL_GRAPH, LENGTH_DELIMITED) + varint(graphSize)) + for (part in parts) { + when (part) { + is Part.Bytes -> stream.write(part.bytes) + is Part.Range -> input.channel.copy(part.start, part.end, out) + } + } + } else { + input.channel.copy(field.start, field.end, out) + } + } + } + } + } + + private sealed interface Part { + val size: Long + + class Bytes(val bytes: ByteArray) : Part { + override val size: Long get() = bytes.size.toLong() + } + + class Range(val start: Long, val end: Long) : Part { + override val size: Long get() = end - start + } + } + + private class Field(val number: Int, val wire: Int, val start: Long, val contentStart: Long, val end: Long) + + /** The fields of the message in [start, end) of [input]: where each starts and ends. */ + private fun fields(input: RandomAccessFile, start: Long, end: Long): List { + val result = ArrayList() + var at = start + while (at < end) { + input.seek(at) + val key = input.varint() + val number = (key ushr 3).toInt() + val wire = (key and 7).toInt() + val contentStart: Long + val fieldEnd: Long + when (wire) { + VARINT -> { + contentStart = input.filePointer + input.varint() + fieldEnd = input.filePointer + } + FIXED64 -> { + contentStart = input.filePointer + fieldEnd = contentStart + 8 + } + LENGTH_DELIMITED -> { + val length = input.varint() + contentStart = input.filePointer + fieldEnd = contentStart + length + } + FIXED32 -> { + contentStart = input.filePointer + fieldEnd = contentStart + 4 + } + else -> throw IOException("unexpected wire type $wire at $at") + } + if (fieldEnd > end) throw IOException("truncated field at $at") + result += Field(number, wire, at, contentStart, fieldEnd) + at = fieldEnd + } + return result + } + + /** The name of a ValueInfoProto. */ + private fun name(info: ByteArray): String? { + var at = 0 + while (at < info.size) { + val (key, afterKey) = varint(info, at) + val wire = (key and 7).toInt() + if (wire != LENGTH_DELIMITED) return null + val (length, content) = varint(info, afterKey) + if ((key ushr 3).toInt() == VALUE_INFO_NAME) return String(info, content, length.toInt(), Charsets.UTF_8) + at = content + length.toInt() + } + return null + } + + /** The ValueInfoProto of the audio input, renamed. */ + private fun renamed(info: ByteArray): ByteArray { + val out = ByteArrayOutputStream() + out.write(string(VALUE_INFO_NAME, AUDIO_RAW)) + var at = 0 + while (at < info.size) { + val (key, afterKey) = varint(info, at) + val (length, content) = varint(info, afterKey) + val end = content + length.toInt() + if ((key ushr 3).toInt() != VALUE_INFO_NAME) out.write(info, at, end - at) + at = end + } + return out.toByteArray() + } + + private fun frontNodes(): ByteArray { + val scale = ByteArrayOutputStream().apply { + write(string(NODE_OUTPUT, SCALE)) + write(string(NODE_NAME, SCALE)) + write(string(NODE_OP_TYPE, "Constant")) + val tensor = ByteArrayOutputStream().apply { + write(key(TENSOR_DATA_TYPE, VARINT) + varint(TENSOR_FLOAT)) + write(string(TENSOR_NAME, SCALE)) + val bits = java.lang.Float.floatToIntBits(AUDIO_SCALE) + write(message(TENSOR_RAW_DATA, ByteArray(4) { (bits ushr (8 * it)).toByte() })) + }.toByteArray() + write( + message( + NODE_ATTRIBUTE, + string(ATTRIBUTE_NAME, "value") + message(ATTRIBUTE_TENSOR, tensor) + + key(ATTRIBUTE_TYPE, VARINT) + varint(ATTRIBUTE_TYPE_TENSOR), + ), + ) + }.toByteArray() + val mul = string(NODE_INPUT, AUDIO_RAW) + string(NODE_INPUT, SCALE) + string(NODE_OUTPUT, AUDIO) + + string(NODE_NAME, "audio_scaled") + string(NODE_OP_TYPE, "Mul") + val shape = string(NODE_INPUT, AUDIO_RAW) + string(NODE_OUTPUT, LENGTH) + string(NODE_NAME, "audio_length") + + string(NODE_OP_TYPE, "Shape") + + message( + NODE_ATTRIBUTE, + string(ATTRIBUTE_NAME, "start") + key(ATTRIBUTE_INT, VARINT) + varint(1) + + key(ATTRIBUTE_TYPE, VARINT) + varint(ATTRIBUTE_TYPE_INT), + ) + return message(GRAPH_NODE, scale) + message(GRAPH_NODE, mul) + message(GRAPH_NODE, shape) + } + + private fun key(number: Int, wire: Int): ByteArray = varint(((number shl 3) or wire).toLong()) + + private fun message(number: Int, content: ByteArray): ByteArray = + key(number, LENGTH_DELIMITED) + varint(content.size.toLong()) + content + + private fun string(number: Int, value: String): ByteArray = message(number, value.toByteArray(Charsets.UTF_8)) + + private fun varint(value: Long): ByteArray { + val out = ByteArrayOutputStream() + var v = value + while (true) { + if (v and 0x7FL.inv() == 0L) { + out.write(v.toInt()) + return out.toByteArray() + } + out.write(((v and 0x7F) or 0x80).toInt()) + v = v ushr 7 + } + } + + private fun varint(bytes: ByteArray, start: Int): Pair { + var result = 0L + var shift = 0 + var at = start + while (true) { + if (at >= bytes.size || shift > 63) throw IOException("bad varint") + val b = bytes[at++].toInt() and 0xFF + result = result or ((b and 0x7F).toLong() shl shift) + if (b and 0x80 == 0) return result to at + shift += 7 + } + } + + private fun RandomAccessFile.varint(): Long { + var result = 0L + var shift = 0 + while (true) { + val b = read() + if (b < 0 || shift > 63) throw IOException("bad varint") + result = result or ((b and 0x7F).toLong() shl shift) + if (b and 0x80 == 0) return result + shift += 7 + } + } + + private fun RandomAccessFile.bytes(start: Long, end: Long): ByteArray { + seek(start) + return ByteArray((end - start).toInt()).also { readFully(it) } + } + + private fun java.nio.channels.FileChannel.copy(start: Long, end: Long, out: java.nio.channels.FileChannel) { + var at = start + while (at < end) at += transferTo(at, end - at, out) + } + + private const val VARINT = 0 + private const val FIXED64 = 1 + private const val LENGTH_DELIMITED = 2 + private const val FIXED32 = 5 + + // onnx.proto field numbers + private const val MODEL_GRAPH = 7 + private const val GRAPH_NODE = 1 + private const val GRAPH_INPUT = 11 + private const val VALUE_INFO_NAME = 1 + private const val NODE_INPUT = 1 + private const val NODE_OUTPUT = 2 + private const val NODE_NAME = 3 + private const val NODE_OP_TYPE = 4 + private const val NODE_ATTRIBUTE = 5 + private const val ATTRIBUTE_NAME = 1 + private const val ATTRIBUTE_INT = 3 + private const val ATTRIBUTE_TENSOR = 5 + private const val ATTRIBUTE_TYPE = 20 + private const val ATTRIBUTE_TYPE_INT = 2L + private const val ATTRIBUTE_TYPE_TENSOR = 4L + private const val TENSOR_DATA_TYPE = 2 + private const val TENSOR_NAME = 8 + private const val TENSOR_RAW_DATA = 9 + private const val TENSOR_FLOAT = 1L + + private const val AUDIO = "audio_signal" + private const val AUDIO_RAW = "audio_raw" + private const val LENGTH = "length" + private const val SCALE = "audio_scale" + private const val AUDIO_SCALE = 0.1f +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/CheckText.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/CheckText.kt new file mode 100644 index 0000000000..921967c492 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/CheckText.kt @@ -0,0 +1,131 @@ +package com.quran.mobile.feature.memorize.check + +import com.quran.mobile.feature.memorize.tracker.PhonemeNormalizer + +/** + * The letters the double-check compares: what its model writes, and how each word of the Quran is + * written in the plain-letter text it was trained on (the "clean" Tanzil text of its quran.json). + * Both sides are reduced to a skeleton of base letters, hamza seats and alif forms unified. A port of + * the lab's text_norm.py / tiers_stream.py; [CheckTextTest] checks it against the lab's tables. + */ +internal object CheckText { + + /** One piece of the model's vocabulary as letters; "|" where a word starts. */ + fun pieceLetters(piece: String): List = buildList { + for (ch in piece) { + if (ch == WORD_START || ch.isWhitespace()) { + add(WORD_BOUNDARY) + } else { + letters(ch.toString()).forEach { add(it.toString()) } + } + } + } + + /** The skeleton of a word of the clean text, runs collapsed. */ + fun wordSkeleton(word: String): String = collapse(letters(word)) + + /** The skeleton of a word from the app's lexicon (its phonemes are already letters). */ + fun phonemeSkeleton(wasl: String): String = PhonemeNormalizer.normalize(wasl, false).replace('ة', 'ه') + + /** + * The clean-text skeleton of each of an ayah's words as the lexicon splits them ([lexicon]: their + * phonemes), from the ayah's clean text. The two split a few ayahs differently (217 of 6,236), e.g. + * one word in one and two in the other: then the words are aligned by their letters. + */ + fun ayahSkeletons(sura: Int, ayah: Int, lexicon: List, clean: String): List { + var words = clean.replace("\uFEFF", "").split(WHITESPACE).filter { it.isNotEmpty() } + // the clean text starts each sura's first ayah with the basmala, the lexicon doesn't + if (ayah == 1 && sura != 1 && sura != 9 && words.take(4) == BASMALA) words = words.drop(4) + val lex = lexicon.map { phonemeSkeleton(it) } + val cleanSkeletons = words.map { wordSkeleton(it) } + if (lex.isEmpty()) return emptyList() + val aligned = if (lex.size == cleanSkeletons.size) cleanSkeletons else alignWords(lex, cleanSkeletons) + return aligned.mapIndexed { i, skeleton -> skeleton?.takeIf { it.isNotEmpty() } ?: lex[i] } + } + + /** Per lexicon word, the clean skeleton covering it (groups 1:1, 1:2 and 2:1). */ + fun alignWords(lex: List, clean: List): List { + val n = lex.size + val m = clean.size + val cost = Array(n + 1) { DoubleArray(m + 1) { Double.POSITIVE_INFINITY } } + val step = Array(n + 1) { arrayOfNulls(m + 1) } + cost[0][0] = 0.0 + for (i in 0..n) { + for (j in 0..m) { + if (cost[i][j] == Double.POSITIVE_INFINITY) continue + for ((di, dj) in STEPS) { + if (i + di > n || j + dj > m) continue + val c = cost[i][j] + edit(lex.subList(i, i + di).joinToString(""), clean.subList(j, j + dj).joinToString("")) + + if (di + dj > 2) 0.5 else 0.0 + if (c < cost[i + di][j + dj]) { + cost[i + di][j + dj] = c + step[i + di][j + dj] = intArrayOf(di, dj) + } + } + } + } + val out = arrayOfNulls(n) + var i = n + var j = m + while (i > 0) { + val (di, dj) = step[i][j] ?: return List(n) { null } + i -= di + j -= dj + if (di == 1) { + out[i] = clean.subList(j, j + dj).joinToString("") + } else { + // one clean word for two lexicon words: split it where it fits them best + val w = clean[j] + val k = (0..w.length).minBy { edit(lex[i], w.substring(0, it)) + edit(lex[i + 1], w.substring(it)) } + out[i] = w.substring(0, k) + out[i + 1] = w.substring(k) + } + } + return out.toList() + } + + fun edit(a: String, b: String): Int { + var previous = IntArray(b.length + 1) { it } + for (i in 1..a.length) { + val current = IntArray(b.length + 1) + current[0] = i + for (j in 1..b.length) { + current[j] = minOf(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + if (a[i - 1] == b[j - 1]) 0 else 1) + } + previous = current + } + return previous[b.length] + } + + // small waw/ya dropped (the model has no piece for them), hamza on/under alif and alif wasla + // folded to alif (the clean text has none), then text_norm's unification; diacritics and marks + // removed; only base letters kept + private fun letters(text: String): String { + val out = StringBuilder() + for (ch in text) { + when (ch) { + 'ۥ', 'ۦ', '\uFEFF', 'ـ' -> Unit + 'أ', 'إ', 'ٱ' -> out.append('ا') + 'ؤ', 'ئ' -> out.append('ء') + 'آ' -> out.append("ءا") + 'ى' -> out.append('ي') + 'ة' -> out.append('ه') + 'ٰ' -> out.append('ا') + else -> if (ch in 'ء'..'ي') out.append(ch) + } + } + return out.toString() + } + + private fun collapse(text: String): String { + val out = StringBuilder() + for (ch in text) if (out.isEmpty() || out.last() != ch) out.append(ch) + return out.toString() + } + + const val WORD_BOUNDARY = "|" + private const val WORD_START = '▁' + private val WHITESPACE = Regex("\\s+") + private val BASMALA = listOf("بسم", "الله", "الرحمن", "الرحيم") + private val STEPS = listOf(1 to 1, 1 to 2, 2 to 1) +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheck.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheck.kt new file mode 100644 index 0000000000..e76fd9d108 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheck.kt @@ -0,0 +1,127 @@ +package com.quran.mobile.feature.memorize.check + +import com.quran.mobile.feature.memorize.data.Passage + +/** The double-check of a session, if it is on and installed (loading takes seconds). */ +fun interface DoubleCheckSource { + fun open(): DoubleCheck? +} + +/** + * A second opinion before the session corrects the user: whether the word the session is waiting + * for was said after all, in the last seconds the user said. If it was, the hint isn't spoken, or + * the mistake isn't shown. + */ +interface DoubleCheck : AutoCloseable { + /** Whether word [k] of [passage] was said in [audio] (16 kHz mono, the last seconds). */ + fun said(audio: FloatArray, passage: Passage, k: Int): Boolean + + /** How long the last check took, in milliseconds. */ + val lastMs: Long +} + +/** An offline CTC model: the pieces of its vocabulary it hears in some audio (16 kHz mono). */ +interface PieceRecognizer : AutoCloseable { + /** Blanks and repeats collapsed. */ + fun pieces(audio: FloatArray): IntArray + + override fun close() = Unit +} + +/** + * The double-check with a larger model, the Tilawi FastConformer. It listens again to the last + * seconds, with all of their context. It was measured in the lab (REPORT.md §15) and on a phone. + * + * The rule: the word must be in the model's transcript, within a quarter of its letters, right after + * the word before it (for the passage's first word, right before the next one). One word heard alone + * isn't enough, because a short word matches too much. + */ +class TilawiDoubleCheck internal constructor( + private val recognizer: PieceRecognizer, + /** Per piece of the vocabulary, its letters ("|" where a word starts). */ + private val pieces: List>, + /** The clean text of an ayah, as the model was trained on. */ + private val cleanText: (sura: Int, ayah: Int) -> String?, +) : DoubleCheck { + + // per ayah (sura * 1000 + ayah), the skeletons of its words + private val skeletons = HashMap>() + + @Volatile override var lastMs: Long = 0L + private set + + /** What the model heard, as letters: runs within a word collapsed, word boundaries dropped. */ + internal fun letters(audio: FloatArray): String { + val out = StringBuilder() + var last: String? = null + var inWord = false + for (id in recognizer.pieces(audio)) { + for (letter in pieces.getOrNull(id).orEmpty()) { + if (letter == CheckText.WORD_BOUNDARY) { + inWord = false + last = null + continue + } + if (inWord && letter == last) continue + out.append(letter) + last = letter + inWord = true + } + } + return out.toString() + } + + override fun said(audio: FloatArray, passage: Passage, k: Int): Boolean { + if (audio.size < MIN_SAMPLES || k !in passage.words.indices) return false + val started = System.nanoTime() + try { + val word = skeleton(passage, k) ?: return false + val before = if (k > 0) skeleton(passage, k - 1) else null + val after = if (k == 0) skeleton(passage, k + 1) else null + if (before == null && after == null) return false + val text = letters(audio) + val n = word.length + for (i in text.indices) { + for (d in -1..1) { + if (n + d <= 0 || i + n + d > text.length) continue + if (CheckText.edit(text.substring(i, i + n + d), word) > tolerance(word)) continue + if (before != null && endsWith(text.substring(0, i), before)) return true + if (after != null && startsWith(text.substring(i + n + d), after)) return true + } + } + return false + } finally { + lastMs = (System.nanoTime() - started) / 1_000_000 + } + } + + private fun skeleton(passage: Passage, index: Int): String? { + val word = passage.words.getOrNull(index)?.id ?: return null + val key = word.sura * 1000 + word.ayah + val ayah = skeletons.getOrPut(key) { + val clean = cleanText(word.sura, word.ayah) ?: return null + val lexicon = passage.words.filter { it.id.sura == word.sura && it.id.ayah == word.ayah }.map { it.wasl } + CheckText.ayahSkeletons(word.sura, word.ayah, lexicon, clean) + } + return ayah.getOrNull(word.word - 1) + } + + private fun tolerance(word: String) = word.length / 4 + + private fun endsWith(text: String, word: String) = (-1..1).any { d -> + val n = word.length + d + n > 0 && text.length >= n && CheckText.edit(text.substring(text.length - n), word) <= tolerance(word) + } + + private fun startsWith(text: String, word: String) = (-1..1).any { d -> + val n = word.length + d + n > 0 && text.length >= n && CheckText.edit(text.substring(0, n), word) <= tolerance(word) + } + + override fun close() = recognizer.close() + + private companion object { + // less than a second can't hold a word and its neighbour + const val MIN_SAMPLES = 16_000 + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckAdvice.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckAdvice.kt new file mode 100644 index 0000000000..34fe476397 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckAdvice.kt @@ -0,0 +1,59 @@ +package com.quran.mobile.feature.memorize.check + +import android.app.ActivityManager +import android.content.Context +import android.os.Build +import com.quran.mobile.di.qualifier.ApplicationContext +import com.quran.mobile.feature.memorize.settings.MemorizePreferences +import dev.zacsweers.metro.Inject + +/** + * Whether the double-check suits this phone, and why: it is recommended with the setting, and + * offered with the recitation model only where it suits. + * + * Its model needs about 300 MB more memory while the user recites. On a Mi 11 (Snapdragon 888, + * 8 GB), its process peaked at 210–330 MB and a check took ~0.7 s; the app's own memory didn't + * change. Phones with less than ~6 GB of memory, or a 32-bit processor, are not advised to use it. + * Once it has run on the phone, the measured time decides: hints that come more than 1.5 s late + * are not worth the fewer wrong ones. + */ +class DoubleCheckAdvice @Inject constructor( + @param:ApplicationContext private val context: Context, + private val preferences: MemorizePreferences, +) { + enum class Reason { + /** Enough memory and a 64-bit processor (not run here yet). */ + SUITS, + /** It has run here, fast enough. */ + FAST, + LOW_MEMORY, + OLD_PROCESSOR, + /** It has run here, too slowly. */ + SLOW, + } + + data class Advice(val recommended: Boolean, val reason: Reason, val memoryBytes: Long, val checkMs: Long) + + fun advice(): Advice { + val activityManager = context.getSystemService(ActivityManager::class.java) + val memory = ActivityManager.MemoryInfo().also { activityManager.getMemoryInfo(it) }.totalMem + return advise(memory, activityManager.isLowRamDevice, Build.SUPPORTED_64_BIT_ABIS.isNotEmpty(), preferences.doubleCheckMs) + } + + companion object { + /** About 6 GB phones and up (the system keeps some of it, so they report a little less). */ + const val MIN_MEMORY_BYTES = 5_000_000_000L + const val MAX_CHECK_MS = 1_500L + + fun advise(memoryBytes: Long, lowRamDevice: Boolean, is64Bit: Boolean, checkMs: Long): Advice { + val reason = when { + lowRamDevice || memoryBytes < MIN_MEMORY_BYTES -> Reason.LOW_MEMORY + !is64Bit -> Reason.OLD_PROCESSOR + checkMs > MAX_CHECK_MS -> Reason.SLOW + checkMs > 0 -> Reason.FAST + else -> Reason.SUITS + } + return Advice(reason == Reason.SUITS || reason == Reason.FAST, reason, memoryBytes, checkMs) + } + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckModel.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckModel.kt new file mode 100644 index 0000000000..b905148694 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckModel.kt @@ -0,0 +1,135 @@ +package com.quran.mobile.feature.memorize.check + +import android.content.Context +import android.util.JsonReader +import com.quran.data.di.AppScope +import com.quran.mobile.di.qualifier.ApplicationContext +import com.quran.mobile.feature.memorize.model.ModelFile +import com.quran.mobile.feature.memorize.model.SpeechModelSpec +import com.quran.mobile.feature.memorize.model.SpeechModelStore +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import java.io.File +import java.io.IOException + +/** Creates the double-check's recognizer from its model files; replaced by a fake in tests. */ +fun interface PieceRecognizerFactory { + fun create(model: File, tokens: File): PieceRecognizer +} + +/** + * The double-check's model (optional, see [DoubleCheck]): downloaded on request from where it is + * published, verified, and prepared for the app's speech engine ([CheckGraph]). + */ +@SingleIn(AppScope::class) +class DoubleCheckModel private constructor( + val store: SpeechModelStore, + private val recognizers: PieceRecognizerFactory, +) : DoubleCheckSource { + @Inject constructor(@ApplicationContext context: Context, recognizers: PieceRecognizerFactory) : + this(SpeechModelStore.of(context, SPEC), recognizers) + + val isInstalled: Boolean get() = store.isInstalled() + + /** Loads the check (seconds, and ~300 MB of memory): not on the main thread. Null if it can't. */ + override fun open(): DoubleCheck? { + if (!store.isInstalled()) return null + return try { + val directory = store.modelFile.parentFile!! + val pieces = readVocabulary(File(directory, SPEC.tokens.name)) + val tokens = File(directory, SHERPA_TOKENS) + // the speech engine names piece i "p" and needs the blank by name (the last piece) + val expected = pieces.indices.joinToString("") { i -> if (i == pieces.lastIndex) " $i\n" else "p$i $i\n" } + if (!tokens.exists() || tokens.readText() != expected) tokens.writeText(expected) + val clean = readCleanText(File(directory, QURAN.name)) + val recognizer = recognizers.create(store.modelFile, tokens) + TilawiDoubleCheck(recognizer, pieces.map { CheckText.pieceLetters(it) }) { sura, ayah -> clean[sura * 1000 + ayah] } + } catch (_: IOException) { + null + } catch (_: IllegalStateException) { + // e.g. a malformed file, or the engine couldn't load the model + null + } + } + + fun delete() = store.delete() + + /** vocab.json: {"0": "", "1": "ة", ...}, every id from 0. */ + private fun readVocabulary(file: File): List { + val pieces = HashMap() + JsonReader(file.reader()).use { reader -> + reader.beginObject() + while (reader.hasNext()) pieces[reader.nextName().toInt()] = reader.nextString() + reader.endObject() + } + return List(pieces.size) { pieces[it] ?: throw IOException("vocab.json has no piece $it") } + } + + /** quran.json: [{"surah": 1, "ayah": 1, "text_clean": "...", ...}, ...]. */ + private fun readCleanText(file: File): Map { + val text = HashMap(6_300) + JsonReader(file.reader()).use { reader -> + reader.beginArray() + while (reader.hasNext()) { + var sura = 0 + var ayah = 0 + var clean: String? = null + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + "surah" -> sura = reader.nextInt() + "ayah" -> ayah = reader.nextInt() + "text_clean" -> clean = reader.nextString() + else -> reader.skipValue() + } + } + reader.endObject() + if (clean != null) text[sura * 1000 + ayah] = clean + } + reader.endArray() + } + return text + } + + companion object { + // The Tilawi FastConformer by muhdur (CC-BY-4.0), as published, pinned to a commit and + // checksummed. The model is converted for the app's speech engine once downloaded (CheckGraph). + private const val BASE = + "https://huggingface.co/muhdur/tilawi-fastconformer-quran/resolve/e9448a0e84f3adb64c28b7a8db501dd8e0e59a84" + private const val SHERPA_TOKENS = "tokens.txt" + + private val QURAN = ModelFile( + name = "quran.json", + url = "$BASE/quran.json", + sha256 = "6e6f31f642c701b49a1ba090311ca4c7a97c6a5b79a302712dff815a9d7b3d03", + size = 3_186_385, + ) + + val SPEC = SpeechModelSpec( + id = "tilawi-fastconformer-e9448a0", + model = ModelFile( + name = "tilawi.onnx", + url = "$BASE/fastconformer_full_mixed.onnx", + sha256 = "2ff3cb3a6e01d3822fd8cb68bbb14f9dcccb1c98dd67c070d7b76c13914bea79", + size = 88_307_524, + source = ModelFile.Source( + sha256 = "4767182cd92975869f81a7e32700b14ca2b04e8dc97a15ff220a8697f4639488", + size = 88_307_366, + converter = CheckGraph, + ), + ), + tokens = ModelFile( + name = "vocab.json", + url = "$BASE/vocab.json", + sha256 = "c55877f3bff8bc3aaefc160e8c2fb88cb349088d092513d40210ccfe535e671b", + size = 21_062, + ), + // the Quran in plain letters (Tanzil Project, CC BY 3.0), only to compare what the model writes + extras = listOf(QURAN), + license = "CC-BY-4.0 (the Quran text: Tanzil Project, CC BY 3.0)", + attribution = "muhdur, Tilawi FastConformer (tilawi-fastconformer-quran)", + ) + + internal fun forTest(store: SpeechModelStore, recognizers: PieceRecognizerFactory) = DoubleCheckModel(store, recognizers) + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckService.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckService.kt new file mode 100644 index 0000000000..21c2630494 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckService.kt @@ -0,0 +1,82 @@ +package com.quran.mobile.feature.memorize.check + +import android.app.Service +import android.content.Intent +import android.os.Bundle +import android.os.Handler +import android.os.HandlerThread +import android.os.IBinder +import android.os.Message +import android.os.Messenger +import android.os.RemoteException +import com.quran.mobile.feature.memorize.engine.sherpa.SherpaPieceRecognizer +import java.io.File +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/** + * Runs the double-check's model in a process of its own (":doublecheck"). + * + * With sherpa-onnx 1.13.8, a second model decoding in the same process as the streaming recognizer + * corrupts the recognizer's state. On a Mi 11 the session went deaf for 20–45 s after a check, + * until its stream started over. This happened whether or not the two decoded at the same time, and + * on a desktop the two failed outright when they did. In its own process the check can't touch the + * recognizer's memory. The app talks to it with [RemotePieceRecognizer]. + */ +class DoubleCheckService : Service() { + private val thread = HandlerThread("double-check").apply { start() } + private var recognizer: SherpaPieceRecognizer? = null + private val messenger = Messenger(Handler(thread.looper) { message -> handle(message); true }) + + override fun onBind(intent: Intent): IBinder = messenger.binder + + private fun handle(message: Message) { + val reply = Message.obtain(null, message.what) + when (message.what) { + OPEN -> { + recognizer?.close() + recognizer = null + val data = message.data + recognizer = runCatching { + SherpaPieceRecognizer(File(data.getString(MODEL)!!), File(data.getString(TOKENS)!!)) + }.getOrNull() + reply.arg1 = if (recognizer != null) 1 else 0 + } + PIECES -> { + // 16-bit little-endian samples, in a file of the app's (too big for a binder message) + val audio = runCatching { + val samples = ByteBuffer.wrap(File(message.data.getString(AUDIO)!!).readBytes()).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer() + FloatArray(samples.remaining()) { samples.get(it) / 32_768f } + }.getOrNull() + val pieces = audio?.let { a -> recognizer?.let { runCatching { it.pieces(a) }.getOrNull() } } + reply.arg1 = if (pieces != null) 1 else 0 + reply.data = Bundle().apply { putIntArray(RESULT, pieces ?: IntArray(0)) } + } + else -> return + } + try { + message.replyTo?.send(reply) + } catch (_: RemoteException) { + // the app went away + } + } + + override fun onDestroy() { + // its looper runs no more messages after this + Handler(thread.looper).post { + recognizer?.close() + recognizer = null + } + thread.quitSafely() + super.onDestroy() + } + + internal companion object { + const val OPEN = 1 + const val PIECES = 2 + const val MODEL = "model" + const val TOKENS = "tokens" + const val AUDIO = "audio" + const val RESULT = "pieces" + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/RemotePieceRecognizer.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/RemotePieceRecognizer.kt new file mode 100644 index 0000000000..813b836bfe --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/check/RemotePieceRecognizer.kt @@ -0,0 +1,116 @@ +package com.quran.mobile.feature.memorize.check + +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.os.Bundle +import android.os.Handler +import android.os.HandlerThread +import android.os.IBinder +import android.os.Message +import android.os.Messenger +import android.os.RemoteException +import java.io.File +import java.io.IOException +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.concurrent.CountDownLatch +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit + +/** + * The double-check's model, in its own process ([DoubleCheckService]). Not on the main thread: + * every call waits for the other process. If that process goes away (e.g. the system needs its + * memory), the checks hear nothing, and the session corrects as it would without them. + */ +internal class RemotePieceRecognizer(private val context: Context, model: File, tokens: File) : PieceRecognizer { + private val thread = HandlerThread("double-check replies").apply { start() } + private val replies = LinkedBlockingQueue() + private val replyTo = Messenger(Handler(thread.looper) { message -> replies.put(Message.obtain(message)); true }) + private val connected = CountDownLatch(1) + @Volatile private var service: Messenger? = null + private val connection = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName, binder: IBinder) { + service = Messenger(binder) + connected.countDown() + } + + override fun onServiceDisconnected(name: ComponentName) { + service = null + } + } + + // what the check hears goes through a file: 8 s of audio is too big for a binder message (Android + // 16 refused them, and they had to be one-way) + private val audioFile = File(context.cacheDir, "doublecheck/audio.pcm").apply { parentFile?.mkdirs() } + + init { + // important: the check's process runs at the app's priority (not cached, so never frozen) while + // a session uses it + val bound = context.bindService( + Intent(context, DoubleCheckService::class.java), connection, Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT, + ) + val opened = bound && connected.await(CONNECT_SECONDS, TimeUnit.SECONDS) && + call( + DoubleCheckService.OPEN, + Bundle().apply { + putString(DoubleCheckService.MODEL, model.path) + putString(DoubleCheckService.TOKENS, tokens.path) + }, + LOAD_SECONDS, + )?.arg1 == 1 + if (!opened) { + close() + throw IllegalStateException("the double-check's model didn't load") + } + } + + @Synchronized + override fun pieces(audio: FloatArray): IntArray { + // 16-bit, as speech models hear it + val bytes = ByteBuffer.allocate(audio.size * 2).order(ByteOrder.LITTLE_ENDIAN) + for (x in audio) bytes.putShort((x * 32_768f).toInt().coerceIn(-32_768, 32_767).toShort()) + try { + audioFile.writeBytes(bytes.array()) + } catch (_: IOException) { + return IntArray(0) + } + val reply = call(DoubleCheckService.PIECES, Bundle().apply { putString(DoubleCheckService.AUDIO, audioFile.path) }, CHECK_SECONDS) + return reply?.takeIf { it.arg1 == 1 }?.data?.getIntArray(DoubleCheckService.RESULT) ?: IntArray(0) + } + + /** Sends [what] and waits for its reply; null if there was none in time. */ + @Synchronized + private fun call(what: Int, data: Bundle, timeoutSeconds: Long): Message? { + val service = service ?: return null + replies.clear() + val message = Message.obtain(null, what).apply { + this.data = data + replyTo = this@RemotePieceRecognizer.replyTo + } + try { + service.send(message) + } catch (_: RemoteException) { + return null + } + while (true) { + val reply = replies.poll(timeoutSeconds, TimeUnit.SECONDS) ?: return null + // a late reply to an earlier call is dropped + if (reply.what == what) return reply + } + } + + override fun close() { + audioFile.delete() + runCatching { context.unbindService(connection) } + service = null + thread.quitSafely() + } + + private companion object { + const val CONNECT_SECONDS = 10L + const val LOAD_SECONDS = 30L + const val CHECK_SECONDS = 10L + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/data/BundledAssets.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/data/BundledAssets.kt new file mode 100644 index 0000000000..58c3fa2ee7 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/data/BundledAssets.kt @@ -0,0 +1,30 @@ +package com.quran.mobile.feature.memorize.data + +import android.content.Context +import java.io.File +import java.io.IOException + +/** Databases bundled as assets, which SQLite can only open once they are copied to a real file. */ +internal object BundledAssets { + + /** + * Copies [asset] to noBackupFilesDir/memorize (once per installed version of the app, so an + * update that changes the asset replaces the old copy) and returns the copy. + */ + @Throws(IOException::class) + fun extract(context: Context, asset: String): File { + val file = File(context.noBackupFilesDir, "memorize/${asset.substringAfterLast('/')}") + val installed = context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime + if (file.exists() && file.lastModified() >= installed) return file + + file.parentFile?.mkdirs() + val partial = File(file.path + ".part") + try { + context.assets.open(asset).use { input -> partial.outputStream().use { input.copyTo(it) } } + if (!partial.renameTo(file)) throw IOException("can't install $asset") + } finally { + partial.delete() + } + return file + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/data/LexiconRepository.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/data/LexiconRepository.kt new file mode 100644 index 0000000000..57fba4b7c3 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/data/LexiconRepository.kt @@ -0,0 +1,103 @@ +package com.quran.mobile.feature.memorize.data + +import android.content.Context +import android.database.sqlite.SQLiteDatabase +import com.quran.data.di.AppScope +import com.quran.data.model.SuraAyah +import com.quran.mobile.di.qualifier.ApplicationContext +import com.quran.mobile.feature.memorize.tracker.WordId +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext + +/** + * The phoneme lexicon (tools/memorize/build_lexicon.py): how every word of the Quran is + * pronounced, in the phonetic script the speech model emits. Bundled with the app. + * + * Reading it throws if the bundled database can't be copied out or opened (e.g. no storage left). + */ +@SingleIn(AppScope::class) +class LexiconRepository private constructor( + private val context: Context, + private val io: CoroutineDispatcher, +) { + @Inject constructor(@ApplicationContext context: Context) : this(context, Dispatchers.IO) + private val mutex = Mutex() + private var database: SQLiteDatabase? = null + + /** + * The words from [start] to the end of its sura, followed by whole suras until there are at least + * [minWords] and [throughSura] is in (or the Quran ends): the session loads more as the user goes + * on (see [nextSuras]). + */ + suspend fun passage(start: SuraAyah, minWords: Int = 0, throughSura: Int = start.sura): Passage = withContext(io) { + val words = suraWords(start.sura, fromAyah = start.ayah) + var sura = start.sura + while ((words.size < minWords || sura < throughSura) && sura < LAST_SURA) { + sura++ + words += suraWords(sura, fromAyah = 1) + } + Passage(words) + } + + /** Whole suras after [afterSura] with at least [minWords] words between them (fewer at the end). */ + suspend fun nextSuras(afterSura: Int, minWords: Int): Passage = withContext(io) { + val words = ArrayList() + var sura = afterSura + while (sura < LAST_SURA && (words.isEmpty() || words.size < minWords)) { + sura++ + words += suraWords(sura, fromAyah = 1) + } + Passage(words) + } + + private suspend fun suraWords(sura: Int, fromAyah: Int): ArrayList { + val words = ArrayList() + database().rawQuery( + "SELECT ayah, word, wasl, iso FROM words WHERE sura = ? AND ayah >= ? ORDER BY ayah, word", + arrayOf(sura.toString(), fromAyah.toString()) + ).use { cursor -> + while (cursor.moveToNext()) { + words += PassageWord( + id = WordId(sura, cursor.getInt(0), cursor.getInt(1)), + wasl = cursor.getString(2), + isolated = cursor.getString(3), + ) + } + } + return words + } + + /** Phrases said around a recitation that aren't part of it, e.g. "isti'adha" or "takbir". */ + suspend fun phrases(kinds: Set): List> = withContext(io) { + val result = ArrayList>() + database().rawQuery("SELECT kind, phonemes FROM phrases", null).use { cursor -> + while (cursor.moveToNext()) { + val kind = cursor.getString(0) + if (kind in kinds) result += kind to cursor.getString(1) + } + } + result + } + + private suspend fun database(): SQLiteDatabase = mutex.withLock { + database ?: open().also { database = it } + } + + private fun open(): SQLiteDatabase { + val file = BundledAssets.extract(context, "memorize/$DATABASE") + return SQLiteDatabase.openDatabase(file.path, null, SQLiteDatabase.OPEN_READONLY) + } + + companion object { + /** A repository reading on the test's dispatcher. */ + internal fun forTest(context: Context, io: CoroutineDispatcher) = LexiconRepository(context, io) + + private const val DATABASE = "lexicon_v1.db" + const val LAST_SURA = 114 + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/data/PageLines.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/data/PageLines.kt new file mode 100644 index 0000000000..470cef5425 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/data/PageLines.kt @@ -0,0 +1,111 @@ +package com.quran.mobile.feature.memorize.data + +import android.database.sqlite.SQLiteDatabase +import com.quran.data.core.QuranFileManager +import com.quran.data.di.AppScope +import com.quran.mobile.feature.memorize.glyph.GlyphTypes +import com.quran.mobile.feature.memorize.glyph.HafsGlyphTypeResolver +import com.quran.page.common.data.coordinates.GlyphSize +import com.quran.page.common.data.coordinates.GlyphTypeResolver +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.Provider +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.File + +/** Where each word is on the pages; replaced by a fake in tests. */ +fun interface LineSource { + /** + * The line (`page * 100 + line`) of every word of the ayat of [suras], keyed by + * [PageLines.key] (index: word number - 1), as far as it is known. + */ + suspend fun forSuras(suras: IntRange): Map +} + +/** + * Where each word is on the pages of the page type in use: its line, as `page * 100 + line`. Used + * to give "the rest of the line" as a hint. Every page type breaks its lines differently, so this + * reads the page type's own ayahinfo database (any width: they share their lines). + */ +@SingleIn(AppScope::class) +class PageLines private constructor( + // a new one each time: it belongs to the page type in use, which the user may change + private val fileManager: Provider, + private val glyphTypes: HafsGlyphTypeResolver, + private val io: CoroutineDispatcher, +) : LineSource { + @Inject constructor(fileManager: Provider, glyphTypes: HafsGlyphTypeResolver) : + this(fileManager, glyphTypes, Dispatchers.IO) + + /** + * The line of every word of the ayat of [suras], keyed by [key] (index: word number - 1); empty + * when the page type's database isn't there or can't be read. + */ + override suspend fun forSuras(suras: IntRange): Map = withContext(io) { + val file = database() ?: return@withContext emptyMap() + runCatching { + SQLiteDatabase.openDatabase(file.path, null, SQLiteDatabase.OPEN_READONLY).use { db -> read(db, suras) } + }.getOrDefault(emptyMap()) + } + + private fun read(db: SQLiteDatabase, suras: IntRange): Map { + val nativeTypes = runCatching { + db.rawQuery("SELECT glyph_type FROM glyphs LIMIT 1", null).use { it.moveToFirst() && !it.isNull(0) } + }.getOrDefault(false) + val result = HashMap() + db.rawQuery( + "SELECT sura_number, ayah_number, page_number, line_number, max_x - min_x, max_y - min_y" + + (if (nativeTypes) ", glyph_type" else "") + + " FROM glyphs WHERE sura_number BETWEEN ? AND ? ORDER BY sura_number, ayah_number, position", + arrayOf(suras.first.toString(), suras.last.toString()) + ).use { cursor -> + val ayah = ArrayList() + fun flush() { + val first = ayah.firstOrNull() ?: return + wordLines(first.sura, first.ayah, ayah)?.let { result[key(first.sura, first.ayah)] = it } + ayah.clear() + } + while (cursor.moveToNext()) { + val glyph = Glyph( + sura = cursor.getInt(0), + ayah = cursor.getInt(1), + line = cursor.getInt(2) * 100 + cursor.getInt(3), + size = GlyphSize(cursor.getInt(4), cursor.getInt(5)), + isWord = if (nativeTypes) cursor.getString(6) == NATIVE_WORD else null, + ) + if (ayah.isNotEmpty() && (ayah[0].sura != glyph.sura || ayah[0].ayah != glyph.ayah)) flush() + ayah += glyph + } + flush() + } + return result + } + + private fun wordLines(sura: Int, ayah: Int, glyphs: List): IntArray? { + if (glyphs.all { it.isWord != null }) { + return glyphs.filter { it.isWord == true }.map { it.line }.toIntArray() + } + val sequence = glyphTypes.sequence(sura, ayah) ?: return null + val types = GlyphTypes.derive(sequence, glyphs.map { it.size }) ?: return null + return glyphs.filterIndexed { i, _ -> types[i] == GlyphTypeResolver.WORD }.map { it.line }.toIntArray() + } + + // the database for this screen's width, or another width's (they share their lines) + private fun database(): File? { + val current = fileManager().ayahInfoFileDirectory() + if (current.isFile) return current + return current.parentFile?.listFiles { file -> file.name.matches(AYAHINFO) }?.minByOrNull { it.name } + } + + private class Glyph(val sura: Int, val ayah: Int, val line: Int, val size: GlyphSize, val isWord: Boolean?) + + companion object { + fun key(sura: Int, ayah: Int) = sura * 1000 + ayah + + private val AYAHINFO = Regex("ayahinfo_\\d+\\.db") + // the glyph_type of words in databases that have glyph types + private const val NATIVE_WORD = "word" + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/data/Passage.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/data/Passage.kt new file mode 100644 index 0000000000..56714cdbd5 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/data/Passage.kt @@ -0,0 +1,38 @@ +package com.quran.mobile.feature.memorize.data + +import com.quran.data.model.SuraAyah +import com.quran.mobile.feature.memorize.tracker.WordId + +/** A word to recite, with its pronunciation in context ([wasl]) and on its own ([isolated]). */ +data class PassageWord(val id: WordId, val wasl: String, val isolated: String) + +/** + * The words a memorization session expects, in order. A session doesn't end with a sura: more suras + * are added as the user goes on, until [reachesEnd]. + */ +data class Passage(val words: List) { + val start: SuraAyah? = words.firstOrNull()?.let { SuraAyah(it.id.sura, it.id.ayah) } + + /** Whether the last word is the last word of the Quran: there is nothing more to load. */ + val reachesEnd: Boolean get() = words.lastOrNull()?.id?.sura == LexiconRepository.LAST_SURA && + words.last().id.ayah == LAST_AYAH_OF_QURAN + + operator fun plus(more: Passage): Passage = Passage(words + more.words) + + fun ayahOf(index: Int): SuraAyah = words[index].id.let { SuraAyah(it.sura, it.ayah) } + + /** Whether the word at [index] is the first word of its ayah. */ + fun startsAyah(index: Int): Boolean = index < words.size && words[index].id.word == 1 + + /** Whether the word at [index] is the last word of its ayah. */ + fun endsAyah(index: Int): Boolean = + index < words.size && (index + 1 == words.size || words[index + 1].id.ayah != words[index].id.ayah) + + /** Whether a user about to say the word at [index] is between ayat (see HintScheduler). */ + fun atAyahBoundary(index: Int): Boolean = startsAyah(index) || endsAyah(index) + + private companion object { + // An-Nas has 6 ayat + const val LAST_AYAH_OF_QURAN = 6 + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/di/MemorizeBindings.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/di/MemorizeBindings.kt new file mode 100644 index 0000000000..a29d4ddfd2 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/di/MemorizeBindings.kt @@ -0,0 +1,87 @@ +package com.quran.mobile.feature.memorize.di + +import android.content.Context +import com.quran.data.di.AppScope +import com.quran.data.di.QuranReadingPageScope +import com.quran.data.di.QuranReadingScope +import com.quran.mobile.di.qualifier.ApplicationContext +import com.quran.mobile.feature.memorize.audio.AudioModeCallState +import com.quran.mobile.feature.memorize.audio.AudioSourceFactory +import com.quran.mobile.feature.memorize.audio.CallState +import com.quran.mobile.feature.memorize.audio.MicAudioSource +import com.quran.mobile.feature.memorize.check.DoubleCheckModel +import com.quran.mobile.feature.memorize.check.DoubleCheckSource +import com.quran.mobile.feature.memorize.check.PieceRecognizerFactory +import com.quran.mobile.feature.memorize.check.RemotePieceRecognizer +import com.quran.mobile.feature.memorize.data.LineSource +import com.quran.mobile.feature.memorize.data.PageLines +import com.quran.mobile.feature.memorize.engine.sherpa.SherpaRecitationEngine +import com.quran.mobile.feature.memorize.presenter.MemorizeHighlightsPresenter +import com.quran.mobile.feature.memorize.presenter.MemorizePlaybackPresenter +import com.quran.mobile.feature.memorize.presenter.MemorizePopupPresenter +import com.quran.mobile.feature.memorize.presenter.MemorizeRecitationPresenter +import com.quran.mobile.feature.memorize.presenter.MemorizeRecitationSettings +import com.quran.mobile.feature.memorize.prompt.HintVoice +import com.quran.mobile.feature.memorize.prompt.HintVoiceDownloads +import com.quran.mobile.feature.memorize.prompt.PromptPlayer +import com.quran.mobile.feature.memorize.prompt.UpcomingSuras +import com.quran.mobile.feature.memorize.recording.Recorders +import com.quran.mobile.feature.memorize.recording.RecordingStore +import com.quran.mobile.feature.memorize.session.RecitationEngineFactory +import com.quran.recitation.presenter.RecitationHighlightsPresenter +import com.quran.recitation.presenter.RecitationPlaybackPresenter +import com.quran.recitation.presenter.RecitationPopupPresenter +import com.quran.recitation.presenter.RecitationPresenter +import com.quran.recitation.presenter.RecitationSettings +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.Binds +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.Provides + +/** Plugs memorization into the app's recitation slot (instead of :feature:recitation's stubs). */ +@BindingContainer +@ContributesTo(QuranReadingScope::class) +interface MemorizeReadingBindings { + @Binds val MemorizeRecitationPresenter.bind: RecitationPresenter + @Binds val MemorizePlaybackPresenter.bind: RecitationPlaybackPresenter +} + +@BindingContainer +@ContributesTo(QuranReadingPageScope::class) +interface MemorizePageBindings { + @Binds val MemorizeHighlightsPresenter.bind: RecitationHighlightsPresenter + @Binds val MemorizePopupPresenter.bind: RecitationPopupPresenter +} + +@BindingContainer +@ContributesTo(AppScope::class) +interface MemorizeAppBindings { + @Binds val MemorizeRecitationSettings.bind: RecitationSettings + @Binds val PromptPlayer.bind: HintVoice + @Binds val PageLines.bind: LineSource + @Binds val HintVoiceDownloads.bind: UpcomingSuras + @Binds val RecordingStore.bind: Recorders + @Binds val DoubleCheckModel.bind: DoubleCheckSource +} + +@BindingContainer +@ContributesTo(AppScope::class) +class MemorizeEngineModule { + @Provides + fun provideEngineFactory(): RecitationEngineFactory = RecitationEngineFactory { models -> + SherpaRecitationEngine(models.modelFile, models.tokensFile) + } + + /** The double-check's model runs in a process of its own (see DoubleCheckService). */ + @Provides + fun providePieceRecognizerFactory(@ApplicationContext context: Context): PieceRecognizerFactory = + PieceRecognizerFactory { model, tokens -> RemotePieceRecognizer(context, model, tokens) } + + @Provides + fun provideAudioSources(): AudioSourceFactory = AudioSourceFactory { onFrame, onError -> + MicAudioSource(onFrame, onError) + } + + @Provides + fun provideCallState(@ApplicationContext context: Context): CallState = AudioModeCallState(context) +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/di/MemorizeComponentInterface.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/di/MemorizeComponentInterface.kt new file mode 100644 index 0000000000..d107fece77 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/di/MemorizeComponentInterface.kt @@ -0,0 +1,23 @@ +package com.quran.mobile.feature.memorize.di + +import com.quran.data.core.QuranInfo +import com.quran.data.di.AppScope +import com.quran.mobile.feature.memorize.settings.MemorizePreferences +import com.quran.mobile.feature.memorize.model.SpeechModelStore +import com.quran.mobile.feature.memorize.recording.RecordingPlayer +import com.quran.mobile.feature.memorize.recording.RecordingStore +import com.quran.mobile.feature.memorize.session.MemorizeSessionController +import com.quran.recitation.pages.PagePreviews +import dev.zacsweers.metro.ContributesTo + +/** Lets Android components that aren't injected (the service, the model import) reach the feature. */ +@ContributesTo(AppScope::class) +interface MemorizeComponentInterface { + fun memorizeSessionController(): MemorizeSessionController + fun speechModelStore(): SpeechModelStore + fun recordingStore(): RecordingStore + fun recordingPlayer(): RecordingPlayer + fun pagePreviews(): PagePreviews + fun memorizePreferences(): MemorizePreferences + fun quranInfo(): QuranInfo +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/glyph/GlyphTypes.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/glyph/GlyphTypes.kt new file mode 100644 index 0000000000..057a754c81 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/glyph/GlyphTypes.kt @@ -0,0 +1,50 @@ +package com.quran.mobile.feature.memorize.glyph + +import com.quran.page.common.data.coordinates.GlyphSize +import com.quran.page.common.data.coordinates.GlyphTypeResolver.Companion.END +import com.quran.page.common.data.coordinates.GlyphTypeResolver.Companion.HIZB +import com.quran.page.common.data.coordinates.GlyphTypeResolver.Companion.PAUSE +import com.quran.page.common.data.coordinates.GlyphTypeResolver.Companion.SAJDAH +import com.quran.page.common.data.coordinates.GlyphTypeResolver.Companion.WORD + +/** + * Tells an ayah's glyphs apart in any page type's layout, given what the text has in that ayah. + * + * The rules of tools/memorize/build_glyph_types.py, which hold for every ayah of the madani pages at + * every width: the last glyph is the ayah end marker; an ayah with a hizb marker starts with it; one + * with a sajdah marker has it just before the end; of the other glyphs, as many as the text has words + * are words and the rest are waqf marks, which are always the shortest glyphs (they float above the + * line). The number of waqf marks comes from the layout, since fonts don't all place the same ones. + */ +internal object GlyphTypes { + + /** Types for [glyphs] given the text's [sequence] for the ayah, or null if they don't fit. */ + fun derive(sequence: String, glyphs: List): String? { + val words = sequence.count { it == WORD } + val hizb = sequence.firstOrNull() == HIZB + val sajdah = SAJDAH in sequence + // a font may draw a marker in the margin rather than as a glyph of the ayah + return derive(words, hizb, sajdah, glyphs) + ?: (if (sajdah) derive(words, hizb, false, glyphs) else null) + ?: (if (hizb) derive(words, false, sajdah, glyphs) else null) + ?: (if (hizb && sajdah) derive(words, hizb = false, sajdah = false, glyphs) else null) + } + + private fun derive(words: Int, hizb: Boolean, sajdah: Boolean, glyphs: List): String? { + val count = glyphs.size + val first = if (hizb) 1 else 0 + val end = count - 1 - if (sajdah) 1 else 0 // the glyphs between the markers: first until end + val pauses = end - first - words + if (count == 0 || end < first || pauses < 0) return null + val pauseAt = (first until end) + .sortedWith(compareBy({ glyphs[it].height }, { glyphs[it].width })) + .take(pauses) + .toSet() + return buildString(count) { + if (hizb) append(HIZB) + for (i in first until end) append(if (i in pauseAt) PAUSE else WORD) + if (sajdah) append(SAJDAH) + append(END) + } + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/glyph/HafsGlyphTypeResolver.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/glyph/HafsGlyphTypeResolver.kt new file mode 100644 index 0000000000..be0d28dd7e --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/glyph/HafsGlyphTypeResolver.kt @@ -0,0 +1,53 @@ +package com.quran.mobile.feature.memorize.glyph + +import android.content.Context +import com.quran.data.di.AppScope +import com.quran.mobile.di.qualifier.ApplicationContext +import com.quran.page.common.data.coordinates.GlyphSize +import com.quran.page.common.data.coordinates.GlyphTypeResolver +import dev.zacsweers.metro.ContributesIntoSet +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn + +/** + * Glyph types for any page type of the Hafs text: what the text has in each ayah (its words, and + * whether it carries a hizb or sajdah marker) comes from the bundled sequence, and the page type's + * own glyphs tell where its font puts the waqf marks (see [GlyphTypes.derive]). + */ +@SingleIn(AppScope::class) +@ContributesIntoSet(AppScope::class) +class HafsGlyphTypeResolver @Inject constructor( + @param:ApplicationContext private val context: Context +) : GlyphTypeResolver { + + private val sequences: Map by lazy { load() } + + override fun glyphTypes(sura: Int, ayah: Int, glyphs: List): String? = + sequences[key(sura, ayah)]?.let { GlyphTypes.derive(it, glyphs) } + + /** The text's sequence of glyph types for an ayah, as drawn in the madani mushaf. */ + fun sequence(sura: Int, ayah: Int): String? = sequences[key(sura, ayah)] + + private fun load(): Map { + val result = HashMap(6_300) + context.assets.open(ASSET).use { input -> + input.bufferedReader().useLines { lines -> + lines.forEach { line -> + val parts = line.split(' ') + if (parts.size == 3) { + result[key(parts[0].toInt(), parts[1].toInt())] = parts[2] + } + } + } + } + return result + } + + private fun key(sura: Int, ayah: Int) = sura * 1000 + ayah + + private companion object { + // generated by tools/memorize/build_glyph_types.py from the madani ayahinfo databases; stored + // uncompressed in the source tree (the APK compresses assets itself) + const val ASSET = "memorize/glyph_types_madani_v1.txt" + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/model/ModelImportActivity.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/model/ModelImportActivity.kt new file mode 100644 index 0000000000..d2062b2707 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/model/ModelImportActivity.kt @@ -0,0 +1,96 @@ +package com.quran.mobile.feature.memorize.model + +import android.app.AlertDialog +import android.content.res.Configuration +import android.net.Uri +import android.os.Bundle +import android.text.format.Formatter +import android.widget.Toast +import androidx.activity.ComponentActivity +import androidx.activity.result.contract.ActivityResultContracts +import androidx.lifecycle.lifecycleScope +import com.quran.mobile.di.QuranApplicationComponentProvider +import com.quran.mobile.feature.memorize.R +import com.quran.mobile.feature.memorize.di.MemorizeComponentInterface +import kotlinx.coroutines.launch + +/** + * Installs the speech model from files the user picks (e.g. copied from a computer), so it can be + * set up without any internet connection. A checklist of the model's files, each picked on its own + * with the system file picker, or all at once from the .zip they came in. + */ +class ModelImportActivity : ComponentActivity() { + + private val models: SpeechModelStore by lazy { + ((application as QuranApplicationComponentProvider).provideQuranApplicationComponent() as MemorizeComponentInterface) + .speechModelStore() + } + + private var dialog: AlertDialog? = null + // the file the picker was opened for, or null for the .zip + private var expected: ModelFile? = null + + private val picker = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri == null) showChecklist() else import(uri) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + showChecklist() + } + + override fun onDestroy() { + dialog?.dismiss() + super.onDestroy() + } + + private fun showChecklist() { + val missing = models.missingFiles() + if (missing.isEmpty()) { + Toast.makeText(this, R.string.memorize_model_imported, Toast.LENGTH_LONG).show() + finish() + return + } + val files = models.spec.files + val items = files.map { file -> + if (file in missing) { + getString(R.string.memorize_import_choose_file, file.name, Formatter.formatShortFileSize(this, file.size)) + } else { + getString(R.string.memorize_import_file_done, file.name) + } + } + getString(R.string.memorize_import_choose_zip) + dialog = AlertDialog.Builder(this, dialogTheme()) + .setTitle(R.string.memorize_import_title) + .setItems(items.toTypedArray()) { _, which -> + val file = files.getOrNull(which) + if (file != null && file !in missing) { + showChecklist() + } else { + expected = file + picker.launch(arrayOf("*/*")) + } + } + .setNegativeButton(android.R.string.cancel) { _, _ -> finish() } + .setOnCancelListener { finish() } + .show() + } + + private fun import(uri: Uri) { + val expected = expected + lifecycleScope.launch { + val installed = models.importFile(uri) + val message = when { + installed.isNotEmpty() -> getString(R.string.memorize_import_installed, installed.joinToString { it.name }) + expected != null -> getString(R.string.memorize_import_wrong_file, expected.name) + else -> getString(R.string.memorize_import_wrong_zip) + } + Toast.makeText(this@ModelImportActivity, message, Toast.LENGTH_LONG).show() + showChecklist() + } + } + + private fun dialogTheme(): Int { + val night = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES + return if (night) android.R.style.Theme_DeviceDefault_Dialog_Alert else android.R.style.Theme_DeviceDefault_Light_Dialog_Alert + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/model/SpeechModelStore.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/model/SpeechModelStore.kt new file mode 100644 index 0000000000..bdd155d39f --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/model/SpeechModelStore.kt @@ -0,0 +1,359 @@ +package com.quran.mobile.feature.memorize.model + +import android.content.Context +import android.net.Uri +import com.quran.data.di.AppScope +import com.quran.mobile.di.qualifier.ApplicationContext +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.io.FilterInputStream +import java.io.IOException +import java.io.InputStream +import java.net.HttpURLConnection +import java.net.URL +import java.security.MessageDigest +import java.util.zip.ZipInputStream + +/** + * The on-device speech model. It is downloaded once (or imported from a file) and verified, after + * which everything runs offline. Nothing but the model files themselves is ever fetched. + */ +@SingleIn(AppScope::class) +class SpeechModelStore private constructor( + private val context: Context, + val spec: SpeechModelSpec, + /** How long to wait before trying a cut-off download again (doubled each time). */ + private val retryDelayMs: Long = RETRY_DELAY_MS, +) { + @Inject constructor(@ApplicationContext context: Context) : this(context, SpeechModelSpec.DEFAULT) + + sealed interface State { + data object NotInstalled : State + data class Downloading(val downloadedBytes: Long, val totalBytes: Long) : State + data object Installed : State + data class Failed(val reason: String) : State + } + + private val directory = File(context.noBackupFilesDir, "memorize/models/${spec.id}") + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private var downloadJob: Job? = null + private val _state = MutableStateFlow(if (isInstalled()) State.Installed else State.NotInstalled) + val state: StateFlow = _state.asStateFlow() + + val modelFile: File get() = File(directory, spec.model.name) + val tokensFile: File get() = File(directory, spec.tokens.name) + + fun isInstalled(): Boolean = spec.files.all { File(directory, it.name).length() == it.size } + + /** Whether a download is running (it carries on if the screen that started it goes away). */ + val isDownloading: Boolean get() = downloadJob?.isActive == true + + /** Downloads any missing file in the background, verifying each; progress is in [state]. */ + fun startDownload() { + if (isDownloading) return + _state.value = State.Downloading(0, spec.downloadSize) + downloadJob = scope.launch { download() } + } + + fun cancelDownload() { + downloadJob?.cancel() + } + + private suspend fun download() { + try { + directory.mkdirs() + val total = spec.downloadSize + var done = spec.files.filter { File(directory, it.name).length() == it.size }.sumOf { it.downloadSize } + for (file in spec.files) { + val target = File(directory, file.name) + if (target.length() == file.size) continue + val base = done + // a connection that drops (as mobile networks do) is tried again; a wrong file is not + var attempt = 1 + while (true) { + try { + fetch(file, target) { written -> _state.value = State.Downloading(base + written, total) } + break + } catch (e: WrongFile) { + throw e + } catch (e: IOException) { + if (attempt == DOWNLOAD_ATTEMPTS) throw e + delay(retryDelayMs shl (attempt - 1)) + attempt++ + } + } + done += file.downloadSize + } + _state.value = State.Installed + } catch (e: CancellationException) { + _state.value = if (isInstalled()) State.Installed else State.NotInstalled + throw e + } catch (e: IOException) { + _state.value = State.Failed(e.message ?: e.javaClass.simpleName) + } catch (e: SecurityException) { + // e.g. no network permission (a test APK); never a crash of the app's download scope + _state.value = State.Failed(e.message ?: e.javaClass.simpleName) + } + } + + private suspend fun fetch(file: ModelFile, target: File, progress: (Long) -> Unit) { + val connection = URL(file.url).openConnection() as HttpURLConnection + connection.instanceFollowRedirects = true + connection.connectTimeout = 30_000 + connection.readTimeout = 60_000 + try { + val code = connection.responseCode + if (code != HttpURLConnection.HTTP_OK) { + // a server error may pass; a missing file won't + if (code in 400..499) throw WrongFile("HTTP $code for ${file.name}") + throw IOException("HTTP $code for ${file.name}") + } + install(connection.inputStream, file, target, progress) + } finally { + connection.disconnect() + } + } + + /** The model files that aren't installed yet. */ + fun missingFiles(): List = spec.files.filter { File(directory, it.name).length() != it.size } + + /** + * Installs model files the user picked (e.g. copied from a computer), for a fully offline setup. + * True if the model is installed afterwards. + */ + suspend fun import(uris: List): Boolean { + for (uri in uris) importFile(uri) + return isInstalled() + } + + /** + * Installs what [uri] holds: one of the model files, or a .zip with them. Files are recognized by + * their SHA-256 (their names may have changed on the way). Returns the files that were installed. + */ + suspend fun importFile(uri: Uri): List = withContext(Dispatchers.IO) { + // a download would write the same files + downloadJob?.cancelAndJoin() + directory.mkdirs() + val installed = ArrayList() + val resolver = context.contentResolver + try { + if (resolver.openInputStream(uri)?.use { isZip(it) } == true) { + ZipInputStream(resolver.openInputStream(uri)).use { zip -> + while (true) { + val entry = zip.nextEntry ?: break + if (entry.isDirectory) continue + // install() closes what it reads; the zip has more entries to read + installMatching(object : FilterInputStream(zip) { override fun close() = Unit })?.let { installed += it } + } + } + } else { + resolver.openInputStream(uri)?.let { input -> installMatching(input)?.let { installed += it } } + } + } catch (_: IOException) { + // unreadable + } + _state.value = if (isInstalled()) State.Installed else State.NotInstalled + installed + } + + /** Copies [input] aside and installs it as the model file with the same SHA-256, if any. */ + private suspend fun installMatching(input: InputStream): ModelFile? { + val partial = File(directory, "import.part") + try { + val digest = MessageDigest.getInstance("SHA-256") + var size = 0L + input.use { source -> + partial.outputStream().use { out -> + val buffer = ByteArray(1 shl 16) + while (true) { + currentCoroutineContext().ensureActive() + val read = source.read(buffer) + if (read < 0) break + digest.update(buffer, 0, read) + out.write(buffer, 0, read) + size += read + // larger than any model file: not one of them + if (size > spec.files.maxOf { maxOf(it.size, it.source?.size ?: 0) }) return null + } + } + } + val sha = digest.digest().joinToString("") { "%02x".format(it) } + spec.files.firstOrNull { it.sha256 == sha && it.size == size }?.let { file -> + return if (partial.renameTo(File(directory, file.name))) file else null + } + // a file as published, which the app converts + val file = spec.files.firstOrNull { it.source?.sha256 == sha && it.source.size == size } ?: return null + return try { + convert(partial, file, File(directory, file.name)) + file + } catch (_: IOException) { + null + } + } finally { + partial.delete() + } + } + + /** A file that is wrong as served (missing, or not the one pinned): trying again won't help. */ + private class WrongFile(message: String) : IOException(message) + + companion object { + /** A cut-off download is tried this many times in all, waiting [RETRY_DELAY_MS], then twice that. */ + private const val DOWNLOAD_ATTEMPTS = 3 + private const val RETRY_DELAY_MS = 2_000L + + /** A store for another model (in its own directory), e.g. the double-check's. */ + internal fun of(context: Context, spec: SpeechModelSpec) = SpeechModelStore(context, spec) + + /** A store for a model of the test's own files. */ + internal fun forTest(context: Context, spec: SpeechModelSpec, retryDelayMs: Long = RETRY_DELAY_MS) = + SpeechModelStore(context, spec, retryDelayMs) + } + + private fun isZip(input: InputStream): Boolean { + val header = ByteArray(4) + return input.read(header) == 4 && header.contentEquals(byteArrayOf(0x50, 0x4b, 0x03, 0x04)) + } + + fun delete() { + cancelDownload() + directory.deleteRecursively() + _state.value = State.NotInstalled + } + + private suspend fun install(input: InputStream, file: ModelFile, target: File, progress: (Long) -> Unit) { + val partial = File(target.path + ".part") + val expected = file.source + try { + val digest = MessageDigest.getInstance("SHA-256") + var written = 0L + input.use { source -> + partial.outputStream().use { out -> + val buffer = ByteArray(1 shl 16) + while (true) { + currentCoroutineContext().ensureActive() + val read = source.read(buffer) + if (read < 0) break + digest.update(buffer, 0, read) + out.write(buffer, 0, read) + written += read + progress(written) + } + } + } + val sha = digest.digest().joinToString("") { "%02x".format(it) } + // shorter than it should be: the connection was cut (a download tries again) + if (written < (expected?.size ?: file.size)) throw IOException("${file.name} was cut short") + if (sha != (expected?.sha256 ?: file.sha256) || written != (expected?.size ?: file.size)) { + throw WrongFile("${file.name} failed verification") + } + if (expected != null) { + convert(partial, file, target) + } else if (!partial.renameTo(target)) { + throw IOException("can't install ${file.name}") + } + } finally { + partial.delete() + } + } + + /** Converts the verified [source] of [file] into [target], and verifies the result. */ + private fun convert(source: File, file: ModelFile, target: File) { + val converted = File(target.path + ".converted") + try { + file.source!!.converter.convert(source, converted) + if (converted.length() != file.size || sha256(converted) != file.sha256) { + throw IOException("${file.name} failed verification after conversion") + } + if (!converted.renameTo(target)) throw IOException("can't install ${file.name}") + } finally { + converted.delete() + } + } + + private fun sha256(file: File): String { + val digest = MessageDigest.getInstance("SHA-256") + file.inputStream().use { input -> + val buffer = ByteArray(1 shl 16) + while (true) { + val read = input.read(buffer) + if (read < 0) break + digest.update(buffer, 0, read) + } + } + return digest.digest().joinToString("") { "%02x".format(it) } + } +} + +/** + * One file of a model, as installed. With a [source], what is downloaded (or imported) is the file + * as published, which the app converts into this one. + */ +data class ModelFile(val name: String, val url: String, val sha256: String, val size: Long, val source: Source? = null) { + data class Source(val sha256: String, val size: Long, val converter: ModelConverter) + + val downloadSize: Long get() = source?.size ?: size +} + +/** Turns a downloaded file into the one the app uses (deterministically: the result is checked). */ +fun interface ModelConverter { + fun convert(source: File, target: File) +} + +/** A downloadable speech model and the terms it comes with. */ +data class SpeechModelSpec( + val id: String, + val model: ModelFile, + val tokens: ModelFile, + val license: String, + val attribution: String, + /** Any other files the model needs. */ + val extras: List = emptyList(), +) { + val files: List get() = listOf(model, tokens) + extras + + /** What downloading every file takes. */ + val downloadSize: Long get() = files.sumOf { it.downloadSize } + + companion object { + // Streaming Zipformer2-CTC phoneme recognizer by Quran-Lab (zipformer_p-arabic-v3.1), int8, as + // re-hosted without gating by Saboorhsn/quran-stt-onnx: byte-identical to Quran-Lab's + // zipformer_p_arabic_v3.1.int8.onnx and tokens.txt (gated repo, @3da514fc). Pinned to a commit + // and checksummed. + private const val BASE = + "https://huggingface.co/Saboorhsn/quran-stt-onnx/resolve/51ec9bcddeaf1c480bbe39064a2a3b88bc2ff224" + + val DEFAULT = SpeechModelSpec( + id = "zipformer-p-arabic-v3.1-int8", + model = ModelFile( + name = "quran-stt-int8.onnx", + url = "$BASE/quran-stt-int8.onnx", + sha256 = "31755836528da336a6192121cd7bc82cb41752dddb65566fd000b89c8686da6b", + size = 72_705_392, + ), + tokens = ModelFile( + name = "tokens.txt", + url = "$BASE/tokens.txt", + sha256 = "252c10687e442aa9291973065fae19fa39bcd681c4f5612ec496a647e20b43a1", + size = 2_346, + ), + license = "Quran-Lab No-Profit License 1.2 (NPL-1.2)", + attribution = "Quran-Lab, zipformer_p-arabic-v3.1", + ) + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/FloatingMicButton.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/FloatingMicButton.kt new file mode 100644 index 0000000000..7684daa5f4 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/FloatingMicButton.kt @@ -0,0 +1,142 @@ +package com.quran.mobile.feature.memorize.presenter + +import android.annotation.SuppressLint +import android.app.Activity +import android.content.Context +import android.view.Gravity +import android.view.MotionEvent +import android.view.ViewConfiguration +import android.view.ViewGroup +import android.widget.FrameLayout +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.platform.ComposeView +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.isVisible +import androidx.core.view.updateLayoutParams +import com.quran.labs.androidquran.common.ui.core.QuranTheme +import com.quran.mobile.feature.memorize.settings.MemorizePreferences +import com.quran.mobile.feature.memorize.ui.MemorizeMicButton +import com.quran.mobile.feature.memorize.ui.MicButtonState +import kotlin.math.hypot + +/** + * The floating mic over the reading screen while a session exists (see [MemorizeMicButton]). It can + * be dragged out of the way; where it was left is remembered. + */ +internal class FloatingMicButton( + private val activity: Activity, + private val preferences: MemorizePreferences, + onToggle: () -> Unit, + onChooseMode: () -> Unit, + onEnd: () -> Unit, + onReplay: () -> Unit, +) { + private val state = mutableStateOf(null) + private val density = activity.resources.displayMetrics.density + + private val container = DraggableFrame(activity) { x, y -> + preferences.micButtonOffset = x to y + }.apply { + isVisible = false + addView(ComposeView(activity).apply { + setContent { + val current = state.value ?: return@setContent + QuranTheme { MemorizeMicButton(current, onToggle, onChooseMode, onEnd, onReplay) } + } + }) + } + + fun attach() { + if (container.parent != null) return + val root = activity.findViewById(android.R.id.content) ?: return + root.addView( + container, + FrameLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM or Gravity.END, + ).apply { + marginEnd = (MARGIN_DP * density).toInt() + bottomMargin = (BOTTOM_DP * density).toInt() + }, + ) + // above the navigation bar and the audio bar + ViewCompat.setOnApplyWindowInsetsListener(container) { view, insets -> + val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout()) + view.updateLayoutParams { bottomMargin = bars.bottom + (BOTTOM_DP * density).toInt() } + insets + } + ViewCompat.requestApplyInsets(container) + preferences.micButtonOffset?.let { (x, y) -> + container.translationX = x + container.translationY = y + } + container.post { container.clampToParent() } + } + + fun detach() { + (container.parent as? ViewGroup)?.removeView(container) + } + + fun show(state: MicButtonState?) { + this.state.value = state + container.isVisible = state != null + } + + /** Moves with the finger once it has moved past the touch slop; taps reach the buttons. */ + @SuppressLint("ViewConstructor") + private class DraggableFrame(context: Context, private val onMoved: (Float, Float) -> Unit) : FrameLayout(context) { + private val slop = ViewConfiguration.get(context).scaledTouchSlop + private var downX = 0f + private var downY = 0f + private var startX = 0f + private var startY = 0f + private var dragging = false + + override fun onInterceptTouchEvent(event: MotionEvent): Boolean { + track(event) + return dragging + } + + @SuppressLint("ClickableViewAccessibility") + override fun onTouchEvent(event: MotionEvent): Boolean { + track(event) + if (dragging && event.actionMasked == MotionEvent.ACTION_MOVE) { + translationX = startX + event.rawX - downX + translationY = startY + event.rawY - downY + clampToParent() + } + if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) { + if (dragging) onMoved(translationX, translationY) + dragging = false + } + return true + } + + private fun track(event: MotionEvent) { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + downX = event.rawX + downY = event.rawY + startX = translationX + startY = translationY + dragging = false + } + MotionEvent.ACTION_MOVE -> + if (!dragging && hypot(event.rawX - downX, event.rawY - downY) > slop) dragging = true + } + } + + /** Keeps the whole button on screen (e.g. after rotating). */ + fun clampToParent() { + val parent = parent as? ViewGroup ?: return + if (width == 0 || parent.width == 0) return + translationX = translationX.coerceIn(-left.toFloat(), (parent.width - width - left).toFloat().coerceAtLeast(-left.toFloat())) + translationY = translationY.coerceIn(-top.toFloat(), (parent.height - height - top).toFloat().coerceAtLeast(-top.toFloat())) + } + } + + private companion object { + const val MARGIN_DP = 12 + const val BOTTOM_DP = 72 + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeHighlightTypes.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeHighlightTypes.kt new file mode 100644 index 0000000000..ebd92d7508 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeHighlightTypes.kt @@ -0,0 +1,40 @@ +package com.quran.mobile.feature.memorize.presenter + +import com.quran.data.model.highlight.HighlightType +import com.quran.data.model.highlight.HighlightType.Mode +import com.quran.mobile.feature.memorize.R + +/** + * How memorization shows up on the page. Ids start at 1000 so they never collide with the app's + * own highlight types (they are keys of a sorted map, ordered by id: on the same word, the lowest + * id is the one drawn). + */ +internal object MemorizeHighlightTypes { + /** The word being heard, when a recorded session plays back: over any other mark. */ + val PLAYING = HighlightType( + 1000, R.color.memorize_playing, Mode.UNDERLAY, isSingle = true, nightColorResId = R.color.memorize_playing_night, + ) + + /** Words not recited yet: not drawn at all. */ + val HIDDEN = HighlightType(1001, R.color.memorize_hidden, Mode.HIDE) + + // The marks are backgrounds drawn under the page image, so the words keep their own colors (e.g. + // on a tajweed-colored mushaf). + + /** Where the user made a mistake: a red background where the (still hidden) word is. */ + val MISTAKE = HighlightType(1002, R.color.memorize_mistake, Mode.UNDERLAY, nightColorResId = R.color.memorize_mistake_night) + + /** Words the app gave as a hint. */ + val HINTED = HighlightType(1003, R.color.memorize_hinted, Mode.UNDERLAY, nightColorResId = R.color.memorize_hinted_night) + + /** Words the user skipped. */ + val MISSED = HighlightType(1004, R.color.memorize_missed, Mode.UNDERLAY, nightColorResId = R.color.memorize_missed_night) + + /** + * Words read so far, while reciting with the text shown: a light trail where the session follows + * the reader. Its night colour keeps its own (lower) alpha. + */ + val RECITED = HighlightType(1005, R.color.memorize_recited, Mode.UNDERLAY, nightColorResId = R.color.memorize_recited_night) + + val ALL = listOf(PLAYING, HIDDEN, MISTAKE, HINTED, MISSED, RECITED) +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeHighlightsPresenter.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeHighlightsPresenter.kt new file mode 100644 index 0000000000..79a25ff948 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeHighlightsPresenter.kt @@ -0,0 +1,81 @@ +package com.quran.mobile.feature.memorize.presenter + +import com.quran.data.core.QuranInfo +import com.quran.data.di.QuranPageScope +import com.quran.data.model.VerseRange +import com.quran.data.model.highlight.HighlightInfo +import com.quran.mobile.feature.memorize.session.MemorizeSessionController +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.recitation.presenter.RecitationHighlightsPresenter +import com.quran.recitation.presenter.RecitationHighlightsPresenter.HighlightAction +import com.quran.recitation.presenter.RecitationHighlightsPresenter.RecitationPage +import dev.zacsweers.metro.Inject +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach + +/** + * Hides the words of the passage that haven't been recited yet and marks mistakes, hints and + * skipped words on the page(s) being shown. Only the difference with what is already applied is + * sent, so revealing a word is cheap. + */ +@QuranPageScope +class MemorizeHighlightsPresenter @Inject constructor( + private val controller: MemorizeSessionController, + private val quranInfo: QuranInfo, +) : RecitationHighlightsPresenter { + + private var scope: CoroutineScope? = null + private var page: RecitationPage? = null + private var applied: Set = emptySet() + + override fun bind(what: RecitationPage) { + page = what + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + this.scope = scope + controller.state.onEach { render(it) }.launchIn(scope) + } + + override fun unbind(what: RecitationPage) { + scope?.cancel() + scope = null + page = null + applied = emptySet() + } + + /** Called after the page's coordinates load: masks sent before that were dropped. */ + override fun refresh() { + val page = page ?: return + page.applyHighlights(MemorizeHighlightTypes.ALL.map { HighlightAction.UnhighlightAll(it) }) + applied = emptySet() + render(controller.state.value) + } + + private fun render(state: MemorizeState?) { + val page = page ?: return + val desired = if (state == null) emptySet() else marksFor(state, page.pageNumbers) + val actions = ArrayList() + (applied - desired).forEach { actions += HighlightAction.Unhighlight(it.info()) } + (desired - applied).forEach { actions += HighlightAction.Highlight(it.info()) } + applied = desired + if (actions.isNotEmpty()) page.applyHighlights(actions) + } + + private fun marksFor(state: MemorizeState, pages: Set): Set = + MemorizeMasks.marks(state, pages.map { versesOn(it) }) + + // the page's ayat and the next page's first one, which may begin on this page in a mushaf whose + // ayat run on to the next page (Shemerly); elsewhere this page has nothing of it to mark + private fun versesOn(page: Int): VerseRange { + val range = quranInfo.getVerseRangeForPage(page) + val next = page + 1 + if (!quranInfo.isValidPage(next)) return range + return range.copy(endingSura = quranInfo.getSuraOnPage(next), endingAyah = quranInfo.getFirstAyahOnPage(next)) + } + + private fun Mark.info() = HighlightInfo(sura, ayah, word, type, scrollToAyah = false) +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeMasks.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeMasks.kt new file mode 100644 index 0000000000..ade471134c --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeMasks.kt @@ -0,0 +1,95 @@ +package com.quran.mobile.feature.memorize.presenter + +import com.quran.data.model.VerseRange +import com.quran.data.model.highlight.HighlightType +import com.quran.mobile.feature.memorize.session.MemorizeState + +/** One highlight on a page: a whole ayah when [word] is -1, otherwise a single word. */ +internal data class Mark(val sura: Int, val ayah: Int, val word: Int, val type: HighlightType) + +/** + * What a memorization session looks like on the pages showing [ranges]: hidden words (whole ayat + * as one mask per line when nothing of them has been recited), the mistake marker (on a word that + * stays hidden), and the styling of hinted and skipped words. In [MemorizeState.Mode.RECITE] nothing + * is hidden: the words read so far are marked instead (see [recitation]). + */ +internal object MemorizeMasks { + + fun marks(state: MemorizeState, ranges: Collection): Set { + if (state.mode == MemorizeState.Mode.RECITE) return recitation(state, ranges) + val marks = HashSet() + val words = state.passage.words + for (range in ranges) { + // the passage is in order and can span many suras: start at the page's first word + var index = firstAtOrAfter(state, range.startSura, range.startAyah) + while (index < words.size) { + val id = words[index].id + if (compare(id.sura, id.ayah, range.endingSura, range.endingAyah) > 0) break + // all the passage words of this ayah + var end = index + while (end < words.size && words[end].id.sura == id.sura && words[end].id.ayah == id.ayah) end++ + val ayahWords = index until end + if (ayahWords.all { state.isHidden(it) }) { + marks += Mark(id.sura, id.ayah, -1, MemorizeHighlightTypes.HIDDEN) + } else { + for (i in ayahWords) { + val word = words[i].id.word + when { + state.isHidden(i) -> marks += Mark(id.sura, id.ayah, word, MemorizeHighlightTypes.HIDDEN) + i in state.hinted -> marks += Mark(id.sura, id.ayah, word, MemorizeHighlightTypes.HINTED) + i in state.missed -> marks += Mark(id.sura, id.ayah, word, MemorizeHighlightTypes.MISSED) + } + } + } + state.mistake?.takeIf { it in ayahWords && state.isHidden(it) }?.let { + marks += Mark(id.sura, id.ayah, words[it].id.word, MemorizeHighlightTypes.MISTAKE) + } + index = end + } + } + return marks + } + + /** + * Reading: a light trail on every word read since the user started (where the session follows + * them), hinted words, and, if [MemorizeState.showMistakes], the words skipped and the mistake + * being made. + */ + private fun recitation(state: MemorizeState, ranges: Collection): Set { + val marks = HashSet() + val words = state.passage.words + for (range in ranges) { + var index = firstAtOrAfter(state, range.startSura, range.startAyah) + while (index < words.size) { + val id = words[index].id + if (compare(id.sura, id.ayah, range.endingSura, range.endingAyah) > 0) break + val type = when { + index == state.mistake && state.showMistakes -> MemorizeHighlightTypes.MISTAKE + !state.started || index < state.firstWord || index >= state.cursor -> null + index in state.hinted -> MemorizeHighlightTypes.HINTED + index in state.missed -> if (state.showMistakes) MemorizeHighlightTypes.MISSED else MemorizeHighlightTypes.RECITED + else -> MemorizeHighlightTypes.RECITED + } + if (type != null) marks += Mark(id.sura, id.ayah, id.word, type) + index++ + } + } + return marks + } + + /** The index of the first passage word in or after sura:ayah (the passage size if none). */ + private fun firstAtOrAfter(state: MemorizeState, sura: Int, ayah: Int): Int { + val words = state.passage.words + var low = 0 + var high = words.size + while (low < high) { + val mid = (low + high) ushr 1 + val id = words[mid].id + if (compare(id.sura, id.ayah, sura, ayah) < 0) low = mid + 1 else high = mid + } + return low + } + + private fun compare(sura: Int, ayah: Int, otherSura: Int, otherAyah: Int): Int = + if (sura != otherSura) sura.compareTo(otherSura) else ayah.compareTo(otherAyah) +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeNoOpPresenters.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeNoOpPresenters.kt new file mode 100644 index 0000000000..66d3839ef8 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeNoOpPresenters.kt @@ -0,0 +1,12 @@ +package com.quran.mobile.feature.memorize.presenter + +import com.quran.data.di.QuranPageScope +import com.quran.recitation.presenter.RecitationPopupPresenter +import com.quran.recitation.presenter.RecitationPopupPresenter.PopupContainer +import dev.zacsweers.metro.Inject + +@QuranPageScope +class MemorizePopupPresenter @Inject constructor() : RecitationPopupPresenter { + override fun bind(what: PopupContainer) {} + override fun unbind(what: PopupContainer) {} +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizePlaybackPresenter.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizePlaybackPresenter.kt new file mode 100644 index 0000000000..e0b806fe46 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizePlaybackPresenter.kt @@ -0,0 +1,86 @@ +package com.quran.mobile.feature.memorize.presenter + +import android.app.Activity +import com.quran.data.di.ActivityScope +import com.quran.data.model.SuraAyah +import com.quran.mobile.feature.memorize.recording.RecordingPlayer +import com.quran.mobile.feature.memorize.recording.SessionPlayback +import com.quran.mobile.feature.memorize.session.MemorizeSessionController +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.recitation.common.RecitedAyah +import com.quran.recitation.common.RecitedSection +import com.quran.recitation.events.RecitationPlaybackEventPresenter +import com.quran.recitation.events.RecitationSelection +import com.quran.recitation.presenter.RecitationPlaybackPresenter +import dev.zacsweers.metro.Inject +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach + +/** + * Plays back the session's own recording (when the user chose to record) from the audio bar, once + * listening is paused: the page follows the ayah being heard. + */ +@ActivityScope +class MemorizePlaybackPresenter @Inject constructor( + private val controller: MemorizeSessionController, + private val sessionPlayback: SessionPlayback, + private val player: RecordingPlayer, + private val playbackEvents: RecitationPlaybackEventPresenter, +) : RecitationPlaybackPresenter { + + private val selection = MutableStateFlow(RecitationSelection.None) + override val recitationPlaybackFlow: StateFlow = selection.asStateFlow() + + private var scope: CoroutineScope? = null + private var sessionRecordingId: String? = null + + override fun bind(what: Activity) { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + this.scope = scope + player.playback + .onEach { playback -> + val ofSession = playback != null && playback.recording.id == controller.state.value?.recordingId + playbackEvents.onPlayingStateChange(ofSession && playback?.isPlaying == true) + if (playback != null && ofSession) { + val ayah = playback.recording.ayahAt(playback.positionMs) + if (ayah != selection.value.ayah()) selection.value = RecitationSelection.Ayah(PlayedAyah(ayah)) + } + } + .launchIn(scope) + controller.state + .onEach { state -> + // listening again, or the session is over: the playback of its recording stops + val playing = player.playback.value?.recording?.id + val ofSession = state?.recordingId ?: sessionRecordingId + if (playing != null && playing == ofSession && (state == null || state.status == MemorizeState.Status.LISTENING)) { + player.stop() + playbackEvents.onPlayingStateChange(false) + } + sessionRecordingId = state?.recordingId + } + .launchIn(scope) + } + + override fun unbind(what: Activity) { + // the screen is going away: don't keep talking in the background + player.pause() + scope?.cancel() + scope = null + } + + override fun play() = sessionPlayback.play() + + override fun pauseIfPlaying() = player.pause() + + private class PlayedAyah(private val ayah: SuraAyah) : RecitedAyah { + override fun ayah(): SuraAyah = ayah + override fun recitedSections(): List = emptyList() + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeRecitationPresenter.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeRecitationPresenter.kt new file mode 100644 index 0000000000..ae3ca863ee --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeRecitationPresenter.kt @@ -0,0 +1,475 @@ +package com.quran.mobile.feature.memorize.presenter + +import android.Manifest +import android.app.Activity +import android.app.AlertDialog +import android.content.pm.PackageManager +import android.os.Build +import android.text.format.Formatter +import android.widget.CheckBox +import android.widget.FrameLayout +import android.widget.ProgressBar +import android.widget.Toast +import androidx.core.app.ActivityCompat +import androidx.core.content.ContextCompat +import com.quran.data.core.QuranInfo +import com.quran.data.di.QuranScope +import com.quran.data.model.SuraAyah +import com.quran.data.model.audio.Qari +import com.quran.mobile.feature.memorize.R +import com.quran.mobile.feature.memorize.check.DoubleCheckAdvice +import com.quran.mobile.feature.memorize.check.DoubleCheckModel +import com.quran.mobile.feature.memorize.model.SpeechModelStore +import com.quran.mobile.feature.memorize.prompt.HintVoiceDownloads +import com.quran.mobile.feature.memorize.prompt.PromptPlayer +import com.quran.mobile.feature.memorize.recording.RecordingPlayer +import com.quran.mobile.feature.memorize.recording.SessionPlayback +import com.quran.mobile.feature.memorize.service.MemorizeService +import com.quran.mobile.feature.memorize.session.MemorizeSessionController +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.mobile.feature.memorize.settings.MemorizePreferences +import com.quran.mobile.feature.memorize.ui.MicButtonState +import com.quran.mobile.feature.memorize.ui.ModeSheet +import com.quran.mobile.feature.memorize.ui.ModeSheetState +import com.quran.mobile.common.ui.core.R as CoreR +import com.quran.recitation.presenter.RecitationPresenter +import com.quran.recitation.presenter.RecitationStart +import dev.zacsweers.metro.Inject +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.lang.ref.WeakReference + +/** + * Starts and controls memorization sessions from the reading screen ("Memorize" / "Recite from + * here" / the audio bar's microphone). + */ +@QuranScope +class MemorizeRecitationPresenter @Inject constructor( + private val controller: MemorizeSessionController, + private val models: SpeechModelStore, + private val preferences: MemorizePreferences, + private val promptPlayer: PromptPlayer, + private val voiceDownloads: HintVoiceDownloads, + private val recordingPlayer: RecordingPlayer, + private val sessionPlayback: SessionPlayback, + private val quranInfo: QuranInfo, + private val doubleCheck: DoubleCheckModel, + private val doubleCheckAdvice: DoubleCheckAdvice, +) : RecitationPresenter { + + private val enabled = MutableStateFlow(true) + private var activityRef = WeakReference(null) + private var scope: CoroutineScope? = null + private var pendingStart: (() -> SuraAyah)? = null + private var pendingMode = MemorizeState.Mode.MEMORIZE + private var voiceChecked = false + // whether to record the session about to start (null: not decided yet) + private var pendingRecord: Boolean? = null + private var serviceSessionId: String? = null + private var downloadDialog: AlertDialog? = null + private var micButton: FloatingMicButton? = null + // from the reading screen: the pages on screen and how to start a session there + private var pagesOnScreen: () -> List = { emptyList() } + private var startOnScreen: (RecitationStart) -> Unit = {} + + override fun bind(what: Activity) { + activityRef = WeakReference(what) + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + this.scope = scope + controller.state + .onEach { state -> + // keeps listening with the screen off; started once the session exists, while it's visible + if (state != null && state.isActive && state.id != serviceSessionId) { + serviceSessionId = state.id + activityRef.get()?.let { MemorizeService.start(it) } + } + } + .launchIn(scope) + controller.failures + .onEach { activityRef.get()?.let { Toast.makeText(it, R.string.memorize_start_failed, Toast.LENGTH_LONG).show() } } + .launchIn(scope) + + // a clear way to pause, resume and end the session, wherever the user is on the page + val micButton = FloatingMicButton( + activity = what, + preferences = preferences, + onToggle = { if (controller.state.value == null) startOnScreen(RecitationStart.CHOOSE) else controller.pauseOrResume() }, + onChooseMode = { startOnScreen(RecitationStart.CHOOSE_ALL) }, + onEnd = ::endSession, + onReplay = { if (sessionPlayback.isPlaying) sessionPlayback.pause() else sessionPlayback.play() }, + ).also { it.attach() } + this.micButton = micButton + combine(controller.state, recordingPlayer.playback) { state, playback -> + // before a session too: it is how a session starts + if (state == null) { + MicButtonState(idle = true, listening = false, preparing = false, recording = false, canReplay = false, replaying = false) + } else state.let { + MicButtonState( + idle = false, + listening = it.status == MemorizeState.Status.LISTENING || it.status == MemorizeState.Status.PREPARING, + preparing = it.status == MemorizeState.Status.PREPARING, + recording = it.recordingId != null, + canReplay = it.recordingId != null, + replaying = playback?.isPlaying == true && playback.recording.id == it.recordingId, + reciting = it.mode == MemorizeState.Mode.RECITE, + ) + } + } + .onEach { micButton.show(it) } + .launchIn(scope) + } + + override fun unbind(what: Activity) { + if (activityRef.get() === what) activityRef.clear() + micButton?.detach() + micButton = null + // a model download carries on; the dialog shows it again on the next start + downloadDialog?.dismiss() + downloadDialog = null + scope?.cancel() + scope = null + // Nothing of the reading screen may outlive it. This presenter can: the audio bar's collectors + // keep it (they are never cancelled), and through these the whole screen with its pages + // (31 MB a screen, found with LeakCanary). + pagesOnScreen = { emptyList() } + startOnScreen = {} + pendingStart = null + // the session itself keeps running (e.g. with the screen off during salah) + } + + override fun isRecitationEnabled(): Boolean = true + + override fun isRecitationEnabledFlow(): StateFlow = enabled + + // memorization keeps no transcript + override fun supportsTranscript(): Boolean = false + + // the user's own recording, when they chose to record the session + override fun supportsPlayback(): Boolean = controller.state.value?.recordingId != null + + override fun supportsHints(): Boolean = true + + // nothing is hidden while reading with the text shown + override fun supportsAyahVisibility(): Boolean = controller.state.value?.mode != MemorizeState.Mode.RECITE + + override fun onHintRequested() = controller.requestHint() + + override fun setReadingScreen(pagesOnScreen: () -> List, start: (RecitationStart) -> Unit) { + this.pagesOnScreen = pagesOnScreen + startOnScreen = start + } + + /** + * Where the user may start: anywhere from [PAGES_AROUND] pages before the page(s) on screen to as + * many after (null without a reading screen). + */ + private fun startPages(): IntRange? { + val pages = pagesOnScreen().takeIf { it.isNotEmpty() } ?: return null + return maxOf(1, pages.min() - PAGES_AROUND)..minOf(quranInfo.numberOfPages, pages.max() + PAGES_AROUND) + } + + private fun firstAyah(page: Int) = quranInfo.getVerseRangeForPage(page).let { SuraAyah(it.startSura, it.startAyah) } + + private fun lastAyah(page: Int) = quranInfo.getVerseRangeForPage(page).let { SuraAyah(it.endingSura, it.endingAyah) } + + override fun startOrStopRecitation(startAyah: () -> SuraAyah, start: RecitationStart) { + val state = controller.state.value + if (state != null && state.isActive) { + controller.pauseOrResume() + return + } + if (state?.status == MemorizeState.Status.FINISHED) { + endSession() + } + pendingStart = startAyah + voiceChecked = false + pendingRecord = null + when (start) { + RecitationStart.DEFAULT -> { + pendingMode = MemorizeState.Mode.MEMORIZE + proceed() + } + RecitationStart.CHOOSE -> chooseMode(MemorizeState.Mode.MEMORIZE, MemorizeState.Mode.RECITE) + RecitationStart.CHOOSE_ALL -> chooseMode(MemorizeState.Mode.MEMORIZE, MemorizeState.Mode.RECITE, MemorizeState.Mode.SALAH) + } + } + + /** + * The mode window: memorize (the page hidden) or recite (the text shown), and salah after a long + * press. With "Record my recitation" asking each time, the user decides there. + */ + private fun chooseMode(vararg modes: MemorizeState.Mode) { + val activity = activityRef.get() ?: return + val start = pendingStart?.invoke() ?: return + val names = activity.resources.getStringArray(CoreR.array.sura_names) + val position = activity.getString(R.string.memorize_sheet_position, names.getOrElse(start.sura - 1) { "${start.sura}" }, start.ayah) + val record = when { + preferences.contribute -> ModeSheetState.RecordLine.Contributing + preferences.recordingMode == MemorizePreferences.RecordingMode.ALWAYS -> ModeSheetState.RecordLine.Always + preferences.recordingMode == MemorizePreferences.RecordingMode.ASK -> ModeSheetState.RecordLine.Ask + else -> ModeSheetState.RecordLine.Off + } + ModeSheet.show( + activity, + ModeSheetState(position, modes.toList(), record), + onChoose = { mode, recordThis -> + pendingMode = mode + // decided in the window: no need to ask again + if (record == ModeSheetState.RecordLine.Ask) pendingRecord = recordThis + proceed() + }, + onCancel = { pendingStart = null }, + ) + } + + override fun endSession() { + controller.stop() + activityRef.get()?.let { MemorizeService.stop(it) } + } + + override fun onRequestPermissionsResult(requestCode: Int, grantResults: IntArray) { + if (requestCode != REQUEST_PERMISSIONS) return + if (grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) { + proceed() + } else { + activityRef.get()?.let { + Toast.makeText(it, R.string.memorize_microphone_denied, Toast.LENGTH_LONG).show() + } + pendingStart = null + } + } + + /** Walks through the one-time steps (disclaimer, model, permission) and then starts. */ + private fun proceed() { + val activity = activityRef.get() ?: return + val start = pendingStart ?: return + when { + !preferences.disclaimerAccepted -> showDisclaimer(activity) + !models.isInstalled() -> when { + models.isDownloading -> showDownload(activity) + preferences.autoDownload -> { + models.startDownload() + showDownload(activity) + } + else -> offerModelDownload(activity) + } + !hasMicrophonePermission(activity) -> requestPermissions(activity) + !voiceChecked -> { + // the double-check is turned on but not downloaded: with automatic downloads, now (the + // session doesn't wait for it) + if (preferences.autoDownload && preferences.doubleCheck && !doubleCheck.isInstalled) { + doubleCheck.store.startDownload() + } + voiceChecked = true + // with automatic downloads, the session downloads the suras it reaches on its own + if (preferences.autoDownload) proceed() else checkHintVoice(activity, start()) + } + // "Record and contribute" records every session + pendingRecord == null && preferences.contribute -> { + pendingRecord = true + proceed() + } + pendingRecord == null -> when (preferences.recordingMode) { + MemorizePreferences.RecordingMode.OFF -> { + pendingRecord = false + proceed() + } + MemorizePreferences.RecordingMode.ALWAYS -> { + pendingRecord = true + proceed() + } + MemorizePreferences.RecordingMode.ASK -> askToRecord(activity) + } + else -> { + pendingStart = null + // the user is expected where they asked to start (the page on screen, or an ayah they chose) + val home = start() + val pages = startPages() + val record = pendingRecord == true + val contribute = preferences.contribute + if (pages == null) { + controller.start(home, pendingMode, record = record, contribute = contribute) + } else { + val first = firstAyah(pages.first).takeIf { it <= home } ?: home + controller.start( + first, pendingMode, record = record, startAnywhereUntil = lastAyah(pages.last), home = home, + contribute = contribute, + ) + } + if (pendingMode == MemorizeState.Mode.SALAH) { + // recognition degrades with distance and room echo: keep the phone close + Toast.makeText(activity, R.string.memorize_salah_placement, Toast.LENGTH_LONG).show() + } + } + } + } + + /** Offers to download the sura (or the whole Quran) in the hint voice so hints can be spoken offline. */ + private fun checkHintVoice(activity: Activity, start: SuraAyah) { + val qari = voiceDownloads.voice() + if (!preferences.speaksHints(pendingMode) || qari == null) { + proceed() + return + } + val scope = scope ?: return + scope.launch { + // reads the reciter's timings and files + val (status, missing) = withContext(Dispatchers.IO) { + promptPlayer.voiceStatus(qari.id, start.sura) to voiceDownloads.missing() + } + if (activityRef.get() !== activity) return@launch + if (status == PromptPlayer.VoiceStatus.AUDIO_MISSING) { + val size = withContext(Dispatchers.IO) { voiceDownloads.size(missing) } + offerVoiceDownload(activity, qari, start, missing, size) + } else { + proceed() + } + } + } + + private fun offerVoiceDownload(activity: Activity, qari: Qari, start: SuraAyah, missing: List, size: Long?) { + val whole = if (size != null) { + activity.getString(R.string.memorize_voice_download_all_size, Formatter.formatShortFileSize(activity, size)) + } else { + activity.getString(R.string.memorize_voice_download_all) + } + AlertDialog.Builder(activity) + .setTitle(R.string.memorize_voice_download_title) + .setMessage(activity.getString(R.string.memorize_voice_download_message, activity.getString(qari.nameResource))) + .setPositiveButton(R.string.memorize_voice_download_sura) { _, _ -> + voiceDownloads.download(listOf(start.sura)) + proceed() + } + .setNeutralButton(whole) { _, _ -> + voiceDownloads.download(missing) + proceed() + } + .setNegativeButton(R.string.memorize_voice_download_skip) { _, _ -> proceed() } + .setOnCancelListener { pendingStart = null } + .show() + } + + private fun askToRecord(activity: Activity) { + AlertDialog.Builder(activity) + .setTitle(R.string.memorize_record_ask_title) + .setMessage(R.string.memorize_record_ask_message) + .setPositiveButton(R.string.memorize_record_ask_yes) { _, _ -> + pendingRecord = true + proceed() + } + .setNegativeButton(R.string.memorize_record_ask_no) { _, _ -> + pendingRecord = false + proceed() + } + .setOnCancelListener { pendingStart = null } + .show() + } + + private fun showDisclaimer(activity: Activity) { + AlertDialog.Builder(activity) + .setTitle(R.string.memorize_title) + .setMessage(R.string.memorize_disclaimer) + .setPositiveButton(R.string.memorize_disclaimer_accept) { _, _ -> + preferences.disclaimerAccepted = true + proceed() + } + .setNegativeButton(android.R.string.cancel) { _, _ -> pendingStart = null } + .show() + } + + private fun offerModelDownload(activity: Activity) { + val sizeMb = models.spec.downloadSize / 1_000_000 + // where it suits the phone, the double-check is offered with it (off by default: a download) + val offerCheck = !doubleCheck.isInstalled && doubleCheckAdvice.advice().recommended + val withCheck = CheckBox(activity).apply { + text = activity.getString( + R.string.memorize_double_check_offer, + Formatter.formatShortFileSize(activity, DoubleCheckModel.SPEC.downloadSize), + ) + isChecked = preferences.doubleCheck + } + AlertDialog.Builder(activity) + .setTitle(R.string.memorize_model_title) + .setMessage(activity.getString(R.string.memorize_model_message, sizeMb, models.spec.attribution, models.spec.license)) + .apply { + if (offerCheck) { + setView(FrameLayout(activity).apply { setPadding(48, 8, 48, 0); addView(withCheck) }) + } + } + .setPositiveButton(R.string.memorize_model_download) { _, _ -> + models.startDownload() + if (offerCheck && withCheck.isChecked) { + preferences.doubleCheck = true + doubleCheck.store.startDownload() + } + showDownload(activity) + } + .setNegativeButton(android.R.string.cancel) { _, _ -> pendingStart = null } + .show() + } + + /** Shows the model download's progress, and goes on with the start once it is installed. */ + private fun showDownload(activity: Activity) { + val scope = scope ?: return + val progress = ProgressBar(activity, null, android.R.attr.progressBarStyleHorizontal).apply { + max = 1000 + setPadding(48, 24, 48, 0) + } + val dialog = AlertDialog.Builder(activity) + .setTitle(R.string.memorize_model_downloading) + .setView(progress) + .setCancelable(false) + .setNegativeButton(android.R.string.cancel) { _, _ -> + models.cancelDownload() + pendingStart = null + } + .show() + downloadDialog = dialog + scope.launch { + val result = models.state + .onEach { state -> + if (state is SpeechModelStore.State.Downloading && state.totalBytes > 0) { + progress.progress = (1000 * state.downloadedBytes / state.totalBytes).toInt() + } + } + .first { it !is SpeechModelStore.State.Downloading } + dialog.dismiss() + if (downloadDialog === dialog) downloadDialog = null + when (result) { + is SpeechModelStore.State.Installed -> proceed() + is SpeechModelStore.State.Failed -> { + Toast.makeText(activity, activity.getString(R.string.memorize_model_failed, result.reason), Toast.LENGTH_LONG).show() + pendingStart = null + } + else -> pendingStart = null + } + } + } + + private fun hasMicrophonePermission(activity: Activity) = + ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED + + private fun requestPermissions(activity: Activity) { + val permissions = buildList { + add(Manifest.permission.RECORD_AUDIO) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) add(Manifest.permission.POST_NOTIFICATIONS) + } + ActivityCompat.requestPermissions(activity, permissions.toTypedArray(), REQUEST_PERMISSIONS) + } + + private companion object { + const val REQUEST_PERMISSIONS = 4242 + /** Pages before and after the one on screen where the user may start. */ + const val PAGES_AROUND = 3 + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeRecitationSettings.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeRecitationSettings.kt new file mode 100644 index 0000000000..3e17a91adc --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeRecitationSettings.kt @@ -0,0 +1,20 @@ +package com.quran.mobile.feature.memorize.presenter + +import com.quran.data.di.AppScope +import com.quran.mobile.feature.memorize.session.MemorizeSessionController +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.recitation.presenter.RecitationSettings +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn + +@SingleIn(AppScope::class) +class MemorizeRecitationSettings @Inject constructor( + private val controller: MemorizeSessionController, +) : RecitationSettings { + override fun isRecitationEnabled(): Boolean = true + + /** The audio bar's "hide/show verses" button: peek at the hidden words and back. */ + override fun toggleAyahVisibility() { + if (controller.state.value?.mode != MemorizeState.Mode.RECITE) controller.togglePeek() + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/prompt/HintVoice.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/prompt/HintVoice.kt new file mode 100644 index 0000000000..1375df8d7f --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/prompt/HintVoice.kt @@ -0,0 +1,24 @@ +package com.quran.mobile.feature.memorize.prompt + +import com.quran.mobile.feature.memorize.tracker.WordId + +/** Speaks the words given as a hint. */ +interface HintVoice { + /** The audio of some words, ready to be played. */ + interface Clip + + /** + * Finds the audio of [words] (consecutive words of one sura) in the voice of [qariId], or null if + * there is none to play. Reads files: call it off the main thread. + */ + fun prepare(qariId: Int, words: List): Clip? + + /** + * Called on the main thread. [onFinished] is called on the main thread when the clip has been + * played, and never if [stop] or another [play] cuts it short. + */ + fun play(clip: Clip, onStarted: () -> Unit, onFinished: () -> Unit) + + /** Stops speaking, without calling onFinished. */ + fun stop() +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/prompt/HintVoiceDownloads.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/prompt/HintVoiceDownloads.kt new file mode 100644 index 0000000000..a9c480a11f --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/prompt/HintVoiceDownloads.kt @@ -0,0 +1,63 @@ +package com.quran.mobile.feature.memorize.prompt + +import com.quran.data.di.AppScope +import com.quran.data.model.audio.Qari +import com.quran.data.source.PageProvider +import com.quran.mobile.common.download.Downloader +import com.quran.mobile.feature.memorize.settings.MemorizePreferences +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + +/** Told which suras a session has loaded, e.g. to download their hint audio ahead of time. */ +fun interface UpcomingSuras { + fun loaded(suras: IntRange) +} + +/** + * Downloads the hint voice's recitation with the app's own audio downloads, so hints can be spoken + * offline: one sura, the whole Quran, or (with automatic downloads on) the suras a session is about + * to reach, without interrupting the user. + */ +@SingleIn(AppScope::class) +class HintVoiceDownloads @Inject constructor( + private val promptPlayer: PromptPlayer, + private val downloader: Downloader, + private val pageProvider: PageProvider, + private val preferences: MemorizePreferences, +) : UpcomingSuras { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + /** The reciter giving the hints, if it exists in the app. */ + fun voice(): Qari? = pageProvider.getQaris().firstOrNull { it.id == preferences.promptQariId } + + /** The suras of [suras] whose audio in the hint voice isn't downloaded. Reads files. */ + fun missing(suras: IntRange = ALL_SURAS): List { + val qari = voice() ?: return emptyList() + return suras.filter { promptPlayer.voiceStatus(qari.id, it) == PromptPlayer.VoiceStatus.AUDIO_MISSING } + } + + /** How much downloading [suras] takes in the hint voice, or null if unknown. Reads files. */ + fun size(suras: List): Long? = voice()?.let { promptPlayer.audioSize(it.id, suras) } + + /** Downloads [suras] in the background; the app's download notification shows the progress. */ + fun download(suras: List) { + val qari = voice() ?: return + if (suras.isNotEmpty()) downloader.downloadCompleteSuras(qari, suras, downloadDatabase = true) + } + + override fun loaded(suras: IntRange) { + if (!preferences.autoDownload || !preferences.correctorEnabled) return + scope.launch { + // e.g. the system not letting a service start: never worth interrupting the session for + runCatching { download(missing(suras)) } + } + } + + companion object { + val ALL_SURAS = 1..114 + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/prompt/PromptPlayer.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/prompt/PromptPlayer.kt new file mode 100644 index 0000000000..fded52037e --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/prompt/PromptPlayer.kt @@ -0,0 +1,172 @@ +package com.quran.mobile.feature.memorize.prompt + +import android.content.Context +import android.net.Uri +import androidx.media3.common.AudioAttributes +import androidx.media3.common.C +import androidx.media3.common.MediaItem +import androidx.media3.common.Player +import androidx.media3.exoplayer.ExoPlayer +import com.quran.data.core.QuranFileManager +import com.quran.data.di.AppScope +import com.quran.data.source.PageProvider +import com.quran.mobile.di.qualifier.ApplicationContext +import com.quran.mobile.feature.memorize.tracker.WordId +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import java.io.File + +/** + * Plays the words given as a hint in a reciter's voice, from the sura files the user downloaded + * for listening. Fully offline: if the sura isn't downloaded (or the timings don't match the file) + * nothing is played and the hint is only shown. The player itself is only used on the main thread. + */ +@SingleIn(AppScope::class) +class PromptPlayer @Inject constructor( + @param:ApplicationContext private val context: Context, + private val quranFileManager: QuranFileManager, + private val pageProvider: PageProvider, +) : HintVoice { + private var player: ExoPlayer? = null + // the clip that is playing: only its end is reported + private var listener: Player.Listener? = null + private val timings = HashMap() + + /** Voices that can have word timings shipped with the app: qari id -> timings asset. */ + private val voices = mapOf( + HUSARY_MURATTAL to "memorize/timings/husary_murattal_wbw_v1.db", + HUSARY_MUALLIM to "memorize/timings/husary_muallim_wbw_v1.db", + HUSARY_MUJAWWAD to "memorize/timings/husary_mujawwad_wbw_v1.db", + ) + + /** Reciters that can give hints: word timings are bundled and the reciter exists in the app. */ + fun availableVoices(): List { + val bundled = context.assets.list("memorize/timings").orEmpty().toSet() + val qaris = pageProvider.getQaris().map { it.id }.toSet() + return voices.filter { (id, asset) -> asset.substringAfterLast('/') in bundled && id in qaris }.keys.toList() + } + + fun voiceName(qariId: Int): Int? = pageProvider.getQaris().firstOrNull { it.id == qariId }?.nameResource + + enum class VoiceStatus { + /** Word timings exist and the sura's audio matches them. */ + READY, + /** No word timings for this reciter. */ + NO_TIMINGS, + /** The sura's audio hasn't been downloaded. */ + AUDIO_MISSING, + /** The downloaded file isn't the recording the timings were made for. */ + AUDIO_MISMATCH, + } + + /** Reads files: call it off the main thread. */ + fun voiceStatus(qariId: Int, sura: Int): VoiceStatus { + val timings = timingsFor(qariId) ?: return VoiceStatus.NO_TIMINGS + val expectedSize = timings.expectedFileSize(sura) ?: return VoiceStatus.NO_TIMINGS + val file = audioFile(qariId, sura) ?: return VoiceStatus.AUDIO_MISSING + return if (file.extension == "mp3" && file.length() != expectedSize) VoiceStatus.AUDIO_MISMATCH else VoiceStatus.READY + } + + /** The size of [suras]' audio in this voice, from its word timings, or null if unknown. Reads files. */ + fun audioSize(qariId: Int, suras: List): Long? { + val timings = timingsFor(qariId) ?: return null + return suras.sumOf { timings.expectedFileSize(it) ?: return null } + } + + override fun prepare(qariId: Int, words: List): HintVoice.Clip? = clip(qariId, words) + + override fun play(clip: HintVoice.Clip, onStarted: () -> Unit, onFinished: () -> Unit) { + stop() + val audio = clip as? FileClip ?: run { + onFinished() + return + } + val player = player ?: ExoPlayer.Builder(context).build().also { + it.setAudioAttributes( + AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_SPEECH).build(), + /* handleAudioFocus= */ false + ) + player = it + } + player.setMediaItem( + MediaItem.Builder() + .setUri(Uri.fromFile(audio.file)) + .setClippingConfiguration( + MediaItem.ClippingConfiguration.Builder() + // a little room on both sides so the word's start and ending are heard completely + .setStartPositionMs(maxOf(0L, audio.span.startMs - LEAD_MS)) + .setEndPositionMs(audio.span.endMs + TAIL_MS) + .build() + ) + .build() + ) + val listener = object : Player.Listener { + override fun onPlaybackStateChanged(playbackState: Int) { + if (playbackState == Player.STATE_ENDED) finished() + } + + override fun onPlayerError(error: androidx.media3.common.PlaybackException) = finished() + + private fun finished() { + player.removeListener(this) + if (this@PromptPlayer.listener === this) this@PromptPlayer.listener = null + onFinished() + } + } + this.listener = listener + player.addListener(listener) + player.prepare() + player.play() + onStarted() + } + + /** Stops the clip that is playing, if any, without calling its onFinished. */ + override fun stop() { + listener?.let { player?.removeListener(it) } + listener = null + player?.stop() + } + + fun release() { + player?.release() + player = null + } + + private class FileClip(val file: File, val span: WordTimings.Span) : HintVoice.Clip + + private fun clip(qariId: Int, words: List): FileClip? { + if (words.isEmpty()) return null + val sura = words.first().sura + // timings are only valid for the exact recording they were measured on + if (voiceStatus(qariId, sura) != VoiceStatus.READY) return null + val file = audioFile(qariId, sura) ?: return null + val span = timingsFor(qariId)?.span(words) ?: return null + return FileClip(file, span) + } + + private fun audioFile(qariId: Int, sura: Int): File? { + val qari = pageProvider.getQaris().firstOrNull { it.id == qariId } ?: return null + val directory = quranFileManager.audioFileDirectory() ?: return null + return listOf("mp3", "opus") + .map { File(directory, "${qari.path}/%03d.$it".format(sura)) } + .firstOrNull { it.exists() } + } + + // called from the session's worker and from the start screen + @Synchronized + private fun timingsFor(qariId: Int): WordTimings? { + if (!timings.containsKey(qariId)) { + timings[qariId] = voices[qariId]?.let { WordTimings.fromAsset(context, it) } + } + return timings[qariId] + } + + companion object { + const val HUSARY_MURATTAL = 1 + // see MadaniPageProvider + const val HUSARY_MUALLIM = 1001 + const val HUSARY_MUJAWWAD = 1002 + private const val LEAD_MS = 60L + private const val TAIL_MS = 120L + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/prompt/WordTimings.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/prompt/WordTimings.kt new file mode 100644 index 0000000000..da64b65ad6 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/prompt/WordTimings.kt @@ -0,0 +1,64 @@ +package com.quran.mobile.feature.memorize.prompt + +import android.content.Context +import android.database.sqlite.SQLiteDatabase +import android.database.sqlite.SQLiteException +import com.quran.mobile.feature.memorize.data.BundledAssets +import com.quran.mobile.feature.memorize.tracker.WordId +import java.io.File +import java.io.IOException + +/** + * Word timings of one reciter's gapless sura files (tools/memorize/align_timing_pack.py): where + * each word starts and ends, and which exact files (by size) they were measured on. + */ +class WordTimings private constructor(private val database: SQLiteDatabase) : AutoCloseable { + + data class Span(val startMs: Long, val endMs: Long) + + /** The size of the sura file the timings were made for, or null if the sura isn't covered. */ + fun expectedFileSize(sura: Int): Long? = + database.rawQuery("SELECT size FROM audio_files WHERE sura = ?", arrayOf(sura.toString())).use { + if (it.moveToFirst()) it.getLong(0) else null + } + + /** The audio span of [words] (consecutive words of one sura), or null if any is unknown. */ + fun span(words: List): Span? { + if (words.isEmpty()) return null + val sura = words.first().sura + if (words.any { it.sura != sura }) return null + val spans = words.map { word(it) ?: return null } + return Span(spans.minOf { it.startMs }, spans.maxOf { it.endMs }) + } + + private fun word(id: WordId): Span? { + val words = database.rawQuery( + "SELECT words FROM timings WHERE sura = ? AND ayah = ?", + arrayOf(id.sura.toString(), id.ayah.toString()) + ).use { if (it.moveToFirst()) it.getString(0) else null } ?: return null + // "word:start:end,word:start:end,..." + for (entry in words.split(',')) { + val parts = entry.split(':') + if (parts.size == 3 && parts[0].toIntOrNull() == id.word) { + return Span(parts[1].toLong(), parts[2].toLong()) + } + } + return null + } + + override fun close() = database.close() + + companion object { + fun fromFile(file: File): WordTimings = + WordTimings(SQLiteDatabase.openDatabase(file.path, null, SQLiteDatabase.OPEN_READONLY)) + + /** Opens timings bundled as an asset, or null if they aren't bundled or can't be opened. */ + fun fromAsset(context: Context, asset: String): WordTimings? = try { + fromFile(BundledAssets.extract(context, asset)) + } catch (_: IOException) { + null + } catch (_: SQLiteException) { + null + } + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/AacFileWriter.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/AacFileWriter.kt new file mode 100644 index 0000000000..d54377e025 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/AacFileWriter.kt @@ -0,0 +1,109 @@ +package com.quran.mobile.feature.memorize.recording + +import android.media.MediaCodec +import android.media.MediaCodecInfo +import android.media.MediaFormat +import android.media.MediaMuxer +import java.io.File +import java.nio.ByteOrder + +/** + * Encodes 16 kHz mono audio to AAC in an .m4a file with the platform's encoder: about 15 MB per hour + * of recitation. Runs on the caller's thread (the recorder's own). + */ +internal class AacFileWriter(private val file: File) : AudioFileWriter { + private val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC) + private val muxer = MediaMuxer(file.path, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4) + private val info = MediaCodec.BufferInfo() + private var track = -1 + private var samples = 0L + private var wroteAudio = false + + init { + val format = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC, SAMPLE_RATE, 1).apply { + setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC) + setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE) + setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, MAX_INPUT_BYTES) + } + try { + codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) + codec.start() + } catch (e: Exception) { + codec.release() + muxer.release() + file.delete() + throw e + } + } + + override fun write(pcm: ShortArray, count: Int) { + var offset = 0 + while (offset < count) { + val index = codec.dequeueInputBuffer(TIMEOUT_US) + if (index < 0) { + drain(endOfStream = false) + continue + } + val buffer = codec.getInputBuffer(index) ?: continue + buffer.clear() + val n = minOf(count - offset, buffer.remaining() / Short.SIZE_BYTES) + buffer.order(ByteOrder.nativeOrder()).asShortBuffer().put(pcm, offset, n) + codec.queueInputBuffer(index, 0, n * Short.SIZE_BYTES, timeUs(), 0) + samples += n + offset += n + drain(endOfStream = false) + } + } + + override fun close(): Boolean { + try { + val index = codec.dequeueInputBuffer(TIMEOUT_US * 10) + if (index >= 0) codec.queueInputBuffer(index, 0, 0, timeUs(), MediaCodec.BUFFER_FLAG_END_OF_STREAM) + drain(endOfStream = true) + codec.stop() + } finally { + codec.release() + if (wroteAudio) runCatching { muxer.stop() } + muxer.release() + } + if (!wroteAudio) file.delete() + return wroteAudio + } + + private fun timeUs() = samples * 1_000_000L / SAMPLE_RATE + + private fun drain(endOfStream: Boolean) { + var idle = 0 + while (true) { + val index = codec.dequeueOutputBuffer(info, if (endOfStream) TIMEOUT_US else 0) + when { + index == MediaCodec.INFO_TRY_AGAIN_LATER -> if (!endOfStream || ++idle > MAX_IDLE_DRAINS) return + index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> { + track = muxer.addTrack(codec.outputFormat) + muxer.start() + } + index >= 0 -> { + val buffer = codec.getOutputBuffer(index) + val config = info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0 + if (buffer != null && !config && info.size > 0 && track >= 0) { + buffer.position(info.offset) + buffer.limit(info.offset + info.size) + muxer.writeSampleData(track, buffer, info) + wroteAudio = true + } + codec.releaseOutputBuffer(index, false) + if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) return + } + } + } + } + + private companion object { + const val SAMPLE_RATE = 16_000 + const val BIT_RATE = 32_000 + const val MAX_INPUT_BYTES = 16 * 1024 + const val TIMEOUT_US = 10_000L + // when finishing: how long (in TIMEOUT_US steps) to wait for the encoder's last output + const val MAX_IDLE_DRAINS = 100 + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/AudioClock.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/AudioClock.kt new file mode 100644 index 0000000000..e6f2975e73 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/AudioClock.kt @@ -0,0 +1,45 @@ +package com.quran.mobile.feature.memorize.recording + +/** + * Where a time of the session's audio is in what was recorded. They differ once the recorder has + * dropped frames (a phone too busy to keep up): the session heard them, the recording doesn't have + * them. Samples at 16 kHz; not thread-safe (the recorder's thread). + */ +internal class AudioClock { + /** Samples of the session's audio accounted for so far, received or dropped. */ + var sessionSamples = 0L + private set + + /** Samples of audio received. */ + var audioSamples = 0L + private set + + // the dropped stretches, in order: where each starts in the session's audio, and its length + private val gapStarts = ArrayList() + private val gapLengths = ArrayList() + + /** The session has reached [sessionSample]: whatever wasn't received before it was dropped. */ + fun reach(sessionSample: Long) { + if (sessionSample <= sessionSamples) return + gapStarts += sessionSamples + gapLengths += sessionSample - sessionSamples + sessionSamples = sessionSample + } + + /** [samples] more were received, right after what the session reached. */ + fun receive(samples: Int) { + sessionSamples += samples + audioSamples += samples + } + + /** Where [sessionSample] is in the received audio; a time in a dropped stretch is at its end. */ + fun toAudio(sessionSample: Long): Long { + var dropped = 0L + for (i in gapStarts.indices) { + val start = gapStarts[i] + if (sessionSample <= start) break + dropped += minOf(gapLengths[i], sessionSample - start) + } + return (sessionSample - dropped).coerceIn(0L, audioSamples) + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordedSessions.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordedSessions.kt new file mode 100644 index 0000000000..0faaeb9564 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordedSessions.kt @@ -0,0 +1,19 @@ +package com.quran.mobile.feature.memorize.recording + +import android.content.Context +import android.content.Intent +import com.quran.data.di.AppScope +import com.quran.mobile.di.RecordedSessionLauncher +import dev.zacsweers.metro.ContributesIntoSet +import dev.zacsweers.metro.Inject + +/** Opens a recorded session in Recording sessions (from Progress's Sessions). */ +@ContributesIntoSet(AppScope::class) +@Inject +class RecordedSessions : RecordedSessionLauncher { + override fun open(context: Context, recordingId: String) { + context.startActivity( + Intent(context, RecordingsActivity::class.java).putExtra(RecordingsActivity.EXTRA_SESSION, recordingId) + ) + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/Recording.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/Recording.kt new file mode 100644 index 0000000000..9b6b8d53e4 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/Recording.kt @@ -0,0 +1,188 @@ +package com.quran.mobile.feature.memorize.recording + +import com.quran.data.model.SuraAyah +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.mobile.feature.memorize.tracker.WordId +import com.quran.mobile.feature.memorize.tracker.engine.RecognizedToken +import java.io.File + +/** + * A recording the user chose to make of their own recitation: one sura of a session, or the whole + * session (see [RecordingSplit]). Each stretch of listening between pauses is its own file, played + * one after the other. [words] align the recitation with the Quran, e.g. for training speech models. + */ +data class Recording( + val id: String, + /** The memorization session it was recorded in. */ + val session: String, + val mode: MemorizeState.Mode, + /** When recording started (wall clock). */ + val startedAt: Long, + val start: SuraAyah, + /** The last ayah reached. */ + val end: SuraAyah, + val parts: List, + /** Every word the session went through, with times in ms from the start of the recording. */ + val words: List, + /** Recorded to help improve the speech models ("Record and contribute"). */ + val contribute: Boolean = false, + /** What the recognizer heard and what the session did ([RecordingDetails]), kept when contributing. */ + val details: File? = null, +) { + data class Part(val file: File, val durationMs: Long) + + data class Word( + val id: WordId, + val startMs: Long?, + val endMs: Long?, + val status: WordStatus, + val phonemes: String, + /** How many times a mistake was marked on it; null in recordings made before this was kept. */ + val mistakes: Int? = 0, + ) + + enum class WordStatus { + /** Recited by the user. */ + RECITED, + /** Given as a hint (spoken by the hint voice). */ + HINTED, + /** Skipped by the user. */ + MISSED, + } + + val durationMs: Long get() = parts.sumOf { it.durationMs } + + val sizeBytes: Long get() = parts.sumOf { it.file.length() } + (details?.length() ?: 0L) + + /** The ayah being recited [positionMs] into the recording. */ + fun ayahAt(positionMs: Long): SuraAyah { + val word = words.lastOrNull { (it.startMs ?: it.endMs ?: Long.MAX_VALUE) <= positionMs } ?: return start + return SuraAyah(word.id.sura, word.id.ayah) + } +} + +/** A session's recordings (one per sura, or one for all of it), in the order they were made. */ +data class RecordingSession(val recordings: List) { + init { + require(recordings.isNotEmpty()) + } + + private val first get() = recordings.first() + + val id: String get() = first.session + val mode: MemorizeState.Mode get() = first.mode + val startedAt: Long get() = first.startedAt + val start: SuraAyah get() = first.start + val end: SuraAyah get() = recordings.last().end + val durationMs: Long get() = recordings.sumOf { it.durationMs } + val sizeBytes: Long get() = recordings.sumOf { it.sizeBytes } + val contribute: Boolean get() = recordings.any { it.contribute } + + private val words get() = recordings.asSequence().flatMap { it.words } + + val recited: Int get() = words.count { it.status == Recording.WordStatus.RECITED } + val hinted: Int get() = words.count { it.status == Recording.WordStatus.HINTED } + val missed: Int get() = words.count { it.status == Recording.WordStatus.MISSED } + /** Words a mistake was marked on (unknown in recordings made before this was kept). */ + val mistakes: Int get() = words.count { (it.mistakes ?: 0) > 0 } +} + +/** + * Something a session did, kept with recordings made to contribute; [atMs] is in the session's audio + * time (as the recognizer's tokens). + */ +data class SessionEvent(val atMs: Long, val kind: Kind, val word: WordId? = null, val detail: String? = null) { + enum class Kind { + /** The voice activity detector heard sound, or silence. */ + SPEECH, + SILENCE, + /** The tracker found the user said something other than [word] (detail: substitution, skip, elsewhere). */ + MISTAKE, + /** A mistake mark was shown on [word], or taken off it. */ + MARK_SHOWN, + MARK_CLEARED, + /** Words were given from [word] on (detail: how many). */ + HINT, + /** The hint voice started or stopped playing (the microphone hears it). */ + PROMPT_STARTED, + PROMPT_ENDED, + /** The user went back to [word] (detail: the last word repeated). */ + REPETITION, + /** A phrase that isn't part of the passage (detail: basmala, takbir...). */ + PHRASE, + /** The double-check listened again for [word] (detail: said or not said, and how long it took). */ + DOUBLE_CHECK, + /** Hints stopped after too many in a row. */ + GAVE_UP, + CALL_STARTED, + CALL_ENDED, + /** Listening was paused by the user (no audio until it resumes). */ + PAUSED, + } +} + +/** How recordings are cut. */ +enum class RecordingSplit { + /** A recording per sura recited in a session. */ + BY_SURA, + /** A recording per session. */ + BY_SESSION, +} + +/** Where a session's audio and progress go when it is being recorded. */ +interface SessionRecorder { + /** Identifies the session's recordings. */ + val session: String + + /** + * Whether it keeps what the recognizer heard and what the session did ([heard], [event]), for + * recordings made to contribute; the caller may skip them otherwise. + */ + val keepsDetails: Boolean + + /** Audio the session heard (16 kHz mono), right after what came before; never blocks. */ + fun write(samples: FloatArray) + + /** + * The session went through [word]; times are in ms of the session's audio (as written), and + * [phonemes] is how the word is pronounced (in the speech model's phonetic script). [endsSura] + * when it is the last word of its sura; [mistakes] how many times a mistake was marked on it. + */ + fun word( + word: WordId, + startMs: Long?, + endMs: Long?, + status: Recording.WordStatus, + phonemes: String, + endsSura: Boolean, + mistakes: Int = 0, + ) + + /** What the recognizer heard; token times are in ms of the session's audio. */ + fun heard(tokens: List) {} + + fun event(event: SessionEvent) {} + + /** Listening paused: what was recorded so far can be played. */ + fun pause() + + /** The session is over. */ + fun finish() +} + +/** Starts recording sessions; replaced by a fake in tests. */ +fun interface Recorders { + /** + * With [contribute], the recordings are marked as made to help improve the speech models and keep + * the session's details; [info] describes the session for them (settings, speech model). + */ + fun start(start: SuraAyah, mode: MemorizeState.Mode, contribute: Boolean, info: Map): SessionRecorder? +} + +/** Writes 16 kHz mono 16-bit audio to a file (encoded, see [AacFileWriter]). */ +interface AudioFileWriter { + fun write(pcm: ShortArray, count: Int) + + /** Finishes the file; true if it holds any audio. */ + fun close(): Boolean +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingDetails.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingDetails.kt new file mode 100644 index 0000000000..6c4333e5c9 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingDetails.kt @@ -0,0 +1,64 @@ +package com.quran.mobile.feature.memorize.recording + +import com.quran.mobile.feature.memorize.tracker.WordId +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.util.Locale + +/** + * What the recognizer heard and what the session did during a recording made to contribute ("Record + * and contribute"), kept next to it as JSON lines (`.heard.jsonl`, `heard.jsonl` in an export): + * ``` + * {"format": "quran-memorize-heard", "version": 1, "recording": "…", "session": "…", "sample_rate": 16000, + * "app_version": "…", "device": "…", "android_sdk": 34, "model": "…", "model_sha256": "…", "settings": {…}} + * ["t", 1240, "بِ", 0.97] a token the recognizer heard: time, text, probability (or null) + * ["e", 2100, "mistake", "67:1:3", "substitution"] an event: time, kind, word (or null), detail (or null) + * ``` + * Times are in ms from the start of the recording's audio, as its words' in the alignment. Tokens + * are the speech model's own output (its phonetic script), before the app compares them with the + * Quran; events are what the app decided from them (see [SessionEvent.Kind], written in lower case). + */ +internal object RecordingDetails { + const val FORMAT = "quran-memorize-heard" + private const val VERSION = 1 + private const val SAMPLES_PER_MS = 16L + + /** A detail at [sample] of the session's recorded audio. */ + sealed interface Item { + val sample: Long + } + + data class Token(override val sample: Long, val text: String, val probability: Float?) : Item + + data class Event(override val sample: Long, val kind: SessionEvent.Kind, val word: WordId?, val detail: String?) : Item + + /** Writes [items] of a recording whose audio starts at [startSample]; replaces the file at once. */ + fun write(file: File, header: JSONObject, items: List, startSample: Long) { + val partial = File(file.path + ".part") + partial.bufferedWriter().use { out -> + out.write(JSONObject(header.toString()).put("format", FORMAT).put("version", VERSION).put("sample_rate", 16_000).toString()) + out.write("\n") + for (item in items.sortedBy { it.sample }) { + val ms = ((item.sample - startSample) / SAMPLES_PER_MS).coerceAtLeast(0) + val line = when (item) { + is Token -> JSONArray().put("t").put(ms).put(item.text).put(item.probability?.toDouble() ?: JSONObject.NULL) + is Event -> JSONArray().put("e").put(ms).put(item.kind.name.lowercase(Locale.US)) + .put(item.word?.let { "${it.sura}:${it.ayah}:${it.word}" } ?: JSONObject.NULL) + .put(item.detail ?: JSONObject.NULL) + } + out.write(line.toString()) + out.write("\n") + } + } + partial.renameTo(file) + } + + /** The header and the lines of a details file, for tests and tools. */ + fun read(file: File): Pair> { + val lines = file.readLines().filter { it.isNotBlank() } + val header = JSONObject(lines.first()) + require(header.getString("format") == FORMAT) + return header to lines.drop(1).map(::JSONArray) + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingExport.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingExport.kt new file mode 100644 index 0000000000..9994bd3321 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingExport.kt @@ -0,0 +1,108 @@ +package com.quran.mobile.feature.memorize.recording + +import android.content.Context +import com.quran.data.model.SuraAyah +import com.quran.mobile.common.ui.core.R as CoreR +import java.io.OutputStream +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream + +/** Names recordings by where they start and end, and exports them for listening or training. */ +object RecordingExport { + + /** E.g. "Al-Mulk 1–15", or "Al-Mulk 1 – Al-Qalam 20" for a session that went on to the next sura. */ + fun label(context: Context, recording: Recording): String = label(context, recording.start, recording.end) + + /** E.g. "Al-Mulk 1–15", from [start] to [end]. */ + fun label(context: Context, start: SuraAyah, end: SuraAyah): String { + val names = context.resources.getStringArray(CoreR.array.sura_names) + val first = names.getOrNull(start.sura - 1) ?: number(start.sura) + return if (start.sura == end.sura) { + "$first ${number(start.ayah)}–${number(end.ayah)}" + } else { + "$first ${number(start.ayah)} – ${names.getOrNull(end.sura - 1) ?: number(end.sura)} ${number(end.ayah)}" + } + } + + // in the user's digits (e.g. Arabic-Indic) + private fun number(value: Int): String = String.format(Locale.getDefault(), "%d", value) + + /** + * Writes [recordings] as a zip: a folder per recording with its audio and alignment (see + * [RecordingFormat]) and, for one made to contribute, its details ([RecordingDetails]), and a NeMo + * manifest of all their whole ayat at the top. Reads files. + */ + fun zip(recordings: List, output: OutputStream) { + ZipOutputStream(output).use { zip -> + val manifest = StringBuilder() + for (recording in recordings) { + val folder = folder(recording) + val path = { part: Recording.Part -> "$folder/${part.file.name.substringAfter('_')}" } + for (part in recording.parts) { + zip.putNextEntry(ZipEntry(path(part))) + part.file.inputStream().use { it.copyTo(zip) } + zip.closeEntry() + } + val details = recording.details?.takeIf { it.isFile } + if (details != null) { + zip.putNextEntry(ZipEntry("$folder/$DETAILS")) + details.inputStream().use { it.copyTo(zip) } + zip.closeEntry() + } + zip.putNextEntry(ZipEntry("$folder/alignment.json")) + val alignment = RecordingFormat.write(recording, detailsPath = details?.let { DETAILS }) { part -> + part.file.name.substringAfter('_') + } + zip.write(alignment.toByteArray()) + zip.closeEntry() + RecordingFormat.manifest(recording, path).forEach { manifest.append(it).append('\n') } + } + zip.putNextEntry(ZipEntry("manifest.jsonl")) + zip.write(manifest.toString().toByteArray()) + zip.closeEntry() + zip.putNextEntry(ZipEntry("README.txt")) + zip.write(README.toByteArray()) + zip.closeEntry() + } + } + + /** A file name for exporting [recordings]. */ + fun fileName(recordings: List): String = + if (recordings.size == 1) "quran-recitation_${folder(recordings[0])}.zip" else "quran-recitations_${stamp(System.currentTimeMillis())}.zip" + + // e.g. 067-001_067-015_20261022-214000 + private fun folder(recording: Recording): String = "%03d-%03d_%03d-%03d_%s".format( + Locale.US, recording.start.sura, recording.start.ayah, recording.end.sura, recording.end.ayah, stamp(recording.startedAt), + ) + + private fun stamp(time: Long) = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date(time)) + + private val README = """ + |Recitation recorded with Quran for Android (Memorize). + | + |Each folder is one recording: its audio (16 kHz mono AAC, .m4a; the files play one after the + |other, one per stretch of listening) and alignment.json, which lists every word the session went + |through with its time in ms from the start of the first file: + | sura, ayah, word where it is in the Quran (join with any Quran text) + | start_ms, end_ms when it was heard (from the on-device recognizer, about 0.1 s) + | status recited (by the reciter), hinted (given by the app) or missed + | phonemes how it is pronounced, in the quran-transcript phonetic script + | mistakes how many times a mistake was marked on it + |A hinted word starts when the app's hint voice started saying it: that voice is in the audio. + | + |heard.jsonl, in recordings made with "Record and contribute": what the speech model heard and + |what the app decided from it, one JSON value per line. The first line describes the session + |(app and model versions, phone, settings); then, with times in ms from the start of the audio: + | ["t", ms, text, probability] a token (phoneme) the model heard, and its confidence + | ["e", ms, kind, "s:a:w", detail] what the app did: mistake, mark_shown, hint, phrase, ... + | + |manifest.jsonl is a NVIDIA NeMo speech recognition manifest: one line per ayah recited entirely, + |with audio_filepath, offset and duration in seconds, and its phonemes as text. Segments end + |before any hint the app gave. + |""".trimMargin() + + private const val DETAILS = "heard.jsonl" +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingFormat.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingFormat.kt new file mode 100644 index 0000000000..ca195b5f7b --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingFormat.kt @@ -0,0 +1,147 @@ +package com.quran.mobile.feature.memorize.recording + +import com.quran.data.model.SuraAyah +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.mobile.feature.memorize.tracker.WordId +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.util.Locale + +/** + * How recordings are saved and exported, e.g. for training speech models. + * + * Alignment (one JSON file per recording): + * ``` + * { "format": "quran-memorize-alignment", "version": 2, "id": "…", "session": "…", + * "mode": "memorize" | "recite" | "salah", "recorded_at_ms": 1761160800000, "sample_rate": 16000, + * "start": "67:1", "end": "67:15", "contribute": false, "heard": "….heard.jsonl", + * "audio": [ { "file": "…_1.m4a", "duration_ms": 61200 }, … ], + * "words": [ { "sura": 67, "ayah": 1, "word": 1, "start_ms": 1240, "end_ms": 1610, + * "status": "recited" | "hinted" | "missed", "phonemes": "…", "mistakes": 0 }, … ] } + * ``` + * The audio files play one after the other (one per stretch of listening); word times count from the + * start of the first. Times come from the on-device recognizer: about a tenth of a second, good + * enough to cut segments or to start a forced alignment. Phonemes are in the speech model's phonetic + * script (quran-transcript); sura:ayah:word joins the words with any Quran text. A hinted word's + * start is when the hint voice started saying it (the audio has the hint in it). `mistakes` is how + * many times a mistake was marked on the word. `contribute` is true when the user recorded it to + * help improve the speech models; `heard` then names its details ([RecordingDetails]). + * + * Version 1 (before 2026-11) had no `contribute`, `heard` or `mistakes`. + * + * Manifest ([manifest]): JSON lines as used by NVIDIA NeMo's speech recognition datasets, one per + * ayah the user recited entirely and within one audio file: + * `{"audio_filepath": "…", "offset": 1.04, "duration": 4.86, "text": "…", "sura": 67, "ayah": 1}`. + */ +internal object RecordingFormat { + private const val FORMAT = "quran-memorize-alignment" + private const val VERSION = 2 + /** Kept around a segment so its first and last sounds aren't cut. */ + private const val PADDING_BEFORE_MS = 200L + private const val PADDING_AFTER_MS = 300L + + fun write( + recording: Recording, + detailsPath: String? = recording.details?.name, + audioPath: (Recording.Part) -> String = { it.file.name }, + ): String = + JSONObject() + .put("format", FORMAT) + .put("version", VERSION) + .put("id", recording.id) + .put("session", recording.session) + .put("mode", recording.mode.name.lowercase(Locale.US)) + .put("recorded_at_ms", recording.startedAt) + .put("sample_rate", 16_000) + .put("start", text(recording.start)) + .put("end", text(recording.end)) + .put("contribute", recording.contribute) + .apply { if (detailsPath != null) put("heard", detailsPath) } + .put("audio", JSONArray(recording.parts.map { JSONObject().put("file", audioPath(it)).put("duration_ms", it.durationMs) })) + .put("words", JSONArray(recording.words.map { word -> + JSONObject() + .put("sura", word.id.sura) + .put("ayah", word.id.ayah) + .put("word", word.id.word) + .put("start_ms", word.startMs ?: JSONObject.NULL) + .put("end_ms", word.endMs ?: JSONObject.NULL) + .put("status", word.status.name.lowercase(Locale.US)) + .put("phonemes", word.phonemes) + .apply { word.mistakes?.let { put("mistakes", it) } } + })) + .toString(1) + + fun read(json: String, directory: File): Recording { + val root = JSONObject(json) + require(root.getString("format") == FORMAT) + val version = root.optInt("version", 1) + val audio = root.getJSONArray("audio") + val words = root.getJSONArray("words") + val mode = root.getString("mode").uppercase(Locale.US) + return Recording( + id = root.getString("id"), + session = root.getString("session"), + // one made by a newer version may have a mode this one doesn't know + mode = MemorizeState.Mode.entries.firstOrNull { it.name == mode } ?: MemorizeState.Mode.MEMORIZE, + startedAt = root.getLong("recorded_at_ms"), + start = ayah(root.getString("start")), + end = ayah(root.getString("end")), + parts = (0 until audio.length()).map { i -> + val part = audio.getJSONObject(i) + Recording.Part(File(directory, part.getString("file")), part.getLong("duration_ms")) + }, + words = (0 until words.length()).map { i -> + val word = words.getJSONObject(i) + Recording.Word( + id = WordId(word.getInt("sura"), word.getInt("ayah"), word.getInt("word")), + startMs = if (word.isNull("start_ms")) null else word.getLong("start_ms"), + endMs = if (word.isNull("end_ms")) null else word.getLong("end_ms"), + status = Recording.WordStatus.valueOf(word.getString("status").uppercase(Locale.US)), + phonemes = word.getString("phonemes"), + mistakes = when { + word.has("mistakes") && !word.isNull("mistakes") -> word.getInt("mistakes") + // not kept before version 2 + version < 2 -> null + else -> 0 + }, + ) + }, + contribute = root.optBoolean("contribute", false), + details = root.optString("heard", "").takeIf { it.isNotEmpty() }?.let { File(directory, it) }?.takeIf { it.isFile }, + ) + } + + /** NeMo manifest lines for the ayat of [recording] recited entirely by the user. */ + fun manifest(recording: Recording, audioPath: (Recording.Part) -> String): List { + // where each part starts and ends in the recording + val bounds = recording.parts.runningFold(0L) { start, part -> start + part.durationMs } + // when the hint voice started (a hinted word's start) + val hintStarts = recording.words.filter { it.status == Recording.WordStatus.HINTED }.mapNotNull { it.startMs }.sorted() + return recording.words.groupBy { it.id.sura to it.id.ayah }.mapNotNull { (key, words) -> + if (words.any { it.status != Recording.WordStatus.RECITED || it.startMs == null || it.endMs == null }) return@mapNotNull null + // only a whole ayah: from its first word + if (words.first().id.word != 1) return@mapNotNull null + val start = words.minOf { it.startMs!! } + val end = words.maxOf { it.endMs!! } + val part = (0 until recording.parts.size).firstOrNull { start >= bounds[it] && end <= bounds[it + 1] } + ?: return@mapNotNull null + // the hint voice may start right after (it is in the recording): the segment ends before it + val nextHint = hintStarts.firstOrNull { it >= end } ?: Long.MAX_VALUE + val from = maxOf(bounds[part], start - PADDING_BEFORE_MS) - bounds[part] + val to = minOf(bounds[part + 1], end + PADDING_AFTER_MS, nextHint) - bounds[part] + JSONObject() + .put("audio_filepath", audioPath(recording.parts[part])) + .put("offset", from / 1000.0) + .put("duration", (to - from) / 1000.0) + .put("text", words.joinToString(" ") { it.phonemes }) + .put("sura", key.first) + .put("ayah", key.second) + .toString() + } + } + + private fun text(ayah: SuraAyah) = "${ayah.sura}:${ayah.ayah}" + + private fun ayah(text: String) = text.split(':').let { SuraAyah(it[0].toInt(), it[1].toInt()) } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingPlayer.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingPlayer.kt new file mode 100644 index 0000000000..b21bee46d3 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingPlayer.kt @@ -0,0 +1,138 @@ +package com.quran.mobile.feature.memorize.recording + +import android.content.Context +import android.net.Uri +import androidx.media3.common.AudioAttributes +import androidx.media3.common.C +import androidx.media3.common.MediaItem +import androidx.media3.common.Player +import androidx.media3.exoplayer.ExoPlayer +import com.quran.data.di.AppScope +import com.quran.mobile.di.qualifier.ApplicationContext +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch + +/** Plays the user's recordings back (all of a recording's parts in a row). Main thread only. */ +@SingleIn(AppScope::class) +class RecordingPlayer @Inject constructor( + @param:ApplicationContext private val context: Context, +) { + data class Playback(val recording: Recording, val positionMs: Long, val isPlaying: Boolean) + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private val _playback = MutableStateFlow(null) + /** What is loaded, where it is and whether it's playing; null when nothing is. */ + val playback: StateFlow = _playback.asStateFlow() + + private var player: ExoPlayer? = null + private var ticker: Job? = null + + private val listener = object : Player.Listener { + override fun onIsPlayingChanged(isPlaying: Boolean) = publish() + + override fun onPlaybackStateChanged(playbackState: Int) { + if (playbackState == Player.STATE_ENDED) player?.run { + pause() + seekTo(0, 0) + } + publish() + } + } + + /** Plays [recording], from where it was paused if it is the one loaded. */ + fun play(recording: Recording) { + val player = load(recording) + player.play() + tick() + } + + /** Goes to [positionMs] of [recording] (loading it if needed), playing or not as it was. */ + fun seekTo(recording: Recording, positionMs: Long) { + val player = load(recording) + val (part, offset) = partAt(recording.parts, positionMs) + player.seekTo(part, offset) + _playback.value = Playback(recording, position(recording, player), player.isPlaying) + } + + /** Moves [deltaMs] forward (or back) in what is loaded. */ + fun skip(deltaMs: Long) { + val playback = _playback.value ?: return + seekTo(playback.recording, (playback.positionMs + deltaMs).coerceIn(0, playback.recording.durationMs)) + } + + fun pause() { + player?.pause() + } + + private fun load(recording: Recording): ExoPlayer { + val player = player ?: ExoPlayer.Builder(context).build().also { + it.setAudioAttributes( + AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_SPEECH).build(), + true, + ) + it.addListener(listener) + player = it + } + val loaded = _playback.value?.recording + if (loaded?.id != recording.id || loaded.parts != recording.parts) { + player.setMediaItems(recording.parts.map { MediaItem.fromUri(Uri.fromFile(it.file)) }) + player.prepare() + } + _playback.value = Playback(recording, position(recording, player), player.isPlaying) + return player + } + + fun stop() { + ticker?.cancel() + player?.release() + player = null + _playback.value = null + } + + private fun tick() { + if (ticker?.isActive == true) return + ticker = scope.launch { + while (isActive) { + publish() + delay(TICK_MS) + } + } + } + + private fun publish() { + val player = player ?: return + val recording = _playback.value?.recording ?: return + _playback.value = Playback(recording, position(recording, player), player.isPlaying) + if (!player.isPlaying && player.playbackState != Player.STATE_BUFFERING) ticker?.cancel() + } + + private fun position(recording: Recording, player: ExoPlayer): Long = + recording.parts.take(player.currentMediaItemIndex).sumOf { it.durationMs } + player.currentPosition + + internal companion object { + // often enough for the word being heard to be lit as it is said + private const val TICK_MS = 100L + + /** Which of [parts] (played one after the other) holds [positionMs], and where in it. */ + fun partAt(parts: List, positionMs: Long): Pair { + var start = 0L + parts.forEachIndexed { index, part -> + if (positionMs < start + part.durationMs || index == parts.lastIndex) { + return index to (positionMs - start).coerceIn(0, part.durationMs) + } + start += part.durationMs + } + return 0 to 0L + } + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingStore.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingStore.kt new file mode 100644 index 0000000000..e82ed7f2c9 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingStore.kt @@ -0,0 +1,458 @@ +package com.quran.mobile.feature.memorize.recording + +import android.content.Context +import android.os.Build +import com.quran.data.di.AppScope +import com.quran.data.model.SuraAyah +import com.quran.mobile.di.qualifier.ApplicationContext +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.mobile.feature.memorize.settings.MemorizePreferences +import com.quran.mobile.feature.memorize.tracker.WordId +import com.quran.mobile.feature.memorize.tracker.engine.RecognizedToken +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.suspendCancellableCoroutine +import org.json.JSONObject +import java.io.File +import java.util.UUID +import java.util.concurrent.Executor +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.RejectedExecutionException +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong +import kotlin.coroutines.resume + +/** + * The user's recordings of their own recitation, only made when they turned recording on. They are + * kept in the app's no-backup storage: never backed up, and only leave the phone if the user exports + * them. Each recording is saved as its audio files and an alignment ([RecordingFormat]); one made to + * contribute also keeps what the recognizer heard and what the session did ([RecordingDetails]). + */ +@SingleIn(AppScope::class) +class RecordingStore private constructor( + private val context: Context, + private val preferences: MemorizePreferences, + private val writers: (File) -> AudioFileWriter, + /** Where a session's audio is encoded: one thread per session. */ + private val executors: () -> Executor, + private val clock: () -> Long, +) : Recorders { + @Inject constructor(@ApplicationContext context: Context, preferences: MemorizePreferences) : this( + context, preferences, ::AacFileWriter, { Executors.newSingleThreadExecutor { Thread(it, "memorize-recorder") } }, + System::currentTimeMillis, + ) + + private val directory = File(context.noBackupFilesDir, "memorize/recordings") + private val active = HashMap() + private val _changes = MutableStateFlow(0) + /** Changes whenever a recording is saved or deleted. */ + val changes: StateFlow = _changes.asStateFlow() + + override fun start(start: SuraAyah, mode: MemorizeState.Mode, contribute: Boolean, info: Map): SessionRecorder { + val id = UUID.randomUUID().toString() + val header = if (contribute) JSONObject(info).put("session", id).also { addDeviceInfo(it) } else null + val session = ActiveSession(id, start, mode, preferences.recordingSplit, executors(), header) + synchronized(active) { active[session.session] = session } + return session + } + + /** The saved recordings, newest first. Reads files. */ + fun list(): List = + directory.listFiles { file -> file.name.endsWith(METADATA) }.orEmpty() + .mapNotNull { read(it) } + .sortedByDescending { it.startedAt } + + /** The saved recordings by session, the newest session first. Reads files. */ + fun sessions(): List = + list().groupBy { it.session }.values + .map { RecordingSession(it.sortedBy { recording -> recording.startedAt }) } + .sortedByDescending { it.startedAt } + + /** + * Everything recorded in [session] so far as one recording (all its suras in a row): for a session + * that is paused, up to the pause. Reads files. + */ + suspend fun session(session: String): Recording? { + val recordings = synchronized(active) { active[session] }?.snapshot() + ?: list().filter { it.session == session }.sortedBy { it.startedAt } + return combine(session, recordings) + } + + fun delete(id: String) { + read(File(directory, id + METADATA))?.parts?.forEach { it.file.delete() } + File(directory, id + DETAILS).delete() + File(directory, id + METADATA).delete() + _changes.value++ + } + + /** Deletes all the recordings of [session]. */ + fun deleteSession(session: String) { + list().filter { it.session == session }.forEach { delete(it.id) } + } + + fun deleteAll() { + directory.deleteRecursively() + _changes.value++ + } + + private fun read(file: File): Recording? = + runCatching { RecordingFormat.read(file.readText(), directory) }.getOrNull() + ?.takeIf { recording -> recording.parts.isNotEmpty() && recording.parts.all { it.file.isFile } } + + private fun save(recording: Recording) { + val file = File(directory, recording.id + METADATA) + val partial = File(directory, recording.id + METADATA + ".part") + partial.writeText(RecordingFormat.write(recording)) + partial.renameTo(file) + _changes.value++ + } + + /** + * With "replace the same place", a new recording replaces the older ones of the same start; one + * made to contribute is never deleted that way. + */ + private fun applyRetention(saved: Recording) { + if (preferences.keepRecordings != MemorizePreferences.KeepRecordings.REPLACE_SAME_PLACE) return + list().filter { it.id != saved.id && it.start == saved.start && it.mode == saved.mode && !it.contribute } + .forEach { delete(it.id) } + } + + private fun combine(session: String, recordings: List): Recording? { + if (recordings.isEmpty()) return null + var offset = 0L + val words = ArrayList() + for (recording in recordings) { + recording.words.mapTo(words) { it.copy(startMs = it.startMs?.plus(offset), endMs = it.endMs?.plus(offset)) } + offset += recording.durationMs + } + val first = recordings.first() + return first.copy( + id = session, + end = recordings.last().end, + parts = recordings.flatMap { it.parts }, + words = words, + contribute = recordings.any { it.contribute }, + details = null, + ) + } + + private fun addDeviceInfo(header: JSONObject) { + val version = runCatching { context.packageManager.getPackageInfo(context.packageName, 0).versionName }.getOrNull() + header.put("app_version", version ?: "") + .put("device", "${Build.MANUFACTURER} ${Build.MODEL}") + .put("android_sdk", Build.VERSION.SDK_INT) + } + + /** + * A session being recorded. The last [HOLD_MS] of audio are held back before being written, so + * that a new sura's recording can start just after the previous sura's last word even though the + * recognizer only reports it a moment later. Everything but [write]'s conversion runs on [executor]. + * + * Times come in the session's audio time, counted as [write] is called; the recordings lack the + * frames dropped when the phone couldn't keep up, so they are converted with [AudioClock]. + * + * With [header] the recordings are made to contribute and keep their details ([RecordingDetails]): + * each goes to the recording holding the audio it is about, and a recording's details are written + * once [HOLD_MS] more audio has come (the recognizer reports what it heard a moment later). + */ + private inner class ActiveSession( + override val session: String, + start: SuraAyah, + private val mode: MemorizeState.Mode, + private val split: RecordingSplit, + private val executor: Executor, + private val header: JSONObject?, + ) : SessionRecorder { + private val queued = AtomicInteger() + // the session's audio time, as written (frames dropped below included) + private val sessionSamples = AtomicLong() + + override val keepsDetails: Boolean = header != null + + // on the executor + private val audioClock = AudioClock() + private val held = ArrayDeque() + private var current: Open? = null + private var nextStart = start + private val done = ArrayList() + // recordings closed less than HOLD_MS of audio ago, whose details may still come + private val closing = ArrayList() + // details that came between two recordings: they go to the next one + private val pending = ArrayList() + private var finished = false + + override fun write(samples: FloatArray) { + val at = sessionSamples.getAndAdd(samples.size.toLong()) + // a phone too busy to keep up loses some recording rather than slowing down the listening + if (queued.get() >= MAX_QUEUED_FRAMES) return + val pcm = ShortArray(samples.size) { (samples[it].coerceIn(-1f, 1f) * Short.MAX_VALUE).toInt().toShort() } + queued.incrementAndGet() + submit { + queued.decrementAndGet() + audioClock.reach(at) + held.addLast(Chunk(audioClock.audioSamples, pcm)) + audioClock.receive(pcm.size) + while (held.isNotEmpty() && held.first().endSample <= audioClock.audioSamples - HOLD_SAMPLES) writeChunk(held.removeFirst()) + writeSettledDetails() + } + } + + override fun word( + word: WordId, + startMs: Long?, + endMs: Long?, + status: Recording.WordStatus, + phonemes: String, + endsSura: Boolean, + mistakes: Int, + ) { + val now = sessionSamples.get() + submit { + audioClock.reach(now) + val wordStart = startMs?.let(::audioMs) + val wordEnd = endMs?.let(::audioMs) + val received = audioClock.audioSamples / SAMPLES_PER_MS + val open = current + // a sura the session moved to without its end being heard (e.g. the user skipped ahead) + if (split == RecordingSplit.BY_SURA && open != null && open.words.isNotEmpty() && open.sura != word.sura) { + endRecording(open, wordStart ?: wordEnd ?: received, SuraAyah(word.sura, word.ayah)) + } + val target = current ?: open(held.firstOrNull()?.startSample ?: audioClock.audioSamples) + // a recording starts where the user did (they may start anywhere around the page on screen) + if (target.words.isEmpty()) target.start = SuraAyah(word.sura, word.ayah) + val offset = target.startSample / SAMPLES_PER_MS + target.words += Recording.Word(word, wordStart?.minus(offset), wordEnd?.minus(offset), status, phonemes, mistakes) + target.end = SuraAyah(word.sura, word.ayah) + // the sura's recording ends a little after its last word (the end of a long madd), before + // whatever comes next (the basmala, the next sura, ruku...) + if (split == RecordingSplit.BY_SURA && endsSura && word.sura < LAST_SURA) { + val at = (wordEnd ?: wordStart ?: received) + SPLIT_AFTER_MS + endRecording(target, at, SuraAyah(word.sura + 1, 1)) + } + } + } + + override fun heard(tokens: List) { + if (!keepsDetails || tokens.isEmpty()) return + val now = sessionSamples.get() + submit { + audioClock.reach(now) + for (token in tokens) { + addDetail(RecordingDetails.Token(audioSample(token.timeMs), token.text, token.probability)) + } + } + } + + override fun event(event: SessionEvent) { + if (!keepsDetails) return + val now = sessionSamples.get() + submit { + audioClock.reach(now) + addDetail(RecordingDetails.Event(audioSample(event.atMs), event.kind, event.word, event.detail)) + } + } + + /** Ends [open] at [atMs] of the recorded audio (as far back as is held); [next] starts after it. */ + private fun endRecording(open: Open, atMs: Long, next: SuraAyah) { + while (held.isNotEmpty() && held.first().startSample < atMs * SAMPLES_PER_MS) writeChunk(held.removeFirst()) + close(open) + nextStart = next + } + + override fun pause() { + submit { + while (held.isNotEmpty()) writeChunk(held.removeFirst()) + if (keepsDetails) addDetail(RecordingDetails.Event(audioClock.audioSamples, SessionEvent.Kind.PAUSED, null, null)) + val open = current ?: return@submit + if (open.closePart()) { + save(open.recording()) + writeDetails(open) + } + } + } + + override fun finish() { + submit { + while (held.isNotEmpty()) writeChunk(held.removeFirst()) + current?.let { close(it) } + closing.forEach { writeDetails(it) } + closing.clear() + finished = true + synchronized(active) { active.remove(session) } + (executor as? ExecutorService)?.shutdown() + } + } + + /** What has been recorded so far (after whatever was queued before), or null once it's over. */ + suspend fun snapshot(): List? = suspendCancellableCoroutine { continuation -> + val queuedRun = submit(evenIfFinished = true) { + if (finished) { + continuation.resume(null) + } else { + val open = current?.takeIf { it.parts.isNotEmpty() }?.recording() + continuation.resume(done + listOfNotNull(open)) + } + } + if (!queuedRun) continuation.resume(null) + } + + private fun audioMs(sessionMs: Long): Long = audioSample(sessionMs) / SAMPLES_PER_MS + + private fun audioSample(sessionMs: Long): Long = audioClock.toAudio(sessionMs * SAMPLES_PER_MS) + + /** Gives [item] to the recording holding the audio it is about. */ + private fun addDetail(item: RecordingDetails.Item) { + val open = current + val closed = closing.lastOrNull { item.sample >= it.startSample && item.sample < it.endSample } + when { + closed != null -> closed.details += item + open != null && item.sample >= open.startSample -> open.details += item + // audio of no recording (e.g. one without words, which isn't kept) + open != null || item.sample < (closing.lastOrNull()?.endSample ?: 0L) -> Unit + else -> pending += item + } + } + + /** Writes the details of the recordings closed long enough ago that nothing more will come. */ + private fun writeSettledDetails() { + if (closing.isEmpty()) return + val settled = closing.filter { audioClock.audioSamples >= it.endSample + HOLD_SAMPLES } + settled.forEach { writeDetails(it) } + closing.removeAll(settled) + } + + private fun writeDetails(open: Open) { + val header = header ?: return + runCatching { + RecordingDetails.write( + File(directory, open.id + DETAILS), + JSONObject(header.toString()).put("recording", open.id), + open.details.toList(), + open.startSample, + ) + } + } + + private fun writeChunk(chunk: Chunk) { + val open = current ?: open(chunk.startSample) + open.append(chunk.pcm) + } + + private fun open(startSample: Long): Open { + val open = Open(UUID.randomUUID().toString(), clock(), nextStart, startSample) + current = open + pending.filterTo(open.details) { it.sample >= startSample } + pending.clear() + return open + } + + private fun close(open: Open) { + current = null + open.closePart() + if (open.words.isEmpty()) { + open.parts.forEach { it.file.delete() } + return + } + if (open.parts.isEmpty()) return + val recording = open.recording() + save(recording) + applyRetention(recording) + done += recording + if (keepsDetails) closing += open + } + + /** A recording being written; its times count from [startSample] of the recorded audio. */ + private inner class Open(val id: String, val startedAt: Long, var start: SuraAyah, val startSample: Long) { + val sura: Int get() = start.sura + var end = start + val parts = ArrayList() + val words = ArrayList() + val details = ArrayList() + private var writer: AudioFileWriter? = null + private var file: File? = null + private var partSamples = 0L + private var writtenSamples = 0L + private var failed = false + + /** Where its audio ends in the recorded audio. */ + val endSample: Long get() = startSample + writtenSamples + + fun append(pcm: ShortArray) { + writtenSamples += pcm.size + if (failed) return + val writer = writer ?: try { + directory.mkdirs() + val next = File(directory, "${id}_${parts.size + 1}.m4a") + file = next + writers(next).also { writer = it } + } catch (_: Exception) { + // no encoder on this phone: the session goes on without recording + failed = true + return + } + writer.write(pcm, pcm.size) + partSamples += pcm.size + } + + /** True if a part was added. */ + fun closePart(): Boolean { + val writer = writer ?: return false + this.writer = null + val saved = runCatching { writer.close() }.getOrDefault(false) + val file = file + if (saved && file != null) parts += Recording.Part(file, partSamples / SAMPLES_PER_MS) else file?.delete() + partSamples = 0 + return saved + } + + fun recording() = Recording( + id, session, mode, startedAt, start, end, parts.toList(), words.toList(), + contribute = keepsDetails, + details = if (keepsDetails) File(directory, id + DETAILS) else null, + ) + } + + /** + * Runs [task] on the executor; once the session is over, only if [evenIfFinished] (e.g. a write + * that was on its way when it ended must not open a new recording). False if it can't run. + */ + private fun submit(evenIfFinished: Boolean = false, task: () -> Unit): Boolean = try { + executor.execute { if (evenIfFinished || !finished) task() } + true + } catch (_: RejectedExecutionException) { + false // already finished + } + } + + private class Chunk(val startSample: Long, val pcm: ShortArray) { + val endSample: Long get() = startSample + pcm.size + } + + companion object { + /** A store with its own writers and executors (e.g. running tasks right away), for tests. */ + internal fun forTest( + context: Context, + preferences: MemorizePreferences, + writers: (File) -> AudioFileWriter, + executors: () -> Executor, + clock: () -> Long, + ) = RecordingStore(context, preferences, writers, executors, clock) + + private const val METADATA = ".json" + /** A contributed recording's details ([RecordingDetails]); not ".json", which [list] reads. */ + internal const val DETAILS = ".heard.jsonl" + private const val SAMPLES_PER_MS = 16L + // longer than the recognizer takes to report a word, even on a slow phone + private const val HOLD_MS = 4_000L + private const val HOLD_SAMPLES = HOLD_MS * SAMPLES_PER_MS + /** How long after a sura's last word its recording ends (the end of a long madd). */ + private const val SPLIT_AFTER_MS = 500L + private const val LAST_SURA = 114 + // 30 seconds of 100 ms frames + private const val MAX_QUEUED_FRAMES = 300 + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingsActivity.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingsActivity.kt new file mode 100644 index 0000000000..e45d9790d1 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/RecordingsActivity.kt @@ -0,0 +1,320 @@ +package com.quran.mobile.feature.memorize.recording + +import android.net.Uri +import android.os.Bundle +import android.text.format.DateUtils +import android.text.format.Formatter +import android.widget.Toast +import androidx.activity.compose.BackHandler +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AppCompatActivity +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.runtime.key +import com.quran.labs.androidquran.common.ui.core.WidthClass +import com.quran.labs.androidquran.common.ui.core.widthClassOf +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.lifecycle.lifecycleScope +import com.quran.labs.androidquran.common.ui.core.QuranTheme +import com.quran.mobile.di.QuranApplicationComponentProvider +import com.quran.mobile.feature.memorize.R +import com.quran.mobile.feature.memorize.di.MemorizeComponentInterface +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.recitation.pages.PageRenderer +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.util.Calendar + +/** + * Recording sessions: the user's recorded sessions, by day. A session opens in a window that plays + * it back on its own pages (without going to them in the reader); sessions can be exported (e.g. + * for training) or deleted. [EXTRA_SESSION] opens on one session. + */ +class RecordingsActivity : AppCompatActivity() { + + private val component by lazy { + (application as QuranApplicationComponentProvider).provideQuranApplicationComponent() as MemorizeComponentInterface + } + private val store by lazy { component.recordingStore() } + private val player by lazy { component.recordingPlayer() } + private val quranInfo by lazy { component.quranInfo() } + private var renderer: PageRenderer? = null + private val snackbar = SnackbarHostState() + // deleted, but not yet for good: the user may still undo + private val pendingDeletes = mutableStateListOf() + + // the recordings being exported while the user picks where to + private var exporting: List = emptyList() + private val exporter = registerForActivityResult(ActivityResultContracts.CreateDocument("application/zip")) { uri -> + if (uri != null) export(uri, exporting) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + val renderer = component.pagePreviews().open(this).also { renderer = it } + setContent { + val changes by store.changes.collectAsState() + var sessions by remember { mutableStateOf?>(null) } + LaunchedEffect(changes) { sessions = withContext(Dispatchers.IO) { store.sessions() } } + var openId by rememberSaveable { mutableStateOf(intent.getStringExtra(EXTRA_SESSION)) } + val scope = rememberCoroutineScope() + val shown = sessions?.filter { it.id !in pendingDeletes } + + fun delete(session: RecordingSession) { + if (player.playback.value?.recording?.session == session.id) player.stop() + pendingDeletes += session.id + openId = null + scope.launch { + val result = snackbar.showSnackbar( + message = getString(R.string.memorize_sessions_deleted), + actionLabel = getString(R.string.memorize_sessions_undo), + duration = SnackbarDuration.Long, + ) + if (result == SnackbarResult.ActionPerformed) pendingDeletes -= session.id else commitDelete(session.id) + } + } + + QuranTheme { + BoxWithConstraints { + val width = maxWidth + val wide = widthClassOf(width) == WidthClass.Expanded + // one pane at a time on a phone: Back closes the session; side by side on a wide screen + BackHandler(enabled = openId != null && !wide) { + player.pause() + openId = null + } + if (wide) { + val open = openId?.let { id -> shown?.firstOrNull { it.id == id } } + SessionsSideBySide( + width = width, + list = { + SessionListScreen( + rows = shown?.map { row(it) }, + summary = shown?.takeIf { it.isNotEmpty() }?.let { summary(it) }, + snackbar = snackbar, + onOpen = { id -> + if (id != openId) player.pause() + openId = id + }, + onDelete = { id -> shown?.firstOrNull { it.id == id }?.let { delete(it) } }, + onExportAll = { startExport(shown.orEmpty().flatMap { it.recordings }) }, + onDeleteAll = { + player.stop() + pendingDeletes.clear() + lifecycleScope.launch(Dispatchers.IO) { store.deleteAll() } + }, + onBack = ::finish, + selectedId = open?.id, + ) + }, + session = open?.let { session -> + { + key(session.id) { + SessionWindow(session, renderer, onBack = { + player.pause() + openId = null + }, onDelete = { delete(session) }) + } + } + }, + ) + return@BoxWithConstraints + } + AnimatedContent( + targetState = openId?.let { id -> shown?.firstOrNull { it.id == id } }, + transitionSpec = { fadeIn(tween(200)) togetherWith fadeOut(tween(150)) }, + contentKey = { it?.id }, + label = "sessions", + ) { session -> + if (session == null) { + SessionListScreen( + rows = shown?.map { row(it) }, + summary = shown?.takeIf { it.isNotEmpty() }?.let { summary(it) }, + snackbar = snackbar, + onOpen = { openId = it }, + onDelete = { id -> shown?.firstOrNull { it.id == id }?.let { delete(it) } }, + onExportAll = { startExport(shown.orEmpty().flatMap { it.recordings }) }, + onDeleteAll = { + player.stop() + pendingDeletes.clear() + lifecycleScope.launch(Dispatchers.IO) { store.deleteAll() } + }, + onBack = ::finish, + ) + } else { + SessionWindow(session, renderer, onBack = { + player.pause() + openId = null + }, onDelete = { delete(session) }) + } + } + } + } + } + } + + @androidx.compose.runtime.Composable + private fun SessionWindow(session: RecordingSession, renderer: PageRenderer, onBack: () -> Unit, onDelete: () -> Unit) { + // the whole session as one recording (all its suras in a row) + var recording by remember(session.id) { mutableStateOf(null) } + LaunchedEffect(session.id) { recording = withContext(Dispatchers.IO) { store.session(session.id) } } + val playback by player.playback.collectAsState() + val loaded = recording + val pageOf = remember(session.id) { { word: Recording.Word -> quranInfo.getPageFromSuraAyah(word.id.sura, word.id.ayah) } } + val pages = remember(loaded) { + val words = loaded?.words.orEmpty() + if (words.isEmpty()) { + listOf(quranInfo.getPageFromSuraAyah(session.start.sura, session.start.ayah)) + } else { + val onPages = words.map(pageOf) + (onPages.min()..onPages.max()).toList() + } + } + SessionScreen( + title = RecordingExport.label(this, session.start, session.end), + subtitle = listOf( + modeName(session.mode), + DateUtils.formatDateTime(this, session.startedAt, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME), + ).joinToString(" · "), + recording = loaded, + counts = SessionCounts(session.recited, session.hinted, session.missed, session.mistakes), + pages = pages, + pageOf = pageOf, + playback = playback?.takeIf { it.recording.id == loaded?.id }, + renderer = renderer, + onBack = onBack, + onExport = { startExport(session.recordings) }, + onDelete = onDelete, + onPlay = { loaded?.let { play(it) } }, + onPause = player::pause, + onSeek = { position -> loaded?.let { player.seekTo(it, position) } }, + onSkip = player::skip, + ) + } + + /** Plays [recording]; a session listening now is paused first (the microphone mustn't hear it). */ + private fun play(recording: Recording) { + val controller = component.memorizeSessionController() + if (controller.state.value?.status == MemorizeState.Status.LISTENING) controller.pauseOrResume() + player.play(recording) + } + + override fun onStop() { + super.onStop() + player.pause() + // leaving: what was deleted is deleted + pendingDeletes.toList().forEach { commitDelete(it) } + snackbar.currentSnackbarData?.dismiss() + } + + override fun onDestroy() { + renderer?.close() + renderer = null + super.onDestroy() + } + + private fun commitDelete(session: String) { + pendingDeletes -= session + lifecycleScope.launch(Dispatchers.IO + NonCancellable) { store.deleteSession(session) } + } + + private fun row(session: RecordingSession) = SessionRow( + id = session.id, + mode = session.mode, + title = RecordingExport.label(this, session.start, session.end), + details = listOf( + modeName(session.mode), + DateUtils.formatDateTime(this, session.startedAt, DateUtils.FORMAT_SHOW_TIME), + DateUtils.formatElapsedTime(session.durationMs / 1000), + ).joinToString(" · "), + day = day(session.startedAt), + contributed = session.contribute, + ) + + /** E.g. "12 sessions · 84 MB · Record and contribute is on". */ + private fun summary(sessions: List): String = listOfNotNull( + resources.getQuantityString(R.plurals.memorize_sessions_count, sessions.size, sessions.size), + Formatter.formatShortFileSize(this, sessions.sumOf { it.sizeBytes }), + getString(R.string.memorize_sessions_contribute_on).takeIf { component.memorizePreferences().contribute }, + ).joinToString(" · ") + + private fun modeName(mode: MemorizeState.Mode): String = getString( + when (mode) { + MemorizeState.Mode.MEMORIZE -> R.string.memorize_mode_memorize_title + MemorizeState.Mode.RECITE -> R.string.memorize_mode_recite_title + MemorizeState.Mode.SALAH -> R.string.memorize_mode_salah_title + } + ) + + /** "Today", "Yesterday", or the date. */ + private fun day(time: Long): String { + val today = startOfDay(System.currentTimeMillis()) + val day = startOfDay(time) + return when { + day == today -> getString(R.string.memorize_sessions_today) + today - day in 1..DAY_MS + HOUR_MS -> getString(R.string.memorize_sessions_yesterday) + else -> { + val thisYear = Calendar.getInstance().get(Calendar.YEAR) == Calendar.getInstance().apply { timeInMillis = time }.get(Calendar.YEAR) + val flags = DateUtils.FORMAT_SHOW_WEEKDAY or DateUtils.FORMAT_SHOW_DATE or + (if (thisYear) DateUtils.FORMAT_NO_YEAR else DateUtils.FORMAT_SHOW_YEAR) + DateUtils.formatDateTime(this, time, flags) + } + } + } + + private fun startOfDay(time: Long): Long = Calendar.getInstance().apply { + timeInMillis = time + set(Calendar.HOUR_OF_DAY, 0) + set(Calendar.MINUTE, 0) + set(Calendar.SECOND, 0) + set(Calendar.MILLISECOND, 0) + }.timeInMillis + + private fun startExport(recordings: List) { + if (recordings.isEmpty()) return + exporting = recordings + exporter.launch(RecordingExport.fileName(recordings)) + } + + private fun export(uri: Uri, recordings: List) { + lifecycleScope.launch { + val done = withContext(Dispatchers.IO) { + runCatching { contentResolver.openOutputStream(uri)?.use { RecordingExport.zip(recordings, it) } != null } + .getOrDefault(false) + } + Toast.makeText( + this@RecordingsActivity, + if (done) R.string.memorize_recordings_exported else R.string.memorize_recordings_export_failed, + Toast.LENGTH_LONG, + ).show() + } + } + + companion object { + /** The id of the session to open. */ + const val EXTRA_SESSION = "recording_session" + private const val HOUR_MS = 60 * 60 * 1000L + // a day can be 23 or 25 hours long when the clocks change + private const val DAY_MS = 24 * HOUR_MS + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionListScreen.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionListScreen.kt new file mode 100644 index 0000000000..9f462bc7aa --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionListScreen.kt @@ -0,0 +1,289 @@ +package com.quran.mobile.feature.memorize.recording + +import androidx.compose.foundation.background +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.windowInsetsBottomHeight +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SwipeToDismissBox +import androidx.compose.material3.SwipeToDismissBoxValue +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.rememberSwipeToDismissBoxState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import com.quran.labs.androidquran.common.ui.core.QuranIcons +import com.quran.mobile.feature.memorize.R +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.mobile.feature.memorize.ui.MemorizeIcons +import androidx.appcompat.R as AppCompatR + +/** A recorded session as the list shows it. */ +internal data class SessionRow( + val id: String, + val mode: MemorizeState.Mode, + /** E.g. "Al-Mulk 1–15". */ + val title: String, + /** E.g. "Memorization · 21:40 · 4:12". */ + val details: String, + /** The section it is in, e.g. "Today". */ + val day: String, + val contributed: Boolean, +) + +/** The user's recorded sessions, newest first, by day. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun SessionListScreen( + rows: List?, + /** E.g. "12 sessions · 84 MB · Record and contribute is on". */ + summary: String?, + snackbar: SnackbarHostState, + onOpen: (String) -> Unit, + onDelete: (String) -> Unit, + onExportAll: () -> Unit, + onDeleteAll: () -> Unit, + onBack: () -> Unit, + /** The session open beside the list, on a wide screen. */ + selectedId: String? = null, +) { + var menu by remember { mutableStateOf(false) } + var confirmDeleteAll by remember { mutableStateOf(false) } + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.memorize_sessions_title)) }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + QuranIcons.ArrowBack, + contentDescription = stringResource(AppCompatR.string.abc_action_bar_up_description), + ) + } + }, + actions = { + if (!rows.isNullOrEmpty()) { + Box { + IconButton(onClick = { menu = true }) { + Icon(MemorizeIcons.MoreVert, contentDescription = stringResource(R.string.memorize_sessions_more)) + } + DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + DropdownMenuItem( + text = { Text(stringResource(R.string.memorize_recordings_export_all)) }, + leadingIcon = { Icon(MemorizeIcons.Export, contentDescription = null) }, + onClick = { + menu = false + onExportAll() + }, + ) + DropdownMenuItem( + text = { Text(stringResource(R.string.memorize_recordings_delete_all)) }, + leadingIcon = { Icon(MemorizeIcons.Delete, contentDescription = null) }, + onClick = { + menu = false + confirmDeleteAll = true + }, + ) + } + } + } + }, + ) + }, + snackbarHost = { SnackbarHost(snackbar) }, + ) { padding -> + when { + rows == null -> Unit + rows.isEmpty() -> EmptySessions(Modifier.padding(padding)) + else -> LazyColumn(contentPadding = PaddingValues(top = padding.calculateTopPadding()), modifier = Modifier.fillMaxSize()) { + if (summary != null) { + item(key = "summary") { + Text( + text = summary, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 4.dp), + ) + } + } + rows.groupBy { it.day }.forEach { (day, dayRows) -> + item(key = "day:$day") { + Text( + text = day, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .padding(start = 16.dp, end = 16.dp, top = 20.dp, bottom = 4.dp) + .semantics { heading() }, + ) + } + items(dayRows, key = { it.id }) { row -> + SwipeToDelete(onDelete = { onDelete(row.id) }) { + SessionListRow(row, selected = row.id == selectedId, onClick = { onOpen(row.id) }) + } + } + } + item(key = "end") { Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars)) } + } + } + } + if (confirmDeleteAll) { + AlertDialog( + onDismissRequest = { confirmDeleteAll = false }, + text = { Text(stringResource(R.string.memorize_sessions_delete_all_confirm)) }, + confirmButton = { + TextButton(onClick = { + confirmDeleteAll = false + onDeleteAll() + }) { Text(stringResource(R.string.memorize_recordings_delete_all)) } + }, + dismissButton = { + TextButton(onClick = { confirmDeleteAll = false }) { Text(stringResource(android.R.string.cancel)) } + }, + ) + } +} + +@Composable +private fun SessionListRow(row: SessionRow, selected: Boolean, onClick: () -> Unit) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .background(if (selected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surface) + .selectable(selected = selected, role = Role.Tab, onClick = onClick) + .heightIn(min = 72.dp) + .padding(horizontal = 16.dp, vertical = 12.dp), + ) { + Icon( + modeIcon(row.mode), + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(24.dp), + ) + Spacer(Modifier.width(16.dp)) + Column(modifier = Modifier.weight(1f)) { + Text(row.title, style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurface) + Text( + row.details, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 2.dp), + ) + } + if (row.contributed) { + Spacer(Modifier.width(12.dp)) + Text( + stringResource(R.string.memorize_sessions_contributed), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + ) + } + } +} + +/** Swiping a row away deletes it (with Undo); the session window has a delete button too. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun SwipeToDelete(onDelete: () -> Unit, content: @Composable () -> Unit) { + val state = rememberSwipeToDismissBoxState() + val delete by rememberUpdatedState(onDelete) + LaunchedEffect(state.currentValue) { + if (state.currentValue == SwipeToDismissBoxValue.EndToStart) delete() + } + SwipeToDismissBox( + state = state, + enableDismissFromStartToEnd = false, + backgroundContent = { + Box( + contentAlignment = Alignment.CenterEnd, + modifier = Modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.errorContainer) + .padding(horizontal = 24.dp), + ) { + Icon(MemorizeIcons.Delete, contentDescription = null, tint = MaterialTheme.colorScheme.onErrorContainer) + } + }, + ) { content() } +} + +/** Says how sessions get here. */ +@Composable +private fun EmptySessions(modifier: Modifier = Modifier) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + modifier = modifier + .fillMaxSize() + .padding(horizontal = 28.dp), + ) { + Icon( + MemorizeIcons.GraphicEq, + contentDescription = null, + tint = MaterialTheme.colorScheme.outline, + modifier = Modifier.size(48.dp), + ) + Text( + text = stringResource(R.string.memorize_sessions_empty_title), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = 16.dp), + ) + Text( + text = stringResource(R.string.memorize_sessions_empty_body), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = 8.dp), + ) + } +} + +internal fun modeIcon(mode: MemorizeState.Mode): ImageVector = when (mode) { + MemorizeState.Mode.MEMORIZE -> MemorizeIcons.VisibilityOff + MemorizeState.Mode.RECITE -> QuranIcons.MenuBook + MemorizeState.Mode.SALAH -> MemorizeIcons.Mosque +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionMarks.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionMarks.kt new file mode 100644 index 0000000000..769f8e5116 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionMarks.kt @@ -0,0 +1,51 @@ +package com.quran.mobile.feature.memorize.recording + +import com.quran.mobile.feature.memorize.presenter.Mark +import com.quran.mobile.feature.memorize.presenter.MemorizeHighlightTypes + +/** + * What a recorded session looks like on its pages as it plays back: how each word went (hinted, + * mistaken, skipped) from the start, and once it plays, the word being heard and the trail of + * the words before it. + */ +internal object SessionMarks { + + /** The word being heard [positionMs] into [recording] (its index), if any yet. */ + fun wordAt(recording: Recording, positionMs: Long): Int? { + var current: Int? = null + recording.words.forEachIndexed { index, word -> + val time = word.startMs ?: word.endMs ?: return@forEachIndexed + if (time <= positionMs) current = index + } + return current + } + + /** + * The marks of the words [onPage] keeps; [positionMs] is where the playback is, or null before it + * has started. + */ + fun marks(recording: Recording, positionMs: Long?, onPage: (Recording.Word) -> Boolean): Set { + val playing = positionMs?.let { wordAt(recording, it) } + val marks = HashSet() + recording.words.forEachIndexed { index, word -> + if (!onPage(word)) return@forEachIndexed + val type = when { + index == playing -> MemorizeHighlightTypes.PLAYING + word.status == Recording.WordStatus.HINTED -> MemorizeHighlightTypes.HINTED + (word.mistakes ?: 0) > 0 -> MemorizeHighlightTypes.MISTAKE + word.status == Recording.WordStatus.MISSED -> MemorizeHighlightTypes.MISSED + playing != null && index < playing -> MemorizeHighlightTypes.RECITED + else -> null + } + if (type != null) marks += Mark(word.id.sura, word.id.ayah, word.id.word, type) + } + return marks + } + + /** Where to play from for a tap on [ayah] (and [word] if known): its time, or the ayah's first heard. */ + fun timeOf(recording: Recording, sura: Int, ayah: Int, word: Int?): Long? { + val words = recording.words.filter { it.id.sura == sura && it.id.ayah == ayah } + val tapped = word?.let { position -> words.firstOrNull { it.id.word == position } } + return (tapped?.let { it.startMs ?: it.endMs } ?: words.firstNotNullOfOrNull { it.startMs ?: it.endMs }) + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionPlayback.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionPlayback.kt new file mode 100644 index 0000000000..5ead4533a9 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionPlayback.kt @@ -0,0 +1,42 @@ +package com.quran.mobile.feature.memorize.recording + +import com.quran.data.di.AppScope +import com.quran.mobile.feature.memorize.session.MemorizeSessionController +import com.quran.mobile.feature.memorize.session.MemorizeState +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** Plays back what has been recorded of the current session (from the audio bar or the mic button). */ +@SingleIn(AppScope::class) +class SessionPlayback @Inject constructor( + private val controller: MemorizeSessionController, + private val recordings: RecordingStore, + private val player: RecordingPlayer, +) { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + + /** Whether the current session is being recorded. */ + val canPlay: Boolean get() = controller.state.value?.recordingId != null + + /** Whether the session's recording is playing. */ + val isPlaying: Boolean + get() = player.playback.value?.let { it.isPlaying && it.recording.id == controller.state.value?.recordingId } == true + + fun play() { + val state = controller.state.value ?: return + val session = state.recordingId ?: return + // the microphone mustn't hear the playback + if (state.status == MemorizeState.Status.LISTENING) controller.pauseOrResume() + scope.launch { + val recording = withContext(Dispatchers.IO) { recordings.session(session) } ?: return@launch + player.play(recording) + } + } + + fun pause() = player.pause() +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionScreen.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionScreen.kt new file mode 100644 index 0000000000..f00b727dda --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionScreen.kt @@ -0,0 +1,370 @@ +package com.quran.mobile.feature.memorize.recording + +import android.text.format.DateUtils +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.interaction.collectIsDraggedAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.pager.HorizontalPager +import androidx.compose.foundation.pager.rememberPagerState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilledIconButton +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.VerticalDivider +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.luminance +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.viewinterop.AndroidView +import com.quran.data.model.highlight.HighlightInfo +import com.quran.labs.androidquran.common.ui.core.QuranIcons +import com.quran.mobile.feature.memorize.R +import com.quran.mobile.feature.memorize.presenter.Mark +import com.quran.mobile.feature.memorize.ui.MemorizeIcons +import com.quran.recitation.pages.PageRenderer +import com.quran.recitation.presenter.RecitationHighlightsPresenter.HighlightAction +import androidx.appcompat.R as AppCompatR + +/** How a session went, for the legend under its pages. */ +internal data class SessionCounts(val recited: Int, val hinted: Int, val missed: Int, val mistakes: Int) + +/** + * A recorded session played back on its own pages, without leaving the recordings: the page turns + * with the word being heard, the hints, skipped words and mistakes are marked, and tapping a word + * plays from there. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun SessionScreen( + title: String, + subtitle: String, + /** The whole session as one recording, once read. */ + recording: Recording?, + counts: SessionCounts, + /** The session's pages, in order, and the page each word is on. */ + pages: List, + pageOf: (Recording.Word) -> Int, + /** Where this session's playback is, if it is the one loaded. */ + playback: RecordingPlayer.Playback?, + renderer: PageRenderer?, + onBack: () -> Unit, + onExport: () -> Unit, + onDelete: () -> Unit, + onPlay: () -> Unit, + onPause: () -> Unit, + onSeek: (Long) -> Unit, + onSkip: (Long) -> Unit, +) { + Scaffold( + topBar = { + TopAppBar( + title = { + Column { + Text(title, style = MaterialTheme.typography.titleLarge) + Text(subtitle, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + QuranIcons.ArrowBack, + contentDescription = stringResource(AppCompatR.string.abc_action_bar_up_description), + ) + } + }, + actions = { + IconButton(onClick = onExport) { + Icon(MemorizeIcons.Export, contentDescription = stringResource(R.string.memorize_sessions_export)) + } + IconButton(onClick = onDelete) { + Icon(MemorizeIcons.Delete, contentDescription = stringResource(R.string.memorize_sessions_delete)) + } + }, + ) + }, + ) { padding -> + BoxWithConstraints(modifier = Modifier.padding(padding).fillMaxSize()) { + val pagesView: @Composable (Modifier) -> Unit = { modifier -> + // a page view may draw beyond its bounds (its background) + Box(modifier = modifier.clipToBounds()) { + if (recording != null && renderer != null && pages.isNotEmpty()) { + SessionPages(recording, pages, pageOf, playback?.positionMs, renderer, onSeek) + } + } + } + val controls: @Composable () -> Unit = { + Legend(counts) + // media playback reads left to right in every language (time, the timeline and the controls), as + // Material's bidirectionality guidance has it + CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Ltr) { + Player(recording, playback, onPlay, onPause, onSeek, onSkip) + } + } + if (maxHeight < SHORT_HEIGHT && maxWidth > maxHeight) { + // a phone on its side: the pages get the height, the player sits beside them + Row(modifier = Modifier.fillMaxSize()) { + pagesView(Modifier.weight(1f).fillMaxHeight()) + VerticalDivider(color = MaterialTheme.colorScheme.outlineVariant) + Column( + verticalArrangement = Arrangement.Center, + modifier = Modifier.width(SIDE_PLAYER_WIDTH).fillMaxHeight().verticalScroll(rememberScrollState()), + ) { + controls() + } + } + } else { + Column(modifier = Modifier.fillMaxSize()) { + pagesView(Modifier.weight(1f).fillMaxWidth()) + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + controls() + } + } + } + } +} + +/** The session's pages in mushaf order (the first on the right), following the word being heard. */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun SessionPages( + recording: Recording, + pages: List, + pageOf: (Recording.Word) -> Int, + positionMs: Long?, + renderer: PageRenderer, + onSeek: (Long) -> Unit, +) { + val playingIndex = positionMs + ?.let { SessionMarks.wordAt(recording, it) } + ?.let { pages.indexOf(pageOf(recording.words[it])) } + ?.takeIf { it >= 0 } + val pagerState = rememberPagerState(initialPage = playingIndex ?: 0) { pages.size } + var follow by remember { mutableStateOf(true) } + val dragged by pagerState.interactionSource.collectIsDraggedAsState() + LaunchedEffect(dragged) { if (dragged) follow = false } + LaunchedEffect(playingIndex, follow) { + if (follow && playingIndex != null && pagerState.currentPage != playingIndex) pagerState.animateScrollToPage(playingIndex) + } + val seek by rememberUpdatedState(onSeek) + val direction = LocalLayoutDirection.current + Box(modifier = Modifier.fillMaxSize()) { + // pages turn as in a mushaf, whatever the language + CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) { + HorizontalPager( + state = pagerState, + beyondViewportPageCount = 1, + key = { pages[it] }, + // the page view measures itself from the room it is given: give it all of it + modifier = Modifier.fillMaxSize(), + ) { index -> + CompositionLocalProvider(LocalLayoutDirection provides direction) { + val page = pages[index] + SessionPage(page, renderer, SessionMarks.marks(recording, positionMs) { pageOf(it) == page }) { ayah, word -> + SessionMarks.timeOf(recording, ayah.sura, ayah.ayah, word)?.let { + follow = true + seek(it) + } + } + } + } + } + AnimatedVisibility( + visible = !follow && playingIndex != null && pagerState.currentPage != playingIndex, + enter = fadeIn(tween(200)), + exit = fadeOut(tween(150)), + modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 16.dp), + ) { + FilledTonalButton(onClick = { follow = true }) { Text(stringResource(R.string.memorize_sessions_follow)) } + } + } +} + +/** One mushaf page, drawn as in the reader, with the session's marks on it. */ +@Composable +private fun SessionPage( + page: Int, + renderer: PageRenderer, + marks: Set, + onTapped: (com.quran.data.model.SuraAyah, Int?) -> Unit, +) { + val tapped by rememberUpdatedState(onTapped) + val preview = remember(page) { renderer.page(page) { ayah, word -> tapped(ayah, word) } } + DisposableEffect(preview) { onDispose { preview.release() } } + // only what changed is sent (the word being heard changes several times a second) + val applied = remember(preview) { mutableStateOf(emptySet()) } + SideEffect { + val before = applied.value + if (before != marks) { + val actions = (before - marks).map { HighlightAction.Unhighlight(it.info()) } + + (marks - before).map { HighlightAction.Highlight(it.info()) } + preview.apply(actions) + applied.value = marks + } + } + AndroidView(factory = { preview.view }, modifier = Modifier.fillMaxSize()) +} + +private fun Mark.info() = HighlightInfo(sura, ayah, word, type, scrollToAyah = false) + +/** What the marks' colours mean, and how many words each. */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun Legend(counts: SessionCounts) { + val night = MaterialTheme.colorScheme.surface.luminance() < 0.5f + FlowRow( + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp), + ) { + LegendItem(MaterialTheme.colorScheme.primary, stringResource(R.string.memorize_legend_recited), counts.recited) + if (counts.hinted > 0) { + LegendItem(if (night) Color(0xFF4DB6AC) else Color(0xFF00897B), stringResource(R.string.memorize_legend_hinted), counts.hinted) + } + if (counts.missed > 0) { + LegendItem(if (night) Color(0xFFCE93D8) else Color(0xFFFB8C00), stringResource(R.string.memorize_legend_missed), counts.missed) + } + if (counts.mistakes > 0) { + LegendItem(if (night) Color(0xFFEF5350) else Color(0xFFE53935), stringResource(R.string.memorize_legend_mistakes), counts.mistakes) + } + } +} + +@Composable +private fun LegendItem(color: Color, label: String, count: Int) { + // the screen's locale (its digits), followed if it changes + val locale = LocalConfiguration.current.locales[0] + Row(verticalAlignment = Alignment.CenterVertically) { + Box(Modifier.size(10.dp).clip(CircleShape).background(color)) + Spacer(Modifier.width(8.dp)) + Text( + "$label ${String.format(locale, "%d", count)}", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +/** Play, pause, 5 seconds back and on, and where it is. */ +@Composable +private fun Player( + recording: Recording?, + playback: RecordingPlayer.Playback?, + onPlay: () -> Unit, + onPause: () -> Unit, + onSeek: (Long) -> Unit, + onSkip: (Long) -> Unit, +) { + val durationMs = recording?.durationMs ?: 0L + val positionMs = playback?.positionMs ?: 0L + val timeline = remember(recording) { recording?.let(::timelineOf).orEmpty() } + var dragging by remember { mutableStateOf(false) } + var dragged by remember { mutableFloatStateOf(0f) } + val fraction = if (durationMs > 0) (positionMs.toFloat() / durationMs).coerceIn(0f, 1f) else 0f + val positionLabel = stringResource(R.string.memorize_sessions_position) + Column(modifier = Modifier.fillMaxWidth().navigationBarsPadding().padding(start = 16.dp, end = 16.dp, bottom = 8.dp)) { + SessionTimeline( + words = timeline, + durationMs = durationMs, + positionMs = if (dragging) (dragged * durationMs).toLong() else positionMs, + description = stringResource(R.string.memorize_sessions_timeline), + onSeek = onSeek, + modifier = Modifier.padding(horizontal = 8.dp), + ) + Slider( + value = if (dragging) dragged else fraction, + onValueChange = { + dragging = true + dragged = it + }, + onValueChangeFinished = { + onSeek((dragged * durationMs).toLong()) + dragging = false + }, + enabled = durationMs > 0, + modifier = Modifier.semantics { contentDescription = positionLabel }, + ) + Row(modifier = Modifier.fillMaxWidth()) { + val digits = MaterialTheme.typography.labelMedium.merge(TextStyle(fontFeatureSettings = "tnum")) + val shown = if (dragging) (dragged * durationMs).toLong() else positionMs + Text(DateUtils.formatElapsedTime(shown / 1000), style = digits, color = MaterialTheme.colorScheme.onSurfaceVariant) + Spacer(Modifier.weight(1f)) + Text(DateUtils.formatElapsedTime(durationMs / 1000), style = digits, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(28.dp, Alignment.CenterHorizontally), + modifier = Modifier.fillMaxWidth().padding(top = 4.dp), + ) { + IconButton(onClick = { onSkip(-SKIP_MS) }, enabled = playback != null) { + Icon(MemorizeIcons.Replay5, contentDescription = stringResource(R.string.memorize_sessions_back)) + } + val playing = playback?.isPlaying == true + FilledIconButton(onClick = if (playing) onPause else onPlay, enabled = durationMs > 0, modifier = Modifier.size(56.dp)) { + Icon( + if (playing) QuranIcons.Pause else QuranIcons.PlayArrow, + contentDescription = stringResource(if (playing) R.string.memorize_recordings_pause else R.string.memorize_recordings_play), + modifier = Modifier.size(32.dp), + ) + } + IconButton(onClick = { onSkip(SKIP_MS) }, enabled = playback != null) { + Icon(MemorizeIcons.Forward5, contentDescription = stringResource(R.string.memorize_sessions_forward)) + } + } + } +} + +private const val SKIP_MS = 5_000L + +// below this height (a phone on its side) the player goes beside the pages +private val SHORT_HEIGHT = 480.dp +private val SIDE_PLAYER_WIDTH = 360.dp diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionTimeline.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionTimeline.kt new file mode 100644 index 0000000000..573af2f0f3 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionTimeline.kt @@ -0,0 +1,99 @@ +package com.quran.mobile.feature.memorize.recording + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.luminance +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp + +/** Where in a session's time each word was, and how it went (see [SessionTimeline]). */ +internal data class TimelineWord(val atMs: Long, val kind: Kind, val startsAyah: Boolean) { + enum class Kind { RECITED, HINTED, MISSED, MISTAKE } +} + +/** The words of [recording] that have a time, in order. */ +internal fun timelineOf(recording: Recording): List = recording.words.mapNotNull { word -> + val at = word.startMs ?: word.endMs ?: return@mapNotNull null + val kind = when { + word.status == Recording.WordStatus.HINTED -> TimelineWord.Kind.HINTED + (word.mistakes ?: 0) > 0 -> TimelineWord.Kind.MISTAKE + word.status == Recording.WordStatus.MISSED -> TimelineWord.Kind.MISSED + else -> TimelineWord.Kind.RECITED + } + TimelineWord(at, kind, startsAyah = word.id.word == 1) +} + +/** + * The session across its time: a short mark for every word recited, a tall one in the legend's + * colour where a word was given, skipped or got a mistake, and a tick where each ayah starts. The + * part already played is darker. Tapping plays from there. It runs left to right, as the player does. + */ +@Composable +internal fun SessionTimeline( + words: List, + durationMs: Long, + positionMs: Long, + description: String, + onSeek: (Long) -> Unit, + modifier: Modifier = Modifier, +) { + if (durationMs <= 0 || words.isEmpty()) return + val night = MaterialTheme.colorScheme.surface.luminance() < 0.5f + val recited = MaterialTheme.colorScheme.onSurfaceVariant + val tick = MaterialTheme.colorScheme.outline + val colors = remember(night) { + mapOf( + TimelineWord.Kind.HINTED to if (night) Color(0xFF4DB6AC) else Color(0xFF00897B), + TimelineWord.Kind.MISSED to if (night) Color(0xFFCE93D8) else Color(0xFFFB8C00), + TimelineWord.Kind.MISTAKE to if (night) Color(0xFFEF5350) else Color(0xFFE53935), + ) + } + val seek by rememberUpdatedState(onSeek) + Canvas( + modifier + .fillMaxWidth() + .height(36.dp) + .semantics { contentDescription = description } + .pointerInput(durationMs) { + detectTapGestures { offset -> seek((offset.x / size.width * durationMs).toLong().coerceIn(0, durationMs)) } + } + ) { + val mid = size.height / 2 + fun x(ms: Long) = (ms.toFloat() / durationMs).coerceIn(0f, 1f) * size.width + val played = x(positionMs) + words.forEach { word -> + val wx = x(word.atMs) + val past = wx <= played + if (word.startsAyah) { + drawLine(tick.copy(alpha = 0.5f), Offset(wx, 2.dp.toPx()), Offset(wx, size.height - 2.dp.toPx()), 1.dp.toPx()) + } + val color = colors[word.kind] + if (color == null) { + drawLine( + recited.copy(alpha = if (past) 0.75f else 0.3f), + Offset(wx, mid - 4.dp.toPx()), Offset(wx, mid + 4.dp.toPx()), + 2.dp.toPx(), StrokeCap.Round, + ) + } else { + drawLine( + color.copy(alpha = if (past) 1f else 0.6f), + Offset(wx, mid - 12.dp.toPx()), Offset(wx, mid + 12.dp.toPx()), + 3.dp.toPx(), StrokeCap.Round, + ) + } + } + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionsSideBySide.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionsSideBySide.kt new file mode 100644 index 0000000000..c668f56c4c --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/recording/SessionsSideBySide.kt @@ -0,0 +1,43 @@ +package com.quran.mobile.feature.memorize.recording + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.VerticalDivider +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.quran.mobile.feature.memorize.R + +/** Recording sessions on a wide screen: the list, and the chosen session played back beside it. */ +@Composable +internal fun SessionsSideBySide( + width: Dp, + list: @Composable () -> Unit, + session: (@Composable () -> Unit)?, +) { + Row(Modifier.fillMaxSize()) { + Box(Modifier.width(if (width >= 1200.dp) 400.dp else 340.dp).fillMaxHeight()) { list() } + VerticalDivider(color = MaterialTheme.colorScheme.outlineVariant) + Box(Modifier.weight(1f).fillMaxHeight()) { + if (session != null) { + session() + } else { + Text( + stringResource(R.string.memorize_sessions_choose), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.align(Alignment.Center).padding(28.dp), + ) + } + } + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/service/MemorizeService.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/service/MemorizeService.kt new file mode 100644 index 0000000000..13f19d5f97 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/service/MemorizeService.kt @@ -0,0 +1,189 @@ +package com.quran.mobile.feature.memorize.service + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder +import android.os.PowerManager +import androidx.core.app.NotificationCompat +import androidx.core.app.ServiceCompat +import androidx.core.content.ContextCompat +import com.quran.data.model.SuraAyah +import com.quran.mobile.di.QuranApplicationComponentProvider +import com.quran.mobile.feature.memorize.R +import com.quran.mobile.feature.memorize.di.MemorizeComponentInterface +import com.quran.mobile.feature.memorize.session.MemorizeSessionController +import com.quran.mobile.feature.memorize.session.MemorizeState +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onEach + +/** + * Keeps a memorization session listening while the app isn't visible (e.g. the screen is off + * during salah). Android only lets a foreground service with the microphone type keep using the + * microphone in the background, and it must be started while the app is visible. + * + * The notification shows where the user is, never what was heard. + */ +class MemorizeService : Service() { + + private lateinit var controller: MemorizeSessionController + private var scope: CoroutineScope? = null + private var wakeLock: PowerManager.WakeLock? = null + + override fun onCreate() { + super.onCreate() + val component = (application as QuranApplicationComponentProvider) + .provideQuranApplicationComponent() as MemorizeComponentInterface + controller = component.memorizeSessionController() + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + when (intent?.action) { + ACTION_PAUSE_RESUME -> controller.pauseOrResume() + ACTION_STOP -> { + controller.stop() + stopSelf() + return START_NOT_STICKY + } + } + val state = controller.state.value + ServiceCompat.startForeground( + this, NOTIFICATION_ID, notification(state), + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE else 0 + ) + if (scope == null) { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + this.scope = scope + controller.state + // what the notification shows; not every recognized word + .map { current -> current?.let { Shown(it.status, it.currentAyah) } } + .distinctUntilChanged() + .onEach { shown -> + // it is only started once the session exists, so no session means it ended + if (shown == null || shown.status == MemorizeState.Status.FINISHED) { + releaseWakeLock() + ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) + stopSelf() + return@onEach + } + controller.state.value?.let { + getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification(it)) + } + if (shown.status == MemorizeState.Status.LISTENING) holdWakeLock() else releaseWakeLock() + } + .launchIn(scope) + } + return START_NOT_STICKY + } + + override fun onDestroy() { + releaseWakeLock() + scope?.cancel() + scope = null + super.onDestroy() + } + + private data class Shown(val status: MemorizeState.Status, val ayah: SuraAyah) + + /** + * Keeps the CPU running while listening with the screen off (e.g. during salah). Renewed whenever + * the position changes; the timeout only guards against a session that is somehow left running. + */ + private fun holdWakeLock() { + val lock = wakeLock ?: getSystemService(PowerManager::class.java) + .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "quran:memorize") + .apply { setReferenceCounted(false) } + .also { wakeLock = it } + lock.acquire(WAKE_LOCK_TIMEOUT_MS) + } + + private fun releaseWakeLock() { + wakeLock?.takeIf { it.isHeld }?.release() + } + + override fun onBind(intent: Intent?): IBinder? = null + + private fun notification(state: MemorizeState?): Notification { + createChannel() + val listening = state?.status == MemorizeState.Status.LISTENING + val ayah = state?.currentAyah?.let { "${it.sura}:${it.ayah}" }.orEmpty() + // the user always knows when they are being recorded + val position = if (state?.recordingId != null) getString(R.string.memorize_recording_notification, ayah) else ayah + val openApp = packageManager.getLaunchIntentForPackage(packageName)?.let { + PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + } + return NotificationCompat.Builder(this, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_memorize_notification) + .setContentTitle( + getString( + when { + listening -> R.string.memorize_listening + state?.mode == MemorizeState.Mode.RECITE -> R.string.memorize_recite_paused + else -> R.string.memorize_paused + } + ) + ) + .setContentText(position) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setSilent(true) + .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE) + .setContentIntent(openApp) + .addAction( + 0, getString(if (listening) R.string.memorize_pause else R.string.memorize_resume), + action(ACTION_PAUSE_RESUME, 1) + ) + .addAction(0, getString(R.string.memorize_stop), action(ACTION_STOP, 2)) + .build() + } + + private fun action(action: String, requestCode: Int): PendingIntent = + PendingIntent.getService( + this, requestCode, Intent(this, MemorizeService::class.java).setAction(action), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + + private fun createChannel() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + val manager = getSystemService(NotificationManager::class.java) + if (manager.getNotificationChannel(CHANNEL_ID) == null) { + manager.createNotificationChannel( + NotificationChannel(CHANNEL_ID, getString(R.string.memorize_title), NotificationManager.IMPORTANCE_LOW) + ) + } + } + } + + companion object { + private const val CHANNEL_ID = "memorize_session" + private const val NOTIFICATION_ID = 7_412 + private const val ACTION_PAUSE_RESUME = "com.quran.mobile.feature.memorize.PAUSE_RESUME" + private const val ACTION_STOP = "com.quran.mobile.feature.memorize.STOP" + private const val WAKE_LOCK_TIMEOUT_MS = 3 * 60 * 60 * 1000L + + /** Call once the session exists, while the app is in the foreground. */ + fun start(context: Context) { + try { + ContextCompat.startForegroundService(context, Intent(context, MemorizeService::class.java)) + } catch (_: IllegalStateException) { + // not allowed from the background; the session then only listens while the app is visible + } + } + + fun stop(context: Context) { + context.stopService(Intent(context, MemorizeService::class.java)) + } + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/Follower.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/Follower.kt new file mode 100644 index 0000000000..c5906d40aa --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/Follower.kt @@ -0,0 +1,70 @@ +package com.quran.mobile.feature.memorize.session + +import com.quran.mobile.feature.memorize.tracker.RecitationTracker +import com.quran.mobile.feature.memorize.tracker.TimedPhoneme +import com.quran.mobile.feature.memorize.tracker.TrackerEvent +import com.quran.mobile.feature.memorize.tracker.salah.SalahFlow + +/** Follows the user through the passage; the session doesn't care whether it's salah or not. */ +internal interface Follower { + val cursor: Int + val isDone: Boolean + + /** Whether it is known where the user started (see [RecitationTracker.anchored]). */ + val started: Boolean + + /** Whether hints may be given now (in salah: only while the passage itself is being recited). */ + val canHint: Boolean + + /** Whether the start waits for the words that tell two places apart (see [RecitationTracker.startPending]). */ + val startPending: Boolean + + fun feed(phonemes: List): List + fun onPause(): List + fun markHinted(count: Int) + + /** More of the passage (the next suras): the session goes on past the end of a sura. */ + fun extend(words: List, ayahs: List) + + /** Phrases that become possible later, e.g. the basmala before the next sura. */ + fun addPhrases(phrases: List>) + + /** Diagnostics: what the tracker decides and why. */ + fun trace(trace: (String) -> Unit) + + /** Hints gave up: the user went on past what the tracker holds at; it may follow them. */ + fun releaseHold() {} +} + +internal class MemorizeFollower(private val tracker: RecitationTracker) : Follower { + override val cursor: Int get() = tracker.cursor + override val started: Boolean get() = tracker.anchored + override val isDone: Boolean get() = tracker.isDone + override val canHint: Boolean get() = true + override val startPending: Boolean get() = tracker.startPending + override fun feed(phonemes: List) = tracker.feed(phonemes) + override fun onPause() = tracker.onPause() + override fun markHinted(count: Int) = tracker.markHinted(count) + override fun extend(words: List, ayahs: List) = tracker.extend(words, ayahs) + override fun releaseHold() = tracker.releaseHold() + override fun addPhrases(phrases: List>) = tracker.addPhrases(phrases) + override fun trace(trace: (String) -> Unit) { + tracker.trace = trace + } +} + +internal class SalahFollower(private val flow: SalahFlow) : Follower { + override val cursor: Int get() = flow.passage.cursor + override val started: Boolean get() = flow.passage.anchored + override val isDone: Boolean get() = flow.passage.isDone + override val canHint: Boolean get() = flow.isReadingPassage + override val startPending: Boolean get() = flow.passage.startPending + override fun feed(phonemes: List) = flow.feed(phonemes) + override fun onPause() = flow.onPause() + override fun markHinted(count: Int) = flow.passage.markHinted(count) + override fun extend(words: List, ayahs: List) = flow.extendPassage(words, ayahs) + override fun addPhrases(phrases: List>) = flow.passage.addPhrases(phrases) + override fun trace(trace: (String) -> Unit) { + flow.trace = trace + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/MemorizeSessionController.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/MemorizeSessionController.kt new file mode 100644 index 0000000000..86ee95e832 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/MemorizeSessionController.kt @@ -0,0 +1,1144 @@ +package com.quran.mobile.feature.memorize.session + +import android.os.SystemClock +import android.util.Log +import com.quran.data.di.AppScope +import com.quran.data.model.SuraAyah +import com.quran.mobile.progress.session.AyahResult +import com.quran.mobile.progress.session.SessionRecord +import com.quran.mobile.feature.memorize.audio.AudioSource +import com.quran.mobile.feature.memorize.audio.AudioSourceFactory +import com.quran.mobile.feature.memorize.audio.CallState +import com.quran.mobile.feature.memorize.check.DoubleCheck +import com.quran.mobile.feature.memorize.check.DoubleCheckSource +import com.quran.mobile.feature.memorize.data.LexiconRepository +import com.quran.mobile.feature.memorize.data.LineSource +import com.quran.mobile.feature.memorize.data.PageLines +import com.quran.mobile.feature.memorize.data.Passage +import com.quran.mobile.feature.memorize.model.SpeechModelStore +import com.quran.mobile.feature.memorize.prompt.HintVoice +import com.quran.mobile.feature.memorize.prompt.UpcomingSuras +import com.quran.mobile.feature.memorize.recording.Recorders +import com.quran.mobile.feature.memorize.recording.Recording +import com.quran.mobile.feature.memorize.recording.SessionEvent +import com.quran.mobile.feature.memorize.recording.SessionRecorder +import com.quran.mobile.feature.memorize.settings.MemorizePreferences +import com.quran.mobile.feature.memorize.tracker.PhonemeNormalizer +import com.quran.mobile.feature.memorize.tracker.RecitationTracker +import com.quran.mobile.feature.memorize.tracker.TimedPhoneme +import com.quran.mobile.feature.memorize.tracker.TrackerConfig +import com.quran.mobile.feature.memorize.tracker.TrackerEvent +import com.quran.mobile.feature.memorize.tracker.WordId +import com.quran.mobile.feature.memorize.tracker.engine.RecitationEngine +import com.quran.mobile.feature.memorize.tracker.engine.RecitationStream +import com.quran.mobile.feature.memorize.tracker.engine.RecognizedToken +import com.quran.mobile.feature.memorize.tracker.hint.HintScheduler +import com.quran.mobile.feature.memorize.tracker.salah.SalahFlow +import com.quran.recitation.common.Recitation +import com.quran.recitation.common.RecitationSession +import com.quran.recitation.common.RecitedAyah +import com.quran.recitation.events.RecitationEventPresenter +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.util.Locale +import java.util.UUID +import java.util.concurrent.atomic.AtomicInteger + +/** Creates the speech engine; replaced by a fake in tests. */ +fun interface RecitationEngineFactory { + fun create(models: SpeechModelStore): RecitationEngine +} + +/** + * Runs memorization sessions: microphone -> speech engine -> follower (tracker) -> hint scheduler + * -> state, plus the spoken hints. + * + * A session doesn't end with a sura: the user may go on to the next one (e.g. in taraweeh), so the + * next suras are loaded (and hidden) before the user gets to them, up to the end of the Quran. + * + * All recognition and tracking happens on one serialized worker so audio, timer ticks and hints + * never race. Audio frames are dropped as soon as they are decoded (with the optional double-check, + * the last 8 seconds stay in memory for it to listen to again), unless the user records the session. + * When a session ends, its counts (words recited, given, missed and marked, per ayah) go to + * [SessionResults], which keeps them on the device for Progress if the user lets it; no audio and + * no heard words. + * (Diagnostics, for developers: `adb shell setprop log.tag.MemorizeTrace DEBUG` logs what each + * session hears and decides, from its next start; off by default.) + */ +@SingleIn(AppScope::class) +class MemorizeSessionController private constructor( + private val lexicon: LexiconRepository, + private val models: SpeechModelStore, + private val preferences: MemorizePreferences, + private val recitationEventPresenter: RecitationEventPresenter, + private val engineFactory: RecitationEngineFactory, + private val promptPlayer: HintVoice, + private val audioSources: AudioSourceFactory, + private val callState: CallState, + private val lines: LineSource, + private val upcoming: UpcomingSuras, + private val recorders: Recorders, + private val doubleChecks: DoubleCheckSource, + private val results: SessionResults, + private val scope: CoroutineScope, + /** Runs all recognition and tracking, one task at a time. */ + private val worker: CoroutineDispatcher, + /** Runs the double-check (seconds at a time), one at a time, so it never holds up the worker. */ + private val checker: CoroutineDispatcher, + private val clock: () -> Long, + /** How many words to keep loaded ahead of the user. */ + private val lookaheadWords: Int, + /** Where a session's diagnostics go, if anywhere (checked at each start). */ + private val traceSink: () -> ((String) -> Unit)?, +) { + @OptIn(ExperimentalCoroutinesApi::class) + @Inject constructor( + lexicon: LexiconRepository, + models: SpeechModelStore, + preferences: MemorizePreferences, + recitationEventPresenter: RecitationEventPresenter, + engineFactory: RecitationEngineFactory, + promptPlayer: HintVoice, + audioSources: AudioSourceFactory, + callState: CallState, + lines: LineSource, + upcoming: UpcomingSuras, + recorders: Recorders, + doubleChecks: DoubleCheckSource, + results: SessionResults, + ) : this( + lexicon, models, preferences, recitationEventPresenter, engineFactory, promptPlayer, audioSources, callState, + lines, upcoming, recorders, doubleChecks, results, + scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate), + worker = Dispatchers.Default.limitedParallelism(1), + checker = Dispatchers.Default.limitedParallelism(1), + clock = SystemClock::elapsedRealtime, + lookaheadWords = LOOKAHEAD_WORDS, + traceSink = { if (Log.isLoggable(TRACE_TAG, Log.DEBUG)) { message -> Log.d(TRACE_TAG, message) } else null }, + ) + + private val _state = MutableStateFlow(null) + val state: StateFlow = _state.asStateFlow() + + private val _failures = MutableSharedFlow(extraBufferCapacity = 1) + /** Emits when a session couldn't start; that session is over (the state is back to null). */ + val failures: SharedFlow = _failures.asSharedFlow() + + // the following are only touched on the worker + private var engine: RecitationEngine? = null + private var stream: RecitationStream? = null + private var follower: Follower? = null + private var scheduler: HintScheduler? = null + private var keepShortVowels = false + private var silentSinceMs = -1L + private var pauseHandled = true + private var lastRecognizedMs = 0L + private var gapHandled = true + // after too many hints in a row, hints wait until the user recites a word on their own + private var gaveUp = false + // during a call the microphone hears nothing useful and hints must stay quiet + private var inCall = false + // how much audio the session has heard (the speech engine's clock) + private var heardMs = 0L + // the double-check, if on and loaded, and the last seconds the user said for it to hear (the + // check itself only ever runs on the checker) + private var check: DoubleCheck? = null + private var heard: FloatArray? = null + private var heardEnd = 0L + // diagnostics (see the class comment) + private var traceTo: ((String) -> Unit)? = null + private var tracedSpeech = false + private var tracedStatusAt = 0L + // where each loaded word is on the pages (see PageLines), for hints of the rest of a line + private val wordLines = HashMap() + // the session whose next suras are being loaded, if any + private var extendingFor: String? = null + // the basmala before a sura, once the passage goes beyond its first sura (see prepare) + private var basmala: List> = emptyList() + // how many times a mistake was marked on each word (passage index), for its recording + private val mistakeCounts = HashMap() + // the session whose results were last handed to SessionResults, so it goes there once + private var resultsFor: String? = null + // what a recording made to contribute was last told (see report) + private var reportedSpeech: Boolean? = null + private var reportedPrompting = false + + // the following are only touched on the main thread + private var startJob: Job? = null + private var mic: AudioSource? = null + private var frames: Channel? = null + private var jobs: List = emptyList() + // completed once the session's engine and follower can take frames + private var ready = CompletableDeferred() + // while a hint is being played the microphone hears the reciter, not the user + @Volatile private var prompting = false + // where the session's audio goes when the user chose to record it + @Volatile private var recorder: SessionRecorder? = null + // bumped by every hint, by stopping and by a call: a hint only plays (and only ends the wait for + // it) while its number is still the current one + private val hintGeneration = AtomicInteger() + + private class Frame(val samples: FloatArray, val speech: Boolean) + + val isActive: Boolean get() = _state.value?.isActive == true + + /** + * Starts a session at [startAyah]; with [record], the user's recitation is recorded too, and with + * [contribute] the recording keeps what the speech model heard, to help improve the models. + * + * With [startAnywhereUntil] the user may start anywhere from [startAyah] up to that ayah (e.g. the + * pages around the one on screen), and is expected at [home] (e.g. the first ayah on screen, where + * starting elsewhere is marked): the words are hidden once it is known where they started. + */ + fun start( + startAyah: SuraAyah, + mode: MemorizeState.Mode = MemorizeState.Mode.MEMORIZE, + record: Boolean = false, + startAnywhereUntil: SuraAyah? = null, + home: SuraAyah = startAyah, + contribute: Boolean = false, + ) { + if (isActive || startJob?.isActive == true) return + val sessionId = UUID.randomUUID().toString() + startJob = scope.launch { + try { + prepare(sessionId, startAyah, mode, record || contribute, contribute, startAnywhereUntil, home) + } catch (e: CancellationException) { + throw e + } catch (_: Throwable) { + // e.g. no storage to unpack the lexicon, or not enough memory for the speech model + _failures.tryEmit(Unit) + stop() + } + } + } + + /** Loads what the session needs; false if the session was stopped in the meantime. */ + private suspend fun prepare( + sessionId: String, + startAyah: SuraAyah, + mode: MemorizeState.Mode, + record: Boolean, + contribute: Boolean, + startAnywhereUntil: SuraAyah?, + home: SuraAyah, + ): Boolean { + val passage = lexicon.passage(startAyah, minWords = lookaheadWords, throughSura = startAnywhereUntil?.sura ?: startAyah.sura) + require(passage.words.isNotEmpty()) { "nothing to recite from $startAyah" } + // the words the user may start at, and where they are expected to + val startWindow = startAnywhereUntil?.let { end -> + passage.words.indexOfLast { it.id.sura < end.sura || (it.id.sura == end.sura && it.id.ayah <= end.ayah) } + 1 + } ?: 0 + val homeIndex = passage.words.indexOfFirst { it.id.sura == home.sura && it.id.ayah == home.ayah }.coerceAtLeast(0) + val recorder = if (record) recorders.start(startAyah, mode, contribute, if (contribute) sessionInfo(mode) else emptyMap()) else null + this.recorder = recorder + _state.value = MemorizeState( + sessionId, passage, System.currentTimeMillis(), MemorizeState.Status.PREPARING, mode, recordingId = recorder?.session, + cursor = homeIndex, + started = startWindow <= 1, + firstWord = homeIndex, + showMistakes = mode != MemorizeState.Mode.RECITE || preferences.reciteMarkMistakes, + ) + publishSession() + // Listen right away: loading the model takes seconds on slow phones, and what the user says + // meanwhile waits in the frame queue until the session is ready to take it. + val ready = CompletableDeferred().also { this.ready = it } + startListening() + + val salah = mode == MemorizeState.Mode.SALAH + val kinds = if (salah) SalahFlow.PRAYER_PHRASES else setOf("isti'adha", BASMALA) + val allPhrases = lexicon.phrases(kinds) + // Al-Fatiha starts with the basmala itself, and At-Tawba has none: there it isn't said before + // the passage, only before the suras that follow + val basmalaFirst = salah || (home.sura != 1 && home.sura != 9) + val phraseList = allPhrases.filter { (kind, _) -> kind != BASMALA || basmalaFirst } + val fatihaWords = if (salah) lexicon.passage(SuraAyah(1, 2)).words else emptyList() + val pageLines = lines.forSuras(startAyah.sura..passage.words.last().id.sura) + upcoming.loaded(startAyah.sura..passage.words.last().id.sura) + + return withContext(worker) { + // stop() cleans up on this worker too: if it already ran, don't load anything it won't free + if (_state.value?.id != sessionId) return@withContext false + keepShortVowels = preferences.strictTashkeel + val phrases = phraseList.map { (kind, phonemes) -> kind to PhonemeNormalizer.normalize(phonemes, keepShortVowels) } + basmala = if (basmalaFirst) { + emptyList() + } else { + allPhrases.filter { it.first == BASMALA }.map { (kind, phonemes) -> kind to PhonemeNormalizer.normalize(phonemes, keepShortVowels) } + } + wordLines.clear() + wordLines.putAll(pageLines) + mistakeCounts.clear() + reportedSpeech = null + reportedPrompting = false + extendingFor = null + val words = passage.words.map { PhonemeNormalizer.normalize(it.wasl, keepShortVowels) } + val fatiha = fatihaWords.map { PhonemeNormalizer.normalize(it.wasl, keepShortVowels) } + // which ayah each word is in: restarts are found behind, and (but in salah) no ayah is left out + val ayahs = passage.words.map { ayahId(it.id) } + val engine = engine ?: engineFactory.create(models).also { engine = it } + stream = engine.newStream() + follower = if (salah) { + SalahFollower( + SalahFlow( + words, fatiha, phrases, startWindow = startWindow, startIndex = homeIndex, + passageAyahs = ayahs, fatihaAyahs = fatihaWords.map { ayahId(it.id) }, + ) + ) + } else { + MemorizeFollower( + RecitationTracker( + words, trackerConfig(), startIndex = homeIndex, phrases = phrases, startWindow = startWindow, ayahs = ayahs, + ) + ) + } + // the session's clock starts now (the trace's times too) + heardMs = 0L + traceTo = traceSink() + tracedSpeech = false + tracedStatusAt = 0L + loadDoubleCheck(sessionId) + follower?.trace { message -> trace { message } } + trace { + "start $mode ${passage.words.first().id}..${passage.words.last().id} (${passage.words.size} words) " + + "window=$startWindow home=$homeIndex ${passage.words[homeIndex].id} record=$record" + } + scheduler = HintScheduler(preferences.hintConfig(mode)) + silentSinceMs = -1L + pauseHandled = true + gapHandled = true + gaveUp = false + inCall = false + armIfAllowed() + ready.complete(Unit) + true + } + } + + fun pauseOrResume() { + val current = _state.value ?: return + when (current.status) { + MemorizeState.Status.LISTENING -> pause() + MemorizeState.Status.PAUSED -> { + startListening() + scope.launch(worker) { armIfAllowed() } + } + else -> Unit + } + } + + private fun pause() { + stopListening() + // what was recorded so far can be listened to + recorder?.pause() + scope.launch(worker) { scheduler?.disarm()?.let { applyEffects(it) } } + update { it.copy(status = MemorizeState.Status.PAUSED) } + recitationEventPresenter.onListeningStateChange(false) + } + + fun togglePeek() = update { it.copy(peeking = !it.peeking) } + + /** Gives the next word(s) now, as if the hint delay had passed (once the session is ready). */ + fun requestHint() { + val ready = ready + scope.launch(worker) { + ready.await() + giveHint(preferences.wordsPerHint, HintScheduler.Extent.WORDS) + } + } + + fun stop() { + startJob?.cancel() + startJob = null + hintGeneration.incrementAndGet() + promptPlayer.stop() + prompting = false + stopListening() + finishRecording() + val ended = _state.value + scope.launch(worker) { + ended?.let { recordResults(it, finished = false) } + releaseEngine() + follower = null + scheduler = null + } + _state.value = null + recitationEventPresenter.onListeningStateChange(false) + recitationEventPresenter.onRecitationSessionChange(null) + } + + // ------------------------------------------------------------------------------- listening + + private fun startListening() { + val channel = Channel(capacity = MAX_QUEUED_FRAMES, onBufferOverflow = BufferOverflow.DROP_OLDEST) + frames = channel + val mic = audioSources.create( + onFrame = { samples, count, speech -> channel.trySend(Frame(samples.copyOf(count), speech)) }, + onError = { scope.launch { onMicrophoneError() } }, + ) + this.mic = mic + val ready = ready + jobs = listOf( + scope.launch(worker) { + ready.await() + for (frame in channel) process(frame) + }, + scope.launch(worker) { + var ticks = 0 + while (isActive) { + delay(TICK_MS) + if (ticks++ % CALL_CHECK_TICKS == 0) checkCall() + // before the user started, only starting elsewhere gets a hint (the first word), and not + // while what they recite is heard at two places and the start waits for the difference + if ((follower?.started != false || _state.value?.mistake != null) && follower?.startPending != true) { + scheduler?.onTick(now())?.let { applyEffects(it) } + } + } + }, + ) + mic.start() + update { it.copy(status = MemorizeState.Status.LISTENING) } + recitationEventPresenter.onListeningStateChange(true) + } + + private fun stopListening() { + mic?.stop() + mic = null + frames?.close() + frames = null + jobs.forEach { it.cancel() } + jobs = emptyList() + } + + private fun onMicrophoneError() { + if (_state.value?.status == MemorizeState.Status.LISTENING) pause() + } + + private fun process(frame: Frame) { + val stream = stream ?: return + val follower = follower ?: return + val scheduler = scheduler ?: return + // everything the microphone heard, hints included + recorder?.write(frame.samples) + val frameStartMs = heardMs + heardMs += frame.samples.size * 1000L / SAMPLE_RATE + reportEdges(frameStartMs, frame.speech) + heard?.let { buffer -> + // silence while a hint plays: the check must not hear Husary say the word + for (x in frame.samples) buffer[(heardEnd++ % buffer.size).toInt()] = if (prompting) 0f else x + } + if (prompting) { + // keep the stream's timeline continuous, but don't let the hint be recognized as the user + stream.accept(FloatArray(frame.samples.size), speech = false) + return + } + val now = now() + scheduler.onSpeechActivity(now, frame.speech) + val tokens = stream.accept(frame.samples, speech = frame.speech) + if (tokens.isNotEmpty()) recorder?.takeIf { it.keepsDetails }?.heard(tokens) + if (traceTo != null) { + if (frame.speech != tracedSpeech) { + tracedSpeech = frame.speech + trace { if (frame.speech) "speech" else "silence" } + } + if (tokens.isNotEmpty()) trace { "heard ${tokens.joinToString("") { it.text }}" } + if (heardMs - tracedStatusAt >= TRACE_STATUS_MS) { + tracedStatusAt = heardMs + trace { + "status cursor=${follower.cursor} started=${follower.started} canHint=${follower.canHint} " + + "armed=${scheduler.isArmed} gaveUp=$gaveUp mistake=${_state.value?.mistake}" + } + } + } + if (tokens.isNotEmpty()) { + val events = follower.feed(tokens.toPhonemes()) + if (events.isNotEmpty()) onTrackerEvents(events) + } + trackPause(frame.speech, recognized = tokens.isNotEmpty(), now) + // e.g. Al-Fatiha of the next rak'ah has begun, which the follower reports without events + disarmIfNotAllowed() + } + + /** + * Tells the follower when the user has paused (e.g. for ruku after the takbir): after a moment of + * silence, or once nothing new has been recognized for a while, because a mosque's loudspeakers + * and the people around may never sound silent. + */ + private fun trackPause(speech: Boolean, recognized: Boolean, now: Long) { + if (speech) { + silentSinceMs = -1L + pauseHandled = false + } else { + if (silentSinceMs < 0) silentSinceMs = now + if (!pauseHandled && now - silentSinceMs >= PAUSE_MS) { + pauseHandled = true + onPause() + } + } + if (recognized) { + lastRecognizedMs = now + gapHandled = false + } else if (!gapHandled && now - lastRecognizedMs >= RECOGNITION_GAP_MS) { + gapHandled = true + onPause() + } + } + + private fun onPause() { + trace { "pause" } + val events = follower?.onPause().orEmpty() + if (events.isNotEmpty()) onTrackerEvents(events) + } + + /** No hints while the phone rings or is in a call; they start over once it ends. */ + private fun checkCall() { + val calling = callState.isInCall() + if (calling == inCall) return + inCall = calling + report(if (calling) SessionEvent.Kind.CALL_STARTED else SessionEvent.Kind.CALL_ENDED, heardMs) + if (calling) { + // a hint cut short never finishes: stop waiting for it + hintGeneration.incrementAndGet() + scope.launch { + promptPlayer.stop() + prompting = false + } + scheduler?.disarm()?.let { applyEffects(it) } + } else { + armIfAllowed() + } + } + + private fun List.toPhonemes(): List = flatMap { token -> + PhonemeNormalizer.normalize(token.text, keepShortVowels).map { TimedPhoneme(it, token.timeMs) } + } + + // --------------------------------------------------------------------------- tracker events + + private fun onTrackerEvents(events: List) { + val follower = follower ?: return + val scheduler = scheduler ?: return + val passage = _state.value?.passage ?: return + val effects = ArrayList() + val missed = HashSet() + if (events.any { it is TrackerEvent.WordRecited }) gaveUp = false + armIfAllowed() + for (event in events) { + trace { + val word = passage.words.getOrNull(event.index)?.id + when (event) { + is TrackerEvent.Mistake -> "mistake ${event.kind} at ${event.index} $word" + is TrackerEvent.NonTarget -> "phrase ${event.kind}" + // names spelled out: class names don't survive R8 in release builds + is TrackerEvent.WordRecited -> "WordRecited ${event.index} $word" + is TrackerEvent.WordMissed -> "WordMissed ${event.index} $word" + is TrackerEvent.Repetition -> "Repetition ${event.index} $word" + } + } + when (event) { + is TrackerEvent.WordRecited -> recordWord(passage, event.index, event.startMs ?: event.timeMs, event.timeMs, Recording.WordStatus.RECITED) + is TrackerEvent.WordMissed -> { + missed += event.index + recordWord(passage, event.index, null, null, Recording.WordStatus.MISSED) + } + is TrackerEvent.Repetition -> { + effects += scheduler.onRepetition(now()) + report(SessionEvent.Kind.REPETITION, event.timeMs, passage.words.getOrNull(event.index)?.id) { + passage.words.getOrNull(event.lastIndex)?.id?.let { "${it.sura}:${it.ayah}:${it.word}" } + } + } + is TrackerEvent.Mistake -> { + report(SessionEvent.Kind.MISTAKE, event.timeMs, passage.words.getOrNull(event.index)?.id) { + event.kind.name.lowercase(Locale.ROOT) + } + if (scheduler.isArmed) { + effects += scheduler.onMistake(now(), passage.words[event.index].id) + } else if (event.kind == TrackerEvent.Mistake.Kind.ELSEWHERE) { + // e.g. in salah, before the passage: shown, not spoken + showMistake(event.index) + } + } + is TrackerEvent.NonTarget -> report(SessionEvent.Kind.PHRASE, event.timeMs) { event.kind } + } + } + val progressed = events.any { it is TrackerEvent.WordRecited || it is TrackerEvent.WordMissed } + if (progressed) { + effects += scheduler.onWordRecited(now(), atAyahBoundary = passage.atAyahBoundary(follower.cursor)) + } + val cursor = follower.cursor + val started = follower.started + val firstRecited = events.filterIsInstance().minOfOrNull { it.index } + update { state -> + val justStarted = started && !state.started + state.copy( + cursor = cursor, + missed = state.missed + missed, + started = started, + firstWord = if (justStarted) firstRecited ?: cursor else state.firstWord, + // the start found: a mark for starting elsewhere has served its purpose + mistake = if (justStarted) null else state.mistake, + ) + } + applyEffects(effects) + disarmIfNotAllowed() + onPassageProgress() + } + + /** Worker only. Prepares what comes next: the basmala before the next sura, more suras, the end. */ + private fun onPassageProgress() { + val follower = follower ?: return + val state = _state.value ?: return + val passage = state.passage + if (basmala.isNotEmpty() && follower.cursor < passage.words.size && + passage.words[follower.cursor].id.sura != passage.words[0].id.sura + ) { + follower.addPhrases(basmala) + basmala = emptyList() + } + if (follower.isDone && passage.reachesEnd) { + finish() + return + } + if (extendingFor == state.id || passage.reachesEnd || passage.words.size - follower.cursor > lookaheadWords) return + extendingFor = state.id + val session = state.id + val lastSura = passage.words.last().id.sura + scope.launch(worker) { + try { + val more = lexicon.nextSuras(lastSura, lookaheadWords) + if (more.words.isEmpty()) return@launch + val moreLines = lines.forSuras(more.words.first().id.sura..more.words.last().id.sura) + // the session may have ended (or another started) while the suras were read + if (_state.value?.id != session || this@MemorizeSessionController.follower !== follower) return@launch + follower.extend(more.words.map { PhonemeNormalizer.normalize(it.wasl, keepShortVowels) }, more.words.map { ayahId(it.id) }) + trace { "passage extended to ${more.words.last().id}" } + wordLines.putAll(moreLines) + update { if (it.id == session) it.copy(passage = it.passage + more) else it } + upcoming.loaded(more.words.first().id.sura..more.words.last().id.sura) + } catch (e: CancellationException) { + throw e + } catch (_: Throwable) { + // e.g. no storage left to read from: tried again on the next word + } finally { + if (extendingFor == session) extendingFor = null + } + onPassageProgress() + } + } + + /** In salah, hints stop as soon as the passage isn't being recited. */ + private fun disarmIfNotAllowed() { + val follower = follower ?: return + val scheduler = scheduler ?: return + if (!follower.canHint && scheduler.isArmed) applyEffects(scheduler.disarm()) + } + + /** Hints are only armed when the follower allows them (always, or in salah while reciting). */ + private fun armIfAllowed() { + val follower = follower ?: return + val scheduler = scheduler ?: return + val passage = _state.value?.passage ?: return + if (follower.canHint && !scheduler.isArmed && !gaveUp && !inCall && + _state.value?.status != MemorizeState.Status.PAUSED + ) { + applyEffects(scheduler.arm(now(), atAyahBoundary = passage.atAyahBoundary(follower.cursor))) + } + } + + private fun applyEffects(effects: List) { + for (effect in effects) { + trace { "hint scheduler: $effect" } + when (effect) { + is HintScheduler.Effect.MarkMistake -> if (!checkMistake(effect.word)) { + _state.value?.passage?.words?.indexOfFirst { it.id == effect.word }?.takeIf { it >= 0 }?.let { showMistake(it) } + } + is HintScheduler.Effect.ClearMistake -> { + if (_state.value?.mistake != null) report(SessionEvent.Kind.MARK_CLEARED, heardMs, effect.word) + update { it.copy(mistake = null) } + } + is HintScheduler.Effect.GiveHint -> if (!checkHint(effect.count, effect.extent)) giveHint(effect.count, effect.extent) + HintScheduler.Effect.GiveUp -> { + gaveUp = true + report(SessionEvent.Kind.GAVE_UP, heardMs) + // ten hints and the user went on regardless: rather than stay where they aren't, follow + // them (what was never heard is marked as skipped) + follower?.releaseHold() + } + // no hint will give the word the user went on past: after the delay, follow them (what + // they left out is marked as skipped) + HintScheduler.Effect.FollowOn -> follower?.releaseHold() + } + } + } + + private fun giveHint(count: Int, extent: HintScheduler.Extent) { + val follower = follower ?: return + val scheduler = scheduler ?: return + val passage = _state.value?.passage ?: return + val first = follower.cursor + follower.markHinted(hintLength(passage, first, count, extent)) + val hinted = (first until follower.cursor).toList() + if (hinted.isEmpty()) return + hinted.forEach { recordWord(passage, it, heardMs, null, Recording.WordStatus.HINTED) } + report(SessionEvent.Kind.HINT, heardMs, passage.words[first].id) { hinted.size.toString() } + scheduler.onHintStarted() + update { it.copy(cursor = follower.cursor, hinted = it.hinted + hinted, mistake = null, started = follower.started) } + val words = hinted.map { passage.words[it].id }.filter { it.sura == passage.words[first].id.sura } + val generation = hintGeneration.incrementAndGet() + // finding the audio reads files: here on the worker, not on the main thread + val clip = promptPlayer.prepare(preferences.promptQariId, words) + scope.launch { + if (generation != hintGeneration.get()) return@launch + if (clip == null) { + hintFinished(generation) + } else { + promptPlayer.play( + clip, + onStarted = { if (generation == hintGeneration.get()) prompting = true }, + onFinished = { hintFinished(generation) }, + ) + } + } + } + + /** + * How many words a hint gives from [first]: [count], or for [HintScheduler.Extent.AYAH_OR_LINE] the + * rest of the ayah if it is no longer than the line, else the rest of the line (and the next line + * if only one word is left on this one), as the page type in use breaks its lines. + */ + private fun hintLength(passage: Passage, first: Int, count: Int, extent: HintScheduler.Extent): Int { + val words = passage.words + if (extent == HintScheduler.Extent.WORDS || first >= words.size) return count + var ayahEnd = first + while (!passage.endsAyah(ayahEnd)) ayahEnd++ + val restOfAyah = ayahEnd - first + 1 + fun lineOf(index: Int): Int? = words[index].id.let { wordLines[PageLines.key(it.sura, it.ayah)]?.getOrNull(it.word - 1) } + val line = lineOf(first) ?: return maxOf(count, minOf(restOfAyah, UNKNOWN_LINE_WORDS)) + var lineStart = first + while (lineStart > 0 && lineOf(lineStart - 1) == line) lineStart-- + var lineEnd = first + while (lineEnd + 1 < words.size && lineOf(lineEnd + 1) == line) lineEnd++ + if (restOfAyah <= lineEnd - lineStart + 1) return maxOf(count, restOfAyah) + if (lineEnd == first && lineEnd + 1 < words.size) { + val next = lineOf(lineEnd + 1) + while (lineEnd + 1 < words.size && lineOf(lineEnd + 1) == next) lineEnd++ + } + return maxOf(count, lineEnd - first + 1) + } + + /** On the main thread, once hint number [generation] has been played (or had nothing to play). */ + private fun hintFinished(generation: Int) { + scope.launch { + // let the room go quiet before listening to the user again + if (prompting) delay(PROMPT_TAIL_MS) + if (generation != hintGeneration.get()) return@launch + prompting = false + withContext(worker) { + scheduler?.onHintFinished(now()) + onPassageProgress() + } + } + } + + private fun finish() { + scope.launch { + stopListening() + finishRecording() + update { it.copy(status = MemorizeState.Status.FINISHED, mistake = null) } + recitationEventPresenter.onListeningStateChange(false) + // the passage is done; the user may keep reading, but the model's memory isn't needed + withContext(worker) { + _state.value?.let { recordResults(it, finished = true) } + releaseEngine() + } + } + } + + /** + * Worker only. Hands what [state]'s session came to to [results], once per session: from the word + * the user started at to where they got. A session that never got going (it didn't start, or + * nothing was revealed) has nothing to give. + */ + private fun recordResults(state: MemorizeState, finished: Boolean) { + if (resultsFor == state.id) return + if (state.status == MemorizeState.Status.PREPARING || !state.started) return + val words = state.passage.words + val from = state.firstWord + val until = state.cursor.coerceAtMost(words.size) + if (until <= from) return + resultsFor = state.id + val ayahs = LinkedHashMap() + var hinted = 0 + var missed = 0 + for (index in from until until) { + val counts = ayahs.getOrPut(state.passage.ayahOf(index)) { IntArray(4) } + counts[0]++ + when (index) { + in state.hinted -> { counts[1]++; hinted++ } + in state.missed -> { counts[2]++; missed++ } + } + } + mistakeCounts.forEach { (index, count) -> + if (index < words.size) ayahs.getOrPut(state.passage.ayahOf(index)) { IntArray(4) }[3] += count + } + val ayahWords = words.groupingBy { SuraAyah(it.id.sura, it.id.ayah) }.eachCount() + val first = state.passage.ayahOf(from) + val last = state.passage.ayahOf(until - 1) + val count = until - from + results.record( + SessionRecord( + id = state.id, + mode = state.mode.name, + startedAtMs = state.startedAt, + endedAtMs = System.currentTimeMillis(), + listenedMs = heardMs, + startSura = first.sura, + startAyah = first.ayah, + endSura = last.sura, + endAyah = last.ayah, + words = count, + recited = count - hinted - missed, + hinted = hinted, + missed = missed, + mistakes = mistakeCounts.values.sum(), + finished = finished, + recordingId = state.recordingId, + ayahs = ayahs.map { (ayah, counts) -> + AyahResult( + sura = ayah.sura, + ayah = ayah.ayah, + ayahWords = ayahWords[ayah] ?: counts[0], + words = counts[0], + hinted = counts[1], + missed = counts[2], + mistakes = counts[3], + ) + }, + ) + ) + } + + /** Worker only. The model takes a lot of memory; it is loaded again for the next session. */ + private fun releaseEngine() { + runCatching { stream?.close() } + runCatching { engine?.close() } + engine = null + stream = null + releaseDoubleCheck() + } + + // ----------------------------------------------------------------------------- double-check + + /** Worker only. Loads the double-check if it is on (seconds: the session doesn't wait for it). */ + private fun loadDoubleCheck(sessionId: String) { + releaseDoubleCheck() + if (!preferences.doubleCheck) return + scope.launch(checker) { + val loaded = runCatching { doubleChecks.open() }.getOrNull() ?: return@launch + withContext(worker) { + if (_state.value?.id != sessionId || follower == null) { + withContext(checker) { loaded.close() } + return@withContext + } + check = loaded + heard = FloatArray(CHECK_SECONDS * SAMPLE_RATE) + heardEnd = 0L + trace { "double-check loaded" } + } + } + } + + /** Worker only. */ + private fun releaseDoubleCheck() { + val loaded = check ?: return + check = null + heard = null + // after any check still running + scope.launch(checker) { loaded.close() } + } + + /** The last seconds the user said, oldest first. */ + private fun heardAudio(): FloatArray { + val buffer = heard ?: return FloatArray(0) + val n = minOf(heardEnd, buffer.size.toLong()).toInt() + return FloatArray(n) { buffer[((heardEnd - n + it) % buffer.size).toInt()] } + } + + /** Runs [check] on what the user said, then [then] on the worker with whether [index] was said. */ + private fun doubleCheck(check: DoubleCheck, passage: Passage, index: Int, then: (Boolean) -> Unit) { + val audio = heardAudio() + val askedAtMs = heardMs + scope.launch(checker) { + val said = runCatching { check.said(audio, passage, index) }.getOrDefault(false) + val ms = check.lastMs + preferences.recordDoubleCheckMs(ms) + withContext(worker) { + trace { "double-check ${passage.words[index].id}: ${if (said) "said" else "not said"} ($ms ms)" } + report(SessionEvent.Kind.DOUBLE_CHECK, askedAtMs, passage.words[index].id) { "${if (said) "said" else "not said"} $ms ms" } + then(said) + } + } + } + + /** + * Worker only. Before a mistake is shown: a second later (the user may be in the middle of the + * word), the double-check listens again; the mark is only shown if the word wasn't said after + * all. True if the check took the mark over. + */ + private fun checkMistake(word: WordId): Boolean { + val check = check ?: return false + val follower = follower ?: return false + val passage = _state.value?.passage ?: return false + val index = passage.words.indexOfFirst { it.id == word }.takeIf { it >= 0 } ?: return false + scope.launch(worker) { + delay(CHECK_MISTAKE_AFTER_MS) + if (this@MemorizeSessionController.follower !== follower || follower.cursor != index) return@launch + doubleCheck(check, passage, index) { said -> + // still the same mistake, still not recited, and the session still listening + if (this@MemorizeSessionController.follower === follower && follower.cursor == index && !said && + scheduler?.isArmed == true + ) { + showMistake(index) + } + } + } + return true + } + + /** + * Worker only. Before a hint is spoken, the double-check listens again: if the user did say the + * word, it counts as recited (as the hint would have) and nothing is said. True if the check took + * the hint over. + */ + private fun checkHint(count: Int, extent: HintScheduler.Extent): Boolean { + val check = check ?: return false + val follower = follower ?: return false + val scheduler = scheduler ?: return false + val passage = _state.value?.passage ?: return false + val first = follower.cursor + if (first >= passage.words.size) return false + // no other hint while this one is being checked + scheduler.onHintStarted() + doubleCheck(check, passage, first) { said -> + if (this@MemorizeSessionController.follower !== follower || this@MemorizeSessionController.scheduler !== scheduler) { + return@doubleCheck + } + when { + // the user went on meanwhile (no hint needed), or paused, or a call came + follower.cursor != first || !scheduler.isArmed || inCall || + _state.value?.status != MemorizeState.Status.LISTENING -> scheduler.onHintFinished(now()) + said -> { + follower.markHinted(1) + recordWord(passage, first, null, null, Recording.WordStatus.RECITED) + update { it.copy(cursor = follower.cursor, mistake = null, started = follower.started) } + scheduler.onHintFinished(now()) + applyEffects(scheduler.onWordRecited(now(), atAyahBoundary = passage.atAyahBoundary(follower.cursor))) + onPassageProgress() + } + else -> { + // giveHint() starts the hint over + scheduler.onHintFinished(now()) + giveHint(count, extent) + } + } + } + return true + } + + /** Main thread, once listening has stopped. */ + private fun finishRecording() { + val recorder = recorder ?: return + this.recorder = null + if (!recorder.keepsDetails) { + recorder.finish() + return + } + // after the last frame: what the recognizer still had of the last words goes with the recording + scope.launch(worker) { + runCatching { stream?.finish() }.getOrNull()?.takeIf { it.isNotEmpty() }?.let { recorder.heard(it) } + recorder.finish() + } + } + + /** Worker only. Marks the word at [index] as a mistake (if marks are shown), and counts it. */ + private fun showMistake(index: Int) { + val state = _state.value ?: return + if (state.mistake == index) return + mistakeCounts[index] = (mistakeCounts[index] ?: 0) + 1 + report(SessionEvent.Kind.MARK_SHOWN, heardMs, state.passage.words.getOrNull(index)?.id) { + if (state.showMistakes) null else "not shown" + } + update { if (it.showMistakes) it.copy(mistake = index) else it } + } + + /** Worker only. Tells a recording made to contribute what the session did at [atMs]. */ + private inline fun report(kind: SessionEvent.Kind, atMs: Long, word: WordId? = null, detail: () -> String? = { null }) { + val recorder = recorder?.takeIf { it.keepsDetails } ?: return + recorder.event(SessionEvent(atMs, kind, word, detail())) + } + + /** Worker only. When the user started or stopped speaking, and when a hint started or ended playing. */ + private fun reportEdges(atMs: Long, speech: Boolean) { + if (recorder?.keepsDetails != true) return + if (speech != reportedSpeech) { + reportedSpeech = speech + report(if (speech) SessionEvent.Kind.SPEECH else SessionEvent.Kind.SILENCE, atMs) + } + val playing = prompting + if (playing != reportedPrompting) { + reportedPrompting = playing + report(if (playing) SessionEvent.Kind.PROMPT_STARTED else SessionEvent.Kind.PROMPT_ENDED, atMs) + } + } + + /** What a recording made to contribute keeps about the session: its settings and speech model. */ + private fun sessionInfo(mode: MemorizeState.Mode): Map = mapOf( + "mode" to mode.name.lowercase(Locale.ROOT), + "model" to models.spec.id, + "model_sha256" to models.spec.model.sha256, + "double_check" to preferences.doubleCheck, + "settings" to mapOf( + "hint_delay_s" to preferences.hintDelaySeconds, + "words_per_hint" to preferences.wordsPerHint, + "corrector" to preferences.correctorEnabled, + "hint_on_mistakes" to preferences.hintOnMistakes, + "hint_on_pauses" to preferences.hintOnPauses, + "strict_tashkeel" to preferences.strictTashkeel, + "recite_mark_mistakes" to preferences.reciteMarkMistakes, + "recite_say_fix" to preferences.reciteSayFix, + "hint_voice" to preferences.promptQariId, + ), + ) + + /** Tells the recording (if any) what happened to the word at [index], in the session's audio time. */ + private fun recordWord(passage: Passage, index: Int, startMs: Long?, endMs: Long?, status: Recording.WordStatus) { + val recorder = recorder ?: return + val word = passage.words.getOrNull(index) ?: return + // the passage always holds whole suras: its last word ends one too + val endsSura = passage.words.getOrNull(index + 1)?.id?.sura != word.id.sura + recorder.word( + word.id, startMs, endsSura = endsSura, endMs = endMs, status = status, phonemes = word.wasl, + mistakes = mistakeCounts[index] ?: 0, + ) + } + + // ------------------------------------------------------------------------------------ state + + private fun update(transform: (MemorizeState) -> MemorizeState) { + while (true) { + val current = _state.value ?: return + val next = transform(current) + if (_state.compareAndSet(current, next)) { + if (next.currentAyah != current.currentAyah) { + scope.launch { recitationEventPresenter.onRecitationChange(next.currentAyah) } + } + return + } + } + } + + private fun publishSession() { + recitationEventPresenter.onRecitationSessionChange(Session()) + } + + private fun now(): Long = clock() + + /** One id per ayah, for the tracker. */ + private fun ayahId(word: WordId): Int = word.sura * 1000 + word.ayah + + /** + * Outside salah no ayah may be left out: the tracker holds at the first word not recited. Inside an + * ayah, a word or two the recognizer missed may pass, unless every word must be heard. + */ + private fun trackerConfig(): TrackerConfig = + TrackerConfig(skipAyat = false, maxMissedWords = if (preferences.everyWordHeard) 0 else MISSED_WORDS_IN_AYAH) + + /** Diagnostics, built only when they're on; worker only. */ + private inline fun trace(message: () -> String) { + traceTo?.let { it("t=%.1fs %s".format(Locale.ROOT, heardMs / 1000.0, message())) } + } + + /** Exposes the session to the rest of the app (audio bar, page following). */ + private inner class Session : RecitationSession { + private val snapshot = _state.value + override fun id(): String = snapshot?.id.orEmpty() + override fun startAyah(): SuraAyah = snapshot?.passage?.start ?: SuraAyah(1, 1) + override fun currentAyah(): SuraAyah = _state.value?.currentAyah ?: startAyah() + override fun startedAt(): Long = snapshot?.startedAt ?: 0L + override fun recitation(): Recitation = object : Recitation { + override fun recitedAyahs(): List = emptyList() + } + } + + companion object { + /** A controller on the test's scope, dispatcher and virtual clock. */ + internal fun forTest( + lexicon: LexiconRepository, + models: SpeechModelStore, + preferences: MemorizePreferences, + recitationEventPresenter: RecitationEventPresenter, + engineFactory: RecitationEngineFactory, + promptPlayer: HintVoice, + audioSources: AudioSourceFactory, + callState: CallState, + scope: CoroutineScope, + worker: CoroutineDispatcher, + clock: () -> Long, + lines: LineSource = LineSource { emptyMap() }, + upcoming: UpcomingSuras = UpcomingSuras {}, + recorders: Recorders = Recorders { _, _, _, _ -> null }, + lookaheadWords: Int = LOOKAHEAD_WORDS, + trace: ((String) -> Unit)? = null, + doubleChecks: DoubleCheckSource = DoubleCheckSource { null }, + results: SessionResults = SessionResults {}, + ) = MemorizeSessionController( + lexicon, models, preferences, recitationEventPresenter, engineFactory, promptPlayer, audioSources, callState, + lines, upcoming, recorders, doubleChecks, results, scope, worker, worker, clock, lookaheadWords, { trace }, + ) + + private const val TRACE_TAG = "MemorizeTrace" + /** What the double-check listens to: the last seconds, and a second more after a mistake. */ + private const val CHECK_SECONDS = 8 + private const val CHECK_MISTAKE_AFTER_MS = 1_000L + private const val TRACE_STATUS_MS = 10_000L + private const val BASMALA = "basmala" + private const val SAMPLE_RATE = 16_000 + /** Words kept loaded ahead of the user: several pages, so the next sura is always there. */ + private const val LOOKAHEAD_WORDS = 300 + /** Words in a row the recognizer may miss inside an ayah, when not every word must be heard. */ + private const val MISSED_WORDS_IN_AYAH = 2 + /** At most this many words of an ayah are given at once when its lines aren't known. */ + private const val UNKNOWN_LINE_WORDS = 8 + + private const val TICK_MS = 100L + private const val PROMPT_TAIL_MS = 300L + /** Silence after which the user is considered to have paused (completes a phrase like takbir). */ + private const val PAUSE_MS = 800L + /** Time without anything new recognized after which the user is considered to have paused. */ + private const val RECOGNITION_GAP_MS = 1_500L + /** How often (in ticks) to check for a phone call. */ + private const val CALL_CHECK_TICKS = 5 + // 30 seconds of audio: if inference ever falls this far behind, drop the oldest frames + private const val MAX_QUEUED_FRAMES = 300 + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/MemorizeState.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/MemorizeState.kt new file mode 100644 index 0000000000..ffc830634f --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/MemorizeState.kt @@ -0,0 +1,56 @@ +package com.quran.mobile.feature.memorize.session + +import com.quran.data.model.SuraAyah +import com.quran.mobile.feature.memorize.data.Passage + +/** + * What a memorization session looks like right now. Recitation is sequential, so every word before + * [cursor] has been revealed (recited, given as a hint, or missed) and every word from it on is + * still hidden, unless the user is [peeking]. In [Mode.RECITE] nothing is hidden: the words before + * the cursor are the ones read. + */ +data class MemorizeState( + val id: String, + val passage: Passage, + val startedAt: Long, + val status: Status, + val mode: Mode = Mode.MEMORIZE, + val cursor: Int = 0, + val hinted: Set = emptySet(), + val missed: Set = emptySet(), + /** A hidden word the user got wrong; it is marked but not revealed. */ + val mistake: Int? = null, + val peeking: Boolean = false, + /** The recording of this session, if the user chose to record it. */ + val recordingId: String? = null, + /** + * Whether it is known where the user started (they may start anywhere around the page on screen): + * until then every word is hidden; from then on the words before the start are shown. + */ + val started: Boolean = true, + /** The word the user started at, once [started] (it may be anywhere on the pages on screen). */ + val firstWord: Int = 0, + /** Whether mistakes and skipped words are marked (in [Mode.RECITE] the user may turn them off). */ + val showMistakes: Boolean = true, +) { + enum class Status { PREPARING, LISTENING, PAUSED, FINISHED } + + enum class Mode { + /** Reciting from memory with the mushaf page open: words appear as they are recited. */ + MEMORIZE, + /** Reciting during salah (screen may be off): prayer speech is ignored, hints are spoken. */ + SALAH, + /** Reading with the mushaf page open: nothing is hidden, the words are marked as they are read. */ + RECITE, + } + + val isActive: Boolean get() = status == Status.PREPARING || status == Status.LISTENING || status == Status.PAUSED + + // a block body: lint's Kotlin analysis (AGP 9.4) crashes on this as an expression body + fun isHidden(index: Int): Boolean { + return mode != Mode.RECITE && !peeking && (!started || index >= cursor) + } + + val currentAyah: SuraAyah + get() = passage.ayahOf(cursor.coerceAtMost(passage.words.size - 1)) +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/ProgressSessionResults.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/ProgressSessionResults.kt new file mode 100644 index 0000000000..bf5382b2db --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/ProgressSessionResults.kt @@ -0,0 +1,20 @@ +package com.quran.mobile.feature.memorize.session + +import com.quran.data.di.AppCoroutineScope +import com.quran.data.di.AppScope +import com.quran.mobile.progress.session.SessionLog +import com.quran.mobile.progress.session.SessionRecord +import dev.zacsweers.metro.ContributesBinding +import dev.zacsweers.metro.Inject +import kotlinx.coroutines.launch + +/** Keeps session results in Progress's [SessionLog]. */ +@ContributesBinding(AppScope::class) +class ProgressSessionResults @Inject constructor( + private val sessionLog: SessionLog, + private val scope: AppCoroutineScope, +) : SessionResults { + override fun record(record: SessionRecord) { + scope.launch { sessionLog.record(record) } + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/SessionResults.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/SessionResults.kt new file mode 100644 index 0000000000..f969039f23 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/session/SessionResults.kt @@ -0,0 +1,8 @@ +package com.quran.mobile.feature.memorize.session + +import com.quran.mobile.progress.session.SessionRecord + +/** Where a finished or stopped session's results go (Progress keeps them, if the user lets it). */ +fun interface SessionResults { + fun record(record: SessionRecord) +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/settings/BackgroundListening.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/settings/BackgroundListening.kt new file mode 100644 index 0000000000..2682e51cf5 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/settings/BackgroundListening.kt @@ -0,0 +1,92 @@ +package com.quran.mobile.feature.memorize.settings + +import android.annotation.SuppressLint +import android.app.AlertDialog +import android.content.ActivityNotFoundException +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.PowerManager +import android.provider.Settings +import androidx.core.net.toUri +import com.quran.data.di.AppScope +import com.quran.mobile.feature.memorize.R +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn + +/** + * Helps the user let memorization keep listening with the screen off (salah). Phones stop + * background work to save battery; these are the switches that prevent that, opened directly + * where possible. + */ +@SingleIn(AppScope::class) +class BackgroundListening @Inject constructor() { + + fun isUnrestricted(context: Context): Boolean { + val power = context.getSystemService(PowerManager::class.java) ?: return true + return power.isIgnoringBatteryOptimizations(context.packageName) + } + + fun showSetup(context: Context) { + val steps = buildList { + add(Step(R.string.memorize_background_battery) { requestUnrestrictedBattery(it) }) + if (isXiaomi()) { + add(Step(R.string.memorize_background_autostart) { openXiaomiAutostart(it) }) + add(Step(R.string.memorize_background_no_restrictions) { openXiaomiBatterySaver(it) }) + } + add(Step(R.string.memorize_background_app_settings) { openAppDetails(it) }) + } + val status = context.getString( + if (isUnrestricted(context)) R.string.memorize_background_status_ok else R.string.memorize_background_status_restricted + ) + AlertDialog.Builder(context) + .setTitle(context.getString(R.string.memorize_background_title) + "\n" + status) + .setItems(steps.map { context.getString(it.title) }.toTypedArray()) { _, which -> steps[which].action(context) } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + + private class Step(val title: Int, val action: (Context) -> Unit) + + @SuppressLint("BatteryLife") // the user asked for this from settings, for listening during salah + private fun requestUnrestrictedBattery(context: Context) { + val direct = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, "package:${context.packageName}".toUri()) + if (!launch(context, direct)) { + launch(context, Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) || openAppDetails(context) + } + } + + private fun openXiaomiAutostart(context: Context) { + val intent = Intent().setComponent( + ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity") + ) + launch(context, intent) || openAppDetails(context) + } + + private fun openXiaomiBatterySaver(context: Context) { + val intent = Intent() + .setComponent(ComponentName("com.miui.powerkeeper", "com.miui.powerkeeper.ui.HiddenAppsConfigActivity")) + .putExtra("package_name", context.packageName) + .putExtra("package_label", context.applicationInfo.loadLabel(context.packageManager).toString()) + launch(context, intent) || openAppDetails(context) + } + + private fun openAppDetails(context: Context): Boolean = + launch(context, Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, "package:${context.packageName}".toUri())) + + private fun launch(context: Context, intent: Intent): Boolean = try { + if (context !is android.app.Activity) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) + true + } catch (_: ActivityNotFoundException) { + false + } catch (_: SecurityException) { + false + } + + private fun isXiaomi(): Boolean { + val maker = (Build.MANUFACTURER + " " + Build.BRAND).lowercase() + return "xiaomi" in maker || "redmi" in maker || "poco" in maker + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/settings/MemorizePreferences.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/settings/MemorizePreferences.kt new file mode 100644 index 0000000000..51e0297857 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/settings/MemorizePreferences.kt @@ -0,0 +1,197 @@ +package com.quran.mobile.feature.memorize.settings + +import android.content.Context +import androidx.core.content.edit +import com.quran.data.di.AppScope +import com.quran.mobile.di.qualifier.ApplicationContext +import com.quran.mobile.feature.memorize.recording.RecordingSplit +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.mobile.feature.memorize.tracker.hint.HintConfig +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn + +/** Settings of the memorize feature, kept in their own preferences file. */ +@SingleIn(AppScope::class) +class MemorizePreferences @Inject constructor(@param:ApplicationContext context: Context) { + private val prefs = context.getSharedPreferences("memorize", Context.MODE_PRIVATE) + + /** The prayer corrector (مصحح الصلاة): give the next word when the user is stuck. */ + var correctorEnabled: Boolean + get() = prefs.getBoolean(KEY_CORRECTOR, true) + set(value) = prefs.edit { putBoolean(KEY_CORRECTOR, value) } + + var hintDelaySeconds: Int + get() = prefs.getInt(KEY_DELAY, 4) + set(value) = prefs.edit { putInt(KEY_DELAY, value.coerceIn(2, 15)) } + + var wordsPerHint: Int + get() = prefs.getInt(KEY_WORDS, 1) + set(value) = prefs.edit { putInt(KEY_WORDS, value.coerceIn(1, 5)) } + + var hintOnMistakes: Boolean + get() = prefs.getBoolean(KEY_ON_MISTAKES, true) + set(value) = prefs.edit { putBoolean(KEY_ON_MISTAKES, value) } + + var hintOnPauses: Boolean + get() = prefs.getBoolean(KEY_ON_PAUSES, true) + set(value) = prefs.edit { putBoolean(KEY_ON_PAUSES, value) } + + /** Reading with the text shown (Recitation): mark wrong and skipped words. */ + var reciteMarkMistakes: Boolean + get() = prefs.getBoolean(KEY_RECITE_MARK, true) + set(value) = prefs.edit { putBoolean(KEY_RECITE_MARK, value) } + + /** Reading with the text shown (Recitation): after a mistake, say the correct word in the hint voice. */ + var reciteSayFix: Boolean + get() = prefs.getBoolean(KEY_RECITE_SAY, true) + set(value) = prefs.edit { putBoolean(KEY_RECITE_SAY, value) } + + /** + * Inside an ayah, every word must be heard before the session goes on ("strict"). Off by default + * ("loose"): a word or two the recognizer missed may pass, marked as skipped. Either way no ayah may + * be left out (except in salah). + */ + var everyWordHeard: Boolean + get() = prefs.getBoolean(KEY_EVERY_WORD, false) + set(value) = prefs.edit { putBoolean(KEY_EVERY_WORD, value) } + + /** Treat wrong short vowels (tashkeel) as mistakes. Off by default: fewer false alarms. */ + var strictTashkeel: Boolean + get() = prefs.getBoolean(KEY_STRICT, false) + set(value) = prefs.edit { putBoolean(KEY_STRICT, value) } + + /** The reciter whose voice gives the hints (qari id). Husary Murattal by default. */ + var promptQariId: Int + get() = prefs.getInt(KEY_PROMPT_QARI, 1) + set(value) = prefs.edit { putInt(KEY_PROMPT_QARI, value) } + + /** Download the speech model and the hint voice as needed, without asking during a session. */ + var autoDownload: Boolean + get() = prefs.getBoolean(KEY_AUTO_DOWNLOAD, false) + set(value) = prefs.edit { putBoolean(KEY_AUTO_DOWNLOAD, value) } + + enum class RecordingMode { OFF, ALWAYS, ASK } + + /** Whether sessions are recorded so the user can listen to themselves. Off by default. */ + var recordingMode: RecordingMode + get() = prefs.getString(KEY_RECORDING, null)?.let { runCatching { RecordingMode.valueOf(it) }.getOrNull() } + ?: RecordingMode.OFF + set(value) = prefs.edit { putString(KEY_RECORDING, value.name) } + + /** + * "Record and contribute": every session is recorded, with what the speech model heard, to help + * improve the models (kept on the phone). Off by default. + */ + var contribute: Boolean + get() = prefs.getBoolean(KEY_CONTRIBUTE, false) + set(value) = prefs.edit { putBoolean(KEY_CONTRIBUTE, value) } + + enum class KeepRecordings { + /** Until the user deletes them. */ + ALL, + /** A new recording replaces the older ones that start at the same place. */ + REPLACE_SAME_PLACE, + } + + var keepRecordings: KeepRecordings + get() = prefs.getString(KEY_KEEP_RECORDINGS, null)?.let { runCatching { KeepRecordings.valueOf(it) }.getOrNull() } + ?: KeepRecordings.ALL + set(value) = prefs.edit { putString(KEY_KEEP_RECORDINGS, value.name) } + + var recordingSplit: RecordingSplit + get() = prefs.getString(KEY_RECORDING_SPLIT, null)?.let { runCatching { RecordingSplit.valueOf(it) }.getOrNull() } + ?: RecordingSplit.BY_SURA + set(value) = prefs.edit { putString(KEY_RECORDING_SPLIT, value.name) } + + /** Where the user dragged the floating mic (its offset from the bottom corner), if they did. */ + var micButtonOffset: Pair? + get() = if (prefs.contains(KEY_MIC_X)) prefs.getFloat(KEY_MIC_X, 0f) to prefs.getFloat(KEY_MIC_Y, 0f) else null + set(value) = prefs.edit { + if (value == null) { + remove(KEY_MIC_X) + remove(KEY_MIC_Y) + } else { + putFloat(KEY_MIC_X, value.first) + putFloat(KEY_MIC_Y, value.second) + } + } + + /** + * The double-check: a larger model listens again before a hint or a mistake mark (optional, a + * download; see DoubleCheckAdvice for whether it suits the phone). + */ + var doubleCheck: Boolean + get() = prefs.getBoolean(KEY_DOUBLE_CHECK, false) + set(value) = prefs.edit { putBoolean(KEY_DOUBLE_CHECK, value) } + + /** How long a double-check takes on this phone, in milliseconds (a running estimate; 0: unknown). */ + val doubleCheckMs: Long get() = prefs.getLong(KEY_DOUBLE_CHECK_MS, 0L) + + fun recordDoubleCheckMs(ms: Long) { + if (ms <= 0) return + val previous = doubleCheckMs + prefs.edit { putLong(KEY_DOUBLE_CHECK_MS, if (previous == 0L) ms else (3 * previous + ms) / 4) } + } + + var disclaimerAccepted: Boolean + get() = prefs.getBoolean(KEY_DISCLAIMER, false) + set(value) = prefs.edit { putBoolean(KEY_DISCLAIMER, value) } + + /** Whether hints may need the hint voice in [mode]. */ + fun speaksHints(mode: MemorizeState.Mode): Boolean = + if (mode == MemorizeState.Mode.RECITE) reciteSayFix else correctorEnabled + + fun hintConfig(mode: MemorizeState.Mode = MemorizeState.Mode.MEMORIZE): HintConfig { + val delayMs = hintDelaySeconds * 1_000L + if (mode == MemorizeState.Mode.RECITE) { + // the reader sees the next word: no help when they stop, only the correct word after a + // mistake (the Recitation switches, not the corrector's) + return HintConfig( + delayMs = delayMs, + wordsPerHint = 1, + onMistakes = reciteMarkMistakes || reciteSayFix, + hintAfterMistake = reciteSayFix, + onPauses = false, + wordHintsBeforeLonger = Int.MAX_VALUE, + ) + } + val salah = mode == MemorizeState.Mode.SALAH + return HintConfig( + delayMs = delayMs, + wordsPerHint = wordsPerHint, + onMistakes = correctorEnabled && hintOnMistakes, + onPauses = correctorEnabled && hintOnPauses, + // in salah a pause after an ayah is often ruku: give the takbir time to be recognized + ayahBoundaryDelayMs = if (salah) 2 * delayMs else delayMs, + // spoken hints shouldn't talk over the reciter (see HintConfig) + mistakesWaitForPause = salah, + // in salah a silence that lasts is more often ruku or sujud than being stuck: a word at a time, + // and quiet after a few + wordHintsBeforeLonger = if (salah) Int.MAX_VALUE else 3, + maxConsecutiveHints = if (salah) 3 else 10, + ) + } + + private companion object { + const val KEY_CORRECTOR = "corrector_enabled" + const val KEY_DELAY = "hint_delay_seconds" + const val KEY_WORDS = "words_per_hint" + const val KEY_ON_MISTAKES = "hint_on_mistakes" + const val KEY_ON_PAUSES = "hint_on_pauses" + const val KEY_STRICT = "strict_tashkeel" + const val KEY_RECITE_MARK = "recite_mark_mistakes" + const val KEY_RECITE_SAY = "recite_say_fix" + const val KEY_EVERY_WORD = "every_word_heard" + const val KEY_DISCLAIMER = "disclaimer_accepted" + const val KEY_PROMPT_QARI = "prompt_qari" + const val KEY_AUTO_DOWNLOAD = "auto_download" + const val KEY_RECORDING = "recording_mode" + const val KEY_CONTRIBUTE = "contribute" + const val KEY_KEEP_RECORDINGS = "keep_recordings" + const val KEY_RECORDING_SPLIT = "recording_split" + const val KEY_MIC_X = "mic_button_x" + const val KEY_MIC_Y = "mic_button_y" + const val KEY_DOUBLE_CHECK = "double_check" + const val KEY_DOUBLE_CHECK_MS = "double_check_ms" + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/settings/MemorizePreferencesProvider.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/settings/MemorizePreferencesProvider.kt new file mode 100644 index 0000000000..df689b3f25 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/settings/MemorizePreferencesProvider.kt @@ -0,0 +1,467 @@ +package com.quran.mobile.feature.memorize.settings + +import android.app.AlertDialog +import android.content.Context +import android.content.Intent +import android.text.format.Formatter +import androidx.preference.ListPreference +import androidx.preference.Preference +import androidx.preference.PreferenceCategory +import androidx.preference.PreferenceDataStore +import androidx.preference.PreferenceGroup +import androidx.preference.SwitchPreferenceCompat +import com.quran.data.di.AppScope +import com.quran.mobile.di.ExtraPreferencesProvider +import com.quran.mobile.feature.memorize.R +import com.quran.mobile.feature.memorize.check.DoubleCheckAdvice +import com.quran.mobile.feature.memorize.check.DoubleCheckModel +import com.quran.mobile.feature.memorize.model.ModelImportActivity +import com.quran.mobile.feature.memorize.model.SpeechModelStore +import com.quran.mobile.feature.memorize.prompt.HintVoiceDownloads +import com.quran.mobile.feature.memorize.prompt.PromptPlayer +import com.quran.mobile.feature.memorize.recording.RecordingSplit +import com.quran.mobile.feature.memorize.recording.RecordingsActivity +import dev.zacsweers.metro.ContributesIntoSet +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** The "Memorize" section of the app's settings, including the prayer corrector. */ +@SingleIn(AppScope::class) +@ContributesIntoSet(AppScope::class) +@Inject +class MemorizePreferencesProvider( + private val preferences: MemorizePreferences, + private val models: SpeechModelStore, + private val backgroundListening: BackgroundListening, + private val promptPlayer: PromptPlayer, + private val voiceDownloads: HintVoiceDownloads, + private val doubleCheck: DoubleCheckModel, + private val doubleCheckAdvice: DoubleCheckAdvice, +) : ExtraPreferencesProvider { + + override val order: Int = 10 + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + // keeps the double-check's summary up to date (its download), for the settings screen shown last + private var doubleCheckSummaryJob: Job? = null + + private val store = object : PreferenceDataStore() { + override fun getBoolean(key: String, defValue: Boolean): Boolean = when (key) { + KEY_CORRECTOR -> preferences.correctorEnabled + KEY_ON_MISTAKES -> preferences.hintOnMistakes + KEY_ON_PAUSES -> preferences.hintOnPauses + KEY_STRICT -> preferences.strictTashkeel + KEY_RECITE_MARK -> preferences.reciteMarkMistakes + KEY_RECITE_SAY -> preferences.reciteSayFix + KEY_AUTO_DOWNLOAD -> preferences.autoDownload + KEY_DOUBLE_CHECK -> preferences.doubleCheck + KEY_CONTRIBUTE -> preferences.contribute + else -> defValue + } + + override fun putBoolean(key: String, value: Boolean) { + when (key) { + KEY_CORRECTOR -> preferences.correctorEnabled = value + KEY_ON_MISTAKES -> preferences.hintOnMistakes = value + KEY_ON_PAUSES -> preferences.hintOnPauses = value + KEY_STRICT -> preferences.strictTashkeel = value + KEY_RECITE_MARK -> preferences.reciteMarkMistakes = value + KEY_RECITE_SAY -> preferences.reciteSayFix = value + KEY_AUTO_DOWNLOAD -> preferences.autoDownload = value + KEY_DOUBLE_CHECK -> preferences.doubleCheck = value + KEY_CONTRIBUTE -> preferences.contribute = value + } + } + + override fun getString(key: String, defValue: String?): String? = when (key) { + KEY_DELAY -> preferences.hintDelaySeconds.toString() + KEY_WORDS -> preferences.wordsPerHint.toString() + KEY_VOICE -> preferences.promptQariId.toString() + KEY_RECORDING -> preferences.recordingMode.name + KEY_RECORDING_SPLIT -> preferences.recordingSplit.name + KEY_KEEP_RECORDINGS -> preferences.keepRecordings.name + KEY_MISSED_WORDS -> if (preferences.everyWordHeard) STRICT else LOOSE + else -> defValue + } + + override fun putString(key: String, value: String?) { + when (key) { + KEY_RECORDING -> MemorizePreferences.RecordingMode.entries.firstOrNull { it.name == value } + ?.let { preferences.recordingMode = it } + KEY_RECORDING_SPLIT -> RecordingSplit.entries.firstOrNull { it.name == value }?.let { preferences.recordingSplit = it } + KEY_KEEP_RECORDINGS -> MemorizePreferences.KeepRecordings.entries.firstOrNull { it.name == value } + ?.let { preferences.keepRecordings = it } + KEY_MISSED_WORDS -> preferences.everyWordHeard = value == STRICT + } + val number = value?.toIntOrNull() ?: return + when (key) { + KEY_DELAY -> preferences.hintDelaySeconds = number + KEY_WORDS -> preferences.wordsPerHint = number + KEY_VOICE -> preferences.promptQariId = number + } + } + } + + override fun addPreferences(root: PreferenceGroup) { + val context = root.context + val category = PreferenceCategory(context).apply { + key = KEY_CATEGORY + title = context.getString(R.string.memorize_settings_category) + isIconSpaceReserved = false + } + root.addPreference(category) + + category.addPreference(SwitchPreferenceCompat(context).apply { + setup(KEY_CORRECTOR, R.string.memorize_corrector_title, R.string.memorize_corrector_summary) + }) + category.addPreference(ListPreference(context).apply { + setup(KEY_DELAY, R.string.memorize_delay_title, null) + entryValues = arrayOf("2", "3", "4", "5", "7", "10", "15") + entries = entryValues.map { + context.resources.getQuantityString(R.plurals.memorize_seconds, it.toString().toInt(), it.toString().toInt()) + }.toTypedArray() + summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() + }) + category.addPreference(ListPreference(context).apply { + setup(KEY_WORDS, R.string.memorize_words_title, null) + entryValues = arrayOf("1", "2", "3", "5") + entries = entryValues.map { + context.resources.getQuantityString(R.plurals.memorize_words, it.toString().toInt(), it.toString().toInt()) + }.toTypedArray() + summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() + }) + category.addPreference(SwitchPreferenceCompat(context).apply { + setup(KEY_ON_MISTAKES, R.string.memorize_on_mistakes_title, R.string.memorize_on_mistakes_summary) + }) + category.addPreference(SwitchPreferenceCompat(context).apply { + setup(KEY_ON_PAUSES, R.string.memorize_on_pauses_title, R.string.memorize_on_pauses_summary) + }) + val voices = promptPlayer.availableVoices() + if (voices.isNotEmpty()) { + category.addPreference(ListPreference(context).apply { + setup(KEY_VOICE, R.string.memorize_voice_title, null) + entryValues = voices.map { it.toString() }.toTypedArray() + entries = voices.map { id -> promptPlayer.voiceName(id)?.let { context.getString(it) } ?: id.toString() } + .toTypedArray() + summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() + }) + } + category.addPreference(ListPreference(context).apply { + setup(KEY_MISSED_WORDS, R.string.memorize_missed_words_title, null) + entryValues = arrayOf(LOOSE, STRICT) + entries = arrayOf( + context.getString(R.string.memorize_missed_words_loose), + context.getString(R.string.memorize_missed_words_strict), + ) + summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() + }) + // reading with the text shown has its own switches (the reader sees the next word) + category.addPreference(SwitchPreferenceCompat(context).apply { + setup(KEY_RECITE_MARK, R.string.memorize_recite_mark_title, R.string.memorize_recite_mark_summary) + }) + category.addPreference(SwitchPreferenceCompat(context).apply { + setup(KEY_RECITE_SAY, R.string.memorize_recite_say_title, R.string.memorize_recite_say_summary) + }) + category.addPreference(SwitchPreferenceCompat(context).apply { + setup(KEY_STRICT, R.string.memorize_strict_title, R.string.memorize_strict_summary) + }) + category.addPreference(Preference(context).apply { + setup(KEY_BACKGROUND, R.string.memorize_background_title, R.string.memorize_background_summary) + }) + category.addPreference(ListPreference(context).apply { + setup(KEY_RECORDING, R.string.memorize_recording_title, null) + entryValues = MemorizePreferences.RecordingMode.entries.map { it.name }.toTypedArray() + entries = arrayOf( + context.getString(R.string.memorize_recording_off), + context.getString(R.string.memorize_recording_always), + context.getString(R.string.memorize_recording_ask), + ) + summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() + }) + category.addPreference(SwitchPreferenceCompat(context).apply { + setup(KEY_CONTRIBUTE, R.string.memorize_contribute_title, R.string.memorize_contribute_summary) + setOnPreferenceChangeListener { preference, value -> + if (value == true) { + // consent: what is kept, and that nothing leaves the phone + AlertDialog.Builder(preference.context) + .setTitle(R.string.memorize_contribute_title) + .setMessage(R.string.memorize_contribute_message) + .setPositiveButton(R.string.memorize_contribute_turn_on) { _, _ -> + (preference as SwitchPreferenceCompat).isChecked = true + } + .setNegativeButton(android.R.string.cancel, null) + .show() + false + } else { + true + } + } + }) + category.addPreference(ListPreference(context).apply { + setup(KEY_RECORDING_SPLIT, R.string.memorize_recording_split_title, null) + entryValues = RecordingSplit.entries.map { it.name }.toTypedArray() + entries = arrayOf( + context.getString(R.string.memorize_recording_split_sura), + context.getString(R.string.memorize_recording_split_session), + ) + summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() + }) + category.addPreference(ListPreference(context).apply { + setup(KEY_KEEP_RECORDINGS, R.string.memorize_keep_recordings_title, null) + entryValues = MemorizePreferences.KeepRecordings.entries.map { it.name }.toTypedArray() + entries = arrayOf( + context.getString(R.string.memorize_keep_recordings_all), + context.getString(R.string.memorize_keep_recordings_replace), + ) + summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() + }) + category.addPreference(Preference(context).apply { + setup(KEY_RECORDINGS, R.string.memorize_sessions_title, R.string.memorize_sessions_summary) + }) + category.addPreference(SwitchPreferenceCompat(context).apply { + setup(KEY_DOUBLE_CHECK, R.string.memorize_double_check_title, null) + setOnPreferenceChangeListener { preference, value -> + onDoubleCheckChange(preference as SwitchPreferenceCompat, value as Boolean) + // set once the user has answered + false + } + doubleCheckSummaryJob?.cancel() + doubleCheckSummaryJob = scope.launch { + doubleCheck.store.state.collect { summary = doubleCheckSummary(context, it) } + } + }) + category.addPreference(SwitchPreferenceCompat(context).apply { + setup(KEY_AUTO_DOWNLOAD, R.string.memorize_auto_download_title, R.string.memorize_auto_download_summary) + }) + category.addPreference(Preference(context).apply { + setup(KEY_OFFLINE, R.string.memorize_offline_title, R.string.memorize_offline_summary) + }) + category.addPreference(Preference(context).apply { + setup(KEY_MODEL, R.string.memorize_model_setting_title, null) + summary = modelSummary(context) + }) + category.addPreference(Preference(context).apply { + setup(KEY_PRIVACY, R.string.memorize_privacy_title, R.string.memorize_privacy_summary) + isSelectable = false + }) + } + + override fun onPreferenceClick(preference: Preference): Boolean { + val context = preference.context + return when (preference.key) { + KEY_MODEL -> { + if (models.isInstalled()) { + AlertDialog.Builder(context) + .setTitle(R.string.memorize_model_setting_title) + .setMessage(context.getString(R.string.memorize_model_delete_message, models.spec.attribution, models.spec.license)) + .setPositiveButton(R.string.memorize_model_delete) { _, _ -> + models.delete() + preference.summary = modelSummary(context) + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } else { + AlertDialog.Builder(context) + .setTitle(R.string.memorize_model_setting_title) + .setMessage( + context.getString( + R.string.memorize_model_missing_message, + models.spec.downloadSize / 1_000_000, models.spec.model.name, models.spec.tokens.name + ) + ) + .setPositiveButton(R.string.memorize_model_import) { _, _ -> + context.startActivity(Intent(context, ModelImportActivity::class.java)) + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + true + } + KEY_BACKGROUND -> { + backgroundListening.showSetup(context) + true + } + KEY_RECORDINGS -> { + context.startActivity(Intent(context, RecordingsActivity::class.java)) + true + } + KEY_OFFLINE -> { + offerOfflineDownload(context) + true + } + else -> false + } + } + + private fun onDoubleCheckChange(preference: SwitchPreferenceCompat, on: Boolean) { + val context = preference.context + val size = Formatter.formatShortFileSize(context, DoubleCheckModel.SPEC.downloadSize) + when { + on && doubleCheck.isInstalled -> preference.isChecked = true + on -> AlertDialog.Builder(context) + .setTitle(R.string.memorize_double_check_title) + .setMessage( + context.getString( + R.string.memorize_double_check_download_message, + adviceText(context), size, DoubleCheckModel.SPEC.attribution, DoubleCheckModel.SPEC.license, + ) + ) + .setPositiveButton(R.string.memorize_model_download) { _, _ -> + preference.isChecked = true + doubleCheck.store.startDownload() + } + .setNegativeButton(android.R.string.cancel, null) + .show() + else -> { + preference.isChecked = false + doubleCheck.store.cancelDownload() + if (doubleCheck.isInstalled) { + AlertDialog.Builder(context) + .setTitle(R.string.memorize_double_check_title) + .setMessage(context.getString(R.string.memorize_double_check_delete_message, size)) + .setPositiveButton(R.string.memorize_model_delete) { _, _ -> doubleCheck.delete() } + .setNegativeButton(R.string.memorize_double_check_keep, null) + .show() + } + } + } + } + + private fun doubleCheckSummary(context: Context, state: SpeechModelStore.State): String { + val size = Formatter.formatShortFileSize(context, DoubleCheckModel.SPEC.downloadSize) + val status = when { + state is SpeechModelStore.State.Downloading && state.totalBytes > 0 -> + context.getString(R.string.memorize_double_check_downloading, (100 * state.downloadedBytes / state.totalBytes).toInt()) + state is SpeechModelStore.State.Failed -> context.getString(R.string.memorize_model_failed, state.reason) + preferences.doubleCheck && state !is SpeechModelStore.State.Installed -> + context.getString(R.string.memorize_double_check_not_downloaded) + else -> null + } + return listOfNotNull(context.getString(R.string.memorize_double_check_summary, size), adviceText(context), status) + .joinToString(" ") + } + + /** Whether the double-check suits this phone, and why. */ + private fun adviceText(context: Context): String { + val advice = doubleCheckAdvice.advice() + val seconds = String.format(java.util.Locale.getDefault(), "%.1f", advice.checkMs / 1000.0) + return when (advice.reason) { + DoubleCheckAdvice.Reason.SUITS -> context.getString(R.string.memorize_double_check_recommended) + DoubleCheckAdvice.Reason.FAST -> context.getString(R.string.memorize_double_check_recommended_fast, seconds) + DoubleCheckAdvice.Reason.LOW_MEMORY -> context.getString( + R.string.memorize_double_check_low_memory, Formatter.formatShortFileSize(context, advice.memoryBytes), + ) + DoubleCheckAdvice.Reason.OLD_PROCESSOR -> context.getString(R.string.memorize_double_check_old_processor) + DoubleCheckAdvice.Reason.SLOW -> context.getString(R.string.memorize_double_check_slow, seconds) + } + } + + /** The speech model and the hint voice for the whole Quran, in one go. */ + private fun offerOfflineDownload(context: Context) { + scope.launch { + // reads the reciter's timings and files + val voice = voiceDownloads.voice() + val missing = withContext(Dispatchers.IO) { voiceDownloads.missing() } + val voiceSize = withContext(Dispatchers.IO) { voiceDownloads.size(missing) } + val modelMissing = !models.isInstalled() + // the double-check where it is on, or where it suits the phone + val offerCheck = !doubleCheck.isInstalled && (preferences.doubleCheck || doubleCheckAdvice.advice().recommended) + val size = { bytes: Long -> Formatter.formatShortFileSize(context, bytes) } + val lines = buildList { + add( + if (modelMissing) { + context.getString(R.string.memorize_offline_model, size(models.spec.downloadSize)) + } else { + context.getString(R.string.memorize_offline_model_done) + } + ) + if (offerCheck) { + add(context.getString(R.string.memorize_offline_check, size(DoubleCheckModel.SPEC.downloadSize))) + } else if (preferences.doubleCheck) { + add(context.getString(R.string.memorize_offline_check_done)) + } + if (voice != null) { + val name = context.getString(voice.nameResource) + add( + when { + missing.isEmpty() -> context.getString(R.string.memorize_offline_voice_done, name) + voiceSize != null -> context.getString(R.string.memorize_offline_voice, name, 114 - missing.size, size(voiceSize)) + else -> context.getString(R.string.memorize_offline_voice_unknown, name, 114 - missing.size) + } + ) + } + } + val nothingToDo = !modelMissing && missing.isEmpty() && !offerCheck + AlertDialog.Builder(context) + .setTitle(R.string.memorize_offline_title) + .setMessage( + lines.joinToString("\n\n") + if (nothingToDo) "" else "\n\n" + context.getString(R.string.memorize_offline_wifi) + ) + .apply { + if (nothingToDo) { + setPositiveButton(android.R.string.ok, null) + } else { + setPositiveButton(R.string.memorize_model_download) { _, _ -> + if (modelMissing) models.startDownload() + voiceDownloads.download(missing) + if (offerCheck) { + preferences.doubleCheck = true + doubleCheck.store.startDownload() + } + } + setNegativeButton(android.R.string.cancel, null) + } + } + .show() + } + } + + private fun modelSummary(context: Context): String = + if (models.isInstalled()) { + context.getString(R.string.memorize_model_installed, models.spec.attribution) + } else { + context.getString(R.string.memorize_model_not_installed) + } + + private fun Preference.setup(key: String, title: Int, summary: Int?) { + this.key = key + this.preferenceDataStore = store + this.isIconSpaceReserved = false + this.isPersistent = true + setTitle(title) + if (summary != null) setSummary(summary) + } + + private companion object { + const val KEY_CATEGORY = "memorize_category" + const val KEY_CORRECTOR = "memorize_corrector" + const val KEY_DELAY = "memorize_delay" + const val KEY_WORDS = "memorize_words" + const val KEY_ON_MISTAKES = "memorize_on_mistakes" + const val KEY_ON_PAUSES = "memorize_on_pauses" + const val KEY_VOICE = "memorize_voice" + const val KEY_STRICT = "memorize_strict" + const val KEY_RECITE_MARK = "memorize_recite_mark" + const val KEY_RECITE_SAY = "memorize_recite_say" + const val KEY_MISSED_WORDS = "memorize_missed_words" + const val LOOSE = "loose" + const val STRICT = "strict" + const val KEY_BACKGROUND = "memorize_background" + const val KEY_MODEL = "memorize_model" + const val KEY_AUTO_DOWNLOAD = "memorize_auto_download" + const val KEY_DOUBLE_CHECK = "memorize_double_check" + const val KEY_OFFLINE = "memorize_offline" + const val KEY_RECORDING = "memorize_recording" + const val KEY_RECORDING_SPLIT = "memorize_recording_split" + const val KEY_KEEP_RECORDINGS = "memorize_keep_recordings" + const val KEY_RECORDINGS = "memorize_recordings" + const val KEY_CONTRIBUTE = "memorize_contribute" + const val KEY_PRIVACY = "memorize_privacy" + } +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/ui/MemorizeIcons.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/ui/MemorizeIcons.kt new file mode 100644 index 0000000000..c9165f4c96 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/ui/MemorizeIcons.kt @@ -0,0 +1,97 @@ +package com.quran.mobile.feature.memorize.ui + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.PathParser +import androidx.compose.ui.unit.dp + +/** Icons the app's shared set doesn't have (paths from Material Icons, Apache-2.0). */ +internal object MemorizeIcons { + val Delete: ImageVector by lazy { + icon("Delete", "M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6v12zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z") + } + + val Export: ImageVector by lazy { + icon("Export", "M19,9h-4V3H9v6H5l7,7 7,-7zM5,18v2h14v-2H5z") + } + + val MicOff: ImageVector by lazy { + icon( + "MicOff", + "M19,11h-1.7c0,0.74 -0.16,1.43 -0.43,2.05l1.23,1.23c0.56,-0.98 0.9,-2.09 0.9,-3.28zM14.98,11.17" + + "c0,-0.06 0.02,-0.11 0.02,-0.17L15,5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v0.18l5.98,5.99zM4.27,3L3,4.27" + + "l6.01,6.01L9.01,11c0,1.66 1.33,3 2.99,3 0.22,0 0.44,-0.03 0.65,-0.08l1.66,1.66c-0.71,0.33 -1.5,0.52" + + " -2.31,0.52 -2.76,0 -5.3,-2.1 -5.3,-5.1L5,11c0,3.41 2.72,6.23 6,6.72L11,21h2v-3.28c0.91,-0.13 1.77," + + "-0.45 2.54,-0.9L19.73,21 21,19.73 4.27,3z" + ) + } + + /** Memorization: the page is hidden. */ + val VisibilityOff: ImageVector by lazy { + icon( + "VisibilityOff", + "M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5" + + "-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12" + + "c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55" + + "c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24" + + "-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z" + ) + } + + /** Salah. */ + val Mosque: ImageVector by lazy { + icon( + "Mosque", + "M7,8h10c0.29,0,0.57,0.06,0.84,0.13C17.93,7.8,18,7.46,18,7.09c0-1.31-0.65-2.53-1.74-3.25L12,1L7.74,3.84" + + " C6.65,4.56,6,5.78,6,7.09C6,7.46,6.07,7.8,6.16,8.13C6.43,8.06,6.71,8,7,8z", + "M24,7c0-1.1-2-3-2-3s-2,1.9-2,3c0,0.74,0.4,1.38,1,1.72V13h-2v-2c0-1.1-0.9-2-2-2H7c-1.1,0-2,0.9-2,2v2H3V8.72" + + " C3.6,8.38,4,7.74,4,7c0-1.1-2-3-2-3S0,5.9,0,7c0,0.74,0.4,1.38,1,1.72V21h9v-4c0-1.1,0.9-2,2-2s2,0.9,2,2v4h9V8.72" + + " C23.6,8.38,24,7.74,24,7z", + ) + } + + val Replay5: ImageVector by lazy { + icon( + "Replay5", + "M12,5V1L7,6l5,5V7c3.31,0,6,2.69,6,6s-2.69,6-6,6s-6-2.69-6-6H4c0,4.42,3.58,8,8,8s8-3.58,8-8S16.42,5,12,5z", + "M10.69,13.9l0.25-2.17h2.39v0.71h-1.7l-0.11,0.92c0.03-0.02,0.07-0.03,0.11-0.05s0.09-0.04,0.15-0.05" + + " s0.12-0.03,0.18-0.04s0.13-0.02,0.2-0.02c0.21,0,0.39,0.03,0.55,0.1s0.3,0.16,0.41,0.28s0.2,0.27,0.25,0.45" + + "s0.09,0.38,0.09,0.6 c0,0.19-0.03,0.37-0.09,0.54s-0.15,0.32-0.27,0.45s-0.27,0.24-0.45,0.31s-0.39,0.12-0.64,0.12" + + "c-0.18,0-0.36-0.03-0.53-0.08 s-0.32-0.14-0.46-0.24s-0.24-0.24-0.32-0.39s-0.13-0.33-0.13-0.53h0.84" + + "c0.02,0.18,0.08,0.32,0.19,0.41s0.25,0.15,0.42,0.15 c0.11,0,0.2-0.02,0.27-0.06s0.14-0.1,0.18-0.17" + + "s0.08-0.15,0.11-0.25s0.03-0.2,0.03-0.31s-0.01-0.21-0.04-0.31 s-0.07-0.17-0.13-0.24s-0.13-0.12-0.21-0.15" + + "s-0.19-0.05-0.3-0.05c-0.08,0-0.15,0.01-0.2,0.02s-0.11,0.03-0.15,0.05 s-0.08,0.05-0.12,0.07s-0.07,0.06-0.1,0.09" + + "L10.69,13.9z", + ) + } + + val Forward5: ImageVector by lazy { + icon( + "Forward5", + "M18,13c0,3.31-2.69,6-6,6s-6-2.69-6-6s2.69-6,6-6v4l5-5l-5-5v4c-4.42,0-8,3.58-8,8c0,4.42,3.58,8,8,8" + + "c4.42,0,8-3.58,8-8 H18z", + "M12.03,15.38c-0.44,0-0.58-0.31-0.6-0.56h-0.84c0.03,0.85,0.79,1.25,1.44,1.25c0.93,0,1.44-0.63,1.44-1.43" + + " c0-1.33-0.97-1.44-1.3-1.44c-0.2,0-0.43,0.05-0.64,0.16l0.11-0.92h1.7v-0.71h-2.39l-0.25,2.17l0.67,0.17" + + " c0.13-0.13,0.28-0.23,0.57-0.23c0.4,0,0.69,0.23,0.69,0.75C12.62,14.64,12.65,15.38,12.03,15.38z", + ) + } + + val MoreVert: ImageVector by lazy { + icon( + "MoreVert", + "M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6" + + "c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z", + ) + } + + /** A recording (the empty sessions list). */ + val GraphicEq: ImageVector by lazy { + icon("GraphicEq", "M7 18h2V6H7v12zm4 4h2V2h-2v20zm-8-8h2v-4H3v4zm12 4h2V6h-2v12zm4-8v4h2v-4h-2z") + } + + private fun icon(name: String, vararg paths: String): ImageVector = + ImageVector.Builder(name, 24.dp, 24.dp, 24f, 24f) + .apply { paths.forEach { addPath(PathParser().parsePathString(it).toNodes(), fill = SolidColor(Color.Black)) } } + .build() +} diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/ui/MemorizeMicButton.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/ui/MemorizeMicButton.kt new file mode 100644 index 0000000000..6526d7a6f3 --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/ui/MemorizeMicButton.kt @@ -0,0 +1,177 @@ +package com.quran.mobile.feature.memorize.ui + +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.scale +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.quran.labs.androidquran.common.ui.core.QuranIcons +import com.quran.mobile.feature.memorize.R + +/** What the floating mic button shows. */ +internal data class MicButtonState( + /** No session yet: the button starts one. */ + val idle: Boolean, + val listening: Boolean, + val preparing: Boolean, + val recording: Boolean, + val canReplay: Boolean, + val replaying: Boolean, + /** Reading with the text shown (Recitation), not memorizing. */ + val reciting: Boolean = false, +) + +/** + * The floating mic of the reading screen: green before a session (tap to start on the pages on + * screen, long press to choose memorize or salah), blue and pulsing while it listens (with a red dot + * when the session is recorded), grey while paused, with buttons to end the session and to listen + * to the recording. + */ +@Composable +internal fun MemorizeMicButton( + state: MicButtonState, + onToggle: () -> Unit, + onChooseMode: () -> Unit, + onEnd: () -> Unit, + onReplay: () -> Unit, +) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + if (!state.listening && !state.idle) { + SmallButton( + QuranIcons.Close, + stringResource(if (state.reciting) R.string.memorize_mic_end_recite else R.string.memorize_mic_end), + onEnd, + ) + if (state.canReplay) { + SmallButton( + if (state.replaying) QuranIcons.Pause else QuranIcons.PlayArrow, + stringResource(if (state.replaying) R.string.memorize_mic_replay_pause else R.string.memorize_mic_replay), + onReplay, + ) + } + } + Box(contentAlignment = Alignment.Center, modifier = Modifier.size(80.dp)) { + if (state.listening) Pulse() + val description = stringResource( + when { + state.idle -> R.string.memorize_mic_start + state.listening -> R.string.memorize_mic_pause + else -> R.string.memorize_mic_resume + } + ) + val chooseMode = stringResource(R.string.memorize_mic_more_ways) + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .size(60.dp) + .clip(CircleShape) + .background( + when { + state.idle -> READY + state.listening -> LISTENING + else -> MaterialTheme.colorScheme.surfaceVariant + } + ) + .semantics { contentDescription = description } + .combinedClickable( + role = Role.Button, + onClick = onToggle, + onLongClickLabel = chooseMode, + onLongClick = if (state.idle) onChooseMode else null, + ), + ) { + Icon( + imageVector = if (state.listening || state.idle) QuranIcons.Mic else MemorizeIcons.MicOff, + contentDescription = null, + tint = if (state.listening || state.idle) Color.White else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(30.dp), + ) + if (state.preparing) { + CircularProgressIndicator(color = Color.White, strokeWidth = 2.dp, modifier = Modifier.size(56.dp)) + } + } + if (state.recording) { + Box( + modifier = Modifier + .align(Alignment.TopEnd) + .padding(top = 12.dp, end = 12.dp) + .size(14.dp) + .clip(CircleShape) + .background(RECORDING) + .border(2.dp, Color.White, CircleShape) + ) + } + } + } +} + +@Composable +private fun Pulse() { + val transition = rememberInfiniteTransition(label = "listening") + val progress = transition.animateFloat( + initialValue = 0f, + targetValue = 1f, + animationSpec = infiniteRepeatable(tween(1_400, easing = LinearEasing), RepeatMode.Restart), + label = "pulse", + ) + Box( + modifier = Modifier + .size(60.dp) + .scale(1f + 0.35f * progress.value) + .graphicsLayer { alpha = 0.45f * (1f - progress.value) } + .clip(CircleShape) + .background(LISTENING) + ) +} + +@Composable +private fun SmallButton(icon: ImageVector, description: String, onClick: () -> Unit, size: Dp = 44.dp) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.surfaceVariant, + shadowElevation = 3.dp, + modifier = Modifier.size(size), + ) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .semantics { contentDescription = description } + .clickable(role = Role.Button, onClick = onClick), + ) { + Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} + +private val READY = Color(0xFF43A047) +private val LISTENING = Color(0xFF1E88E5) +private val RECORDING = Color(0xFFE53935) diff --git a/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/ui/ModeSheet.kt b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/ui/ModeSheet.kt new file mode 100644 index 0000000000..827838a18f --- /dev/null +++ b/feature/memorize/src/main/kotlin/com/quran/mobile/feature/memorize/ui/ModeSheet.kt @@ -0,0 +1,340 @@ +package com.quran.mobile.feature.memorize.ui + +import android.app.Activity +import android.view.ViewGroup +import androidx.compose.foundation.background +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.height +import androidx.compose.material3.Surface +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.RectangleShape +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import com.quran.labs.androidquran.common.ui.core.QuranIcons +import com.quran.labs.androidquran.common.ui.core.QuranTheme +import com.quran.mobile.feature.memorize.R +import com.quran.mobile.feature.memorize.session.MemorizeState +import kotlinx.coroutines.launch + +/** What the mode window shows: where the session starts, the ways to recite, and whether it records. */ +internal data class ModeSheetState( + /** E.g. "Al-Mulk, ayah 1". */ + val start: String, + val modes: List, + val record: RecordLine, +) { + /** Whether the session will be recorded, and whether the user decides it here. */ + sealed interface RecordLine { + /** Not recorded. */ + data object Off : RecordLine + + /** Recorded for "Record and contribute". */ + data object Contributing : RecordLine + + /** Recorded: "Record my recitation" is on. */ + data object Always : RecordLine + + /** "Record my recitation" asks each time: the user decides here. */ + data object Ask : RecordLine + } +} + +/** + * The window the microphone opens: Memorization or Recitation (and salah after a long press). + * Choosing one starts the session at once. + */ +internal object ModeSheet { + + fun show( + activity: Activity, + state: ModeSheetState, + onChoose: (mode: MemorizeState.Mode, record: Boolean) -> Unit, + onCancel: () -> Unit, + ) { + val root = activity.findViewById(android.R.id.content) ?: return + val host = ComposeView(activity) + host.setContent { + QuranTheme { + ModeBottomSheet( + state = state, + onChoose = { mode, record -> + root.removeView(host) + onChoose(mode, record) + }, + onCancel = { + root.removeView(host) + onCancel() + }, + ) + } + } + // the sheet is a window of its own: its host takes no room + root.addView(host, ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun ModeBottomSheet( + state: ModeSheetState, + onChoose: (MemorizeState.Mode, Boolean) -> Unit, + onCancel: () -> Unit, +) { + val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + val scope = rememberCoroutineScope() + ModalBottomSheet( + onDismissRequest = onCancel, + sheetState = sheetState, + // on a tablet the ways to recite sit side by side, so the sheet may be wider than a phone's + sheetMaxWidth = 840.dp, + dragHandle = null, + shape = RectangleShape, + containerColor = Color.Transparent, + contentWindowInsets = { WindowInsets(0, 0, 0, 0) }, + contentColor = MaterialTheme.colorScheme.onSurface, + ) { + ModeSheetContent(state) { mode, record -> + scope.launch { sheetState.hide() }.invokeOnCompletion { onChoose(mode, record) } + } + } +} + +@Composable +internal fun ModeSheetContent( + state: ModeSheetState, + modifier: Modifier = Modifier, + onChoose: (MemorizeState.Mode, Boolean) -> Unit, +) { + var recordThis by rememberSaveable { mutableStateOf(false) } + val record = when (state.record) { + ModeSheetState.RecordLine.Off -> false + ModeSheetState.RecordLine.Contributing, ModeSheetState.RecordLine.Always -> true + ModeSheetState.RecordLine.Ask -> recordThis + } + Column( + modifier = modifier + .fillMaxWidth() + .clip(RoundedCornerShape(topStart = 22.dp, topEnd = 22.dp)) + .background(MaterialTheme.colorScheme.surfaceContainerHighest) + .navigationBarsPadding() + .padding(bottom = 8.dp) + ) { + Box( + modifier = Modifier + .align(Alignment.CenterHorizontally) + .padding(top = 18.dp) + .size(width = 36.dp, height = 4.dp) + .clip(RoundedCornerShape(percent = 100)) + .background(MaterialTheme.colorScheme.outlineVariant) + ) + Text( + text = stringResource(R.string.memorize_sheet_title), + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(top = 14.dp, start = 18.dp, end = 18.dp), + ) + Text( + text = stringResource(R.string.memorize_sheet_start, state.start), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 6.dp, bottom = 12.dp, start = 18.dp, end = 18.dp), + ) + BoxWithConstraints { + // side by side where there's room for them (a tablet), else one under the other + val cards = maxWidth >= 600.dp + val choices: @Composable (Modifier) -> Unit = { item -> + state.modes.forEachIndexed { index, mode -> + if (index > 0 && !cards) SheetDivider() + val (icon, title, description) = when (mode) { + MemorizeState.Mode.MEMORIZE -> Triple( + MemorizeIcons.VisibilityOff, + stringResource(R.string.memorize_mode_memorize_title), + stringResource(R.string.memorize_mode_memorize_description), + ) + MemorizeState.Mode.RECITE -> Triple( + QuranIcons.MenuBook, + stringResource(R.string.memorize_mode_recite_title), + stringResource(R.string.memorize_mode_recite_description), + ) + MemorizeState.Mode.SALAH -> Triple( + MemorizeIcons.Mosque, + stringResource(R.string.memorize_mode_salah_title), + stringResource(R.string.memorize_mode_salah_description), + ) + } + if (cards) { + ModeCard(icon, title, description, item) { onChoose(mode, record) } + } else { + ModeRow(icon, title, description) { onChoose(mode, record) } + } + } + } + if (cards) { + Row( + horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min).padding(horizontal = 18.dp, vertical = 8.dp), + ) { choices(Modifier.weight(1f).fillMaxHeight()) } + } else { + Column { choices(Modifier) } + } + } + when (state.record) { + ModeSheetState.RecordLine.Off -> Unit + ModeSheetState.RecordLine.Contributing -> { + SheetDivider() + RecordedNote(stringResource(R.string.memorize_sheet_recorded_contribute)) + } + ModeSheetState.RecordLine.Always -> { + SheetDivider() + RecordedNote(stringResource(R.string.memorize_sheet_recorded)) + } + ModeSheetState.RecordLine.Ask -> { + SheetDivider() + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .toggleable(value = recordThis, role = Role.Switch, onValueChange = { recordThis = it }) + .heightIn(min = 56.dp) + .padding(horizontal = 18.dp, vertical = 8.dp), + ) { + Text( + text = stringResource(R.string.memorize_sheet_record_this), + style = MaterialTheme.typography.bodyLarge, + modifier = Modifier.weight(1f), + ) + Switch(checked = recordThis, onCheckedChange = null) + } + } + } + } +} + +@Composable +private fun ModeRow(icon: ImageVector, title: String, description: String, onClick: () -> Unit) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(role = Role.Button, onClick = onClick) + .heightIn(min = 72.dp) + .padding(horizontal = 18.dp, vertical = 14.dp), + ) { + // level with the title, the description runs on below + Icon( + icon, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(top = 1.dp).size(24.dp), + ) + Spacer(Modifier.width(16.dp)) + Column(modifier = Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurface) + Text( + text = description, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 2.dp), + ) + } + } +} + +@Composable +private fun ModeCard(icon: ImageVector, title: String, description: String, modifier: Modifier, onClick: () -> Unit) { + Surface( + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.surface, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), + modifier = modifier, + ) { + Column( + Modifier + .clickable(role = Role.Button, onClick = onClick) + .padding(horizontal = 18.dp, vertical = 16.dp) + ) { + Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(28.dp)) + Text( + title, + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(top = 12.dp), + ) + Text( + description, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 4.dp), + ) + } + } +} + +/** Says the session will be recorded (the user always knows). */ +@Composable +private fun RecordedNote(text: String) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .padding(horizontal = 18.dp, vertical = 12.dp), + ) { + Box( + modifier = Modifier + .padding(horizontal = 8.dp) + .size(8.dp) + .clip(CircleShape) + .background(RecordingRed) + ) + // the text lines up with the ways to recite above + Spacer(Modifier.width(16.dp)) + Text(text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} + +@Composable +private fun SheetDivider() { + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant, modifier = Modifier.padding(horizontal = 18.dp)) +} + +/** The recording dot, as on the floating mic. */ +internal val RecordingRed = Color(0xFFE53935) diff --git a/feature/memorize/src/main/res/drawable/ic_memorize_notification.xml b/feature/memorize/src/main/res/drawable/ic_memorize_notification.xml new file mode 100644 index 0000000000..4168e6f53c --- /dev/null +++ b/feature/memorize/src/main/res/drawable/ic_memorize_notification.xml @@ -0,0 +1,10 @@ + + + diff --git a/feature/memorize/src/main/res/values-ar/strings.xml b/feature/memorize/src/main/res/values-ar/strings.xml new file mode 100644 index 0000000000..9d8881606d --- /dev/null +++ b/feature/memorize/src/main/res/values-ar/strings.xml @@ -0,0 +1,193 @@ + + + احفظ + اقرأ من حفظك: تُخفى الكلمات وتظهر كلما قرأتها قراءة صحيحة، وإذا أخطأت أو توقفت تُعطى الكلمة التالية.\n\nيتم كل ذلك على هذا الجهاز فقط. لا يُسجَّل صوتك إلا إذا شغّلت التسجيل من الإعدادات، وتبقى التسجيلات على هذا الجهاز ولا تُنسخ احتياطيًا ولا تُرسل.\n\nالتصحيح الآلي قد يخطئ ولا يغني عن المعلم المتقن. + فهمت + تنزيل نموذج التلاوة + متابعة تلاوتك تحتاج إلى نموذج للتعرف على الكلام (%1$d ميجابايت) يُنزَّل مرة واحدة، وبعدها يعمل الحفظ دون اتصال بالإنترنت تمامًا.\n\nالنموذج: %2$s، %3$s. + تنزيل + جارٍ تنزيل نموذج التلاوة… + تعذّر تنزيل النموذج: %1$s + يحتاج الحفظ إلى الميكروفون لمتابعة تلاوتك. + يستمع إلى تلاوتك + الحفظ متوقف مؤقتًا + إيقاف مؤقت + متابعة + إنهاء + الحفظ + مصحح الصلاة + إذا أخطأت أو توقفت تُعطى الكلمة التالية بصوت القارئ، كلمةً بعد كلمة حتى تكمل + الانتظار قبل المساعدة + + %1$d ثانية + ثانية واحدة + ثانيتان + %1$d ثوانٍ + %1$d ثانية + %1$d ثانية + + + %1$d كلمة في كل مرة + كلمة واحدة في كل مرة + كلمتان في كل مرة + %1$d كلمات في كل مرة + %1$d كلمة في كل مرة + %1$d كلمة في كل مرة + + عدد الكلمات في كل مرة + المساعدة بعد الخطأ + يُعلَّم موضع الكلمة الخاطئة دون إظهارها، فإن لم تصححها تُعطى الكلمة الصحيحة + المساعدة عند التوقف + إعطاء الكلمة التالية إذا سكتّ + صوت المساعدة + التحقق من التشكيل + اعتبار الخطأ في الحركات خطأً أيضًا (تنبيهات خاطئة أكثر) + الاستماع والشاشة مطفأة + لاستخدام مصحح الصلاة أثناء الصلاة: السماح للتطبيق بمواصلة الاستماع في الخلفية + الاستماع في الخلفية مسموح. + قد يوقف الهاتف الاستماع لتوفير البطارية. + السماح باستخدام البطارية دون قيود + السماح بالتشغيل التلقائي (شاومي) + موفر البطارية: بلا قيود (شاومي) + فتح إعدادات التطبيق + نموذج التلاوة + مُثبَّت: %1$s + لم يُنزَّل بعد، ويُنزَّل عند أول استخدام للحفظ + %1$s، %2$s.\n\nهل تريد حذفه لتوفير المساحة؟ سيُنزَّل مرة أخرى عند الحفظ. + حذف + يُنزَّل نموذج التلاوة (%1$d ميجابايت) عند أول استخدام للحفظ. ولإعداده دون إنترنت، انسخ الملفين %2$s و%3$s (أو ملف ‎.zip الذي يضمهما) إلى الهاتف ثم استوردهما واحدًا تلو الآخر. + استيراد الملفات + تم تثبيت نموذج التلاوة + هذه الملفات ليست نموذج التلاوة + الخصوصية + تُعالَج تلاوتك على هذا الجهاز فقط. لا يُسجَّل شيء إلا إذا شغّلت التسجيل أو «سجّل وساهم»، ولا تغادر التسجيلات الجهاز إلا إذا صدّرتها. ويحفظ «التقدم» أعداد كل جلسة على هذا الجهاز (الإعدادات > التقدم). + التذكير بصوت القارئ + لنطق التذكير دون إنترنت تحتاج إلى تلاوة %1$s. هل تنزّل هذه السورة، أم القرآن كله حتى لا تتوقف أبدًا؟ بدونها يظهر التذكير على الشاشة فقط. ويمكن تشغيل التنزيل التلقائي من الإعدادات. + المتابعة بدون صوت + ضع الهاتف قريبًا أمامك على طرف سجادة الصلاة، فهو يسمعك أفضل على بُعد متر تقريبًا. + تعذّر بدء الحفظ. إن تكرر ذلك فاحذف نموذج التلاوة من الإعدادات ثم نزّله مرة أخرى. + هذه السورة + القرآن كله + القرآن كله (%1$s) + استيراد نموذج التلاوة + اختر %1$s (%2$s) + ✓ %1$s + أو اختر ملف ‎.zip الذي يضم الملفين + تم التثبيت: %1$s + ليس هذا هو الملف المطلوب. اختر %1$s. + لا يحتوي ملف ‎.zip هذا على ملفات النموذج. + تسجيل هذه الجلسة؟ + يمكنك الاستماع إلى نفسك بعد ذلك. يبقى التسجيل على هذا الجهاز. + سجّل + بدون تسجيل + تسجيل تلاوتي + متوقف + دائمًا + اسألني كل مرة + تقسيم التسجيلات + تسجيل لكل سورة + تسجيل لكل جلسة + الاحتفاظ بالتسجيلات + حتى أحذفها + يحل التسجيل الجديد محل القديم للموضع نفسه + تشغيل + إيقاف مؤقت + تصدير الكل + حذف الكل + تم التصدير مع التوقيت (alignment.json) وملف تدريب (manifest.jsonl) + تعذّر تصدير التسجيل + %1$s · جارٍ التسجيل + التنزيل التلقائي + نزّل نموذج التلاوة وصوت التذكير عند الحاجة دون سؤال (قد يستخدم بيانات الجوال) + تنزيل للاستخدام دون إنترنت + نموذج التلاوة وصوت التذكير للقرآن كله دفعة واحدة + نموذج التلاوة: %1$s + نموذج التلاوة: تم التنزيل ✓ + %1$s: نُزّلت %2$d من 114 سورة، ويتبقى %3$s + %1$s: نُزّلت %2$d من 114 سورة + %1$s: نُزّلت السور الـ114 كلها ✓ + يُنصح بالاتصال بشبكة Wi-Fi. يستمر التنزيل في الخلفية. + إيقاف الاستماع مؤقتًا + استئناف الاستماع + إنهاء الحفظ + استمع إلى تلاوتي + إيقاف تلاوتي مؤقتًا + حفظ أو تلاوة + تحقق مزدوج قبل التصحيح + يستمع نموذج أكبر مرة أخرى قبل التذكير أو تمييز الخطأ، فيقل التصحيح الخاطئ (تنزيل %1$s). + يُنصح به لهذا الهاتف. + يُنصح به لهذا الهاتف: يستغرق التحقق نحو %1$s ث هنا. + لا يُنصح به لهذا الهاتف: ذاكرته %1$s، والتحقق يحتاج إلى نحو 300 ميجابايت إضافية أثناء التلاوة. + لا يُنصح به لهذا الهاتف: معالجه أقدم من أن يشغّله. + لا يُنصح به لهذا الهاتف: يستغرق التحقق نحو %1$s ث هنا، فيتأخر التذكير. + لم يُنزَّل بعد. + جارٍ التنزيل… %1$d%% + %1$s\n\nيُنزَّل نموذجه (%2$s) مرة واحدة ويعمل دون إنترنت: %3$s، %4$s. + هل تريد حذف نموذج التحقق المزدوج (%1$s) أيضًا؟ يمكن تنزيله مرة أخرى. + إبقاء + نزّل معه التحقق المزدوج (%1$s)، وهو يُنصح به لهذا الهاتف: تذكير وتمييز أخطاء خاطئ أقل + نموذج التحقق المزدوج، يُنصح به لهذا الهاتف: %1$s + نموذج التحقق المزدوج: تم التنزيل ✓ + + التلاوة متوقفة مؤقتًا + إنهاء التلاوة + التلاوة: تمييز الأخطاء + عند القراءة والنص ظاهر، تُميَّز على الصفحة الكلمة الخاطئة أو المتروكة + التلاوة: نطق الكلمة الصحيحة + عند القراءة والنص ظاهر، تُنطق الكلمة الصحيحة بصوت القارئ بعد الخطأ + + كيف تريد أن تقرأ؟ + يبدأ من %1$s + %1$s، الآية %2$d + الحفظ + من حفظك. تُخفى الصفحة، وتظهر الكلمات كلما تلوتها. + التلاوة + قراءةً من المصحف. تبقى الصفحة كما هي، وتُعلَّم الكلمات كلما قرأتها. + في الصلاة + دون لمس والشاشة مطفأة، ويذكّرك إذا توقفت. + تُسجَّل ضمن «سجّل وساهم» + تُسجَّل كما في «تسجيل تلاوتي» + سجّل هذه الجلسة + طرق أخرى للتلاوة، منها الصلاة + + سجّل وساهم + تُحفظ كل جلسة على هذا الجهاز مع ما سمعه نموذج التعرّف على الكلام، للمساعدة في تحسينه. لا يُرسل شيء. + ستُسجَّل على هذا الجهاز كل جلسة حفظ أو تلاوة أو صلاة، مع ما سمعه نموذج التعرّف على الكلام وكيف تابعك التطبيق. يمكن لهذه التسجيلات أن تساعد في تحسين النموذج والتطبيق.\n\nلا يُرسل شيء. تبقى التسجيلات على هذا الجهاز حتى تحذفها، وسيسألك إصدار لاحق قبل مشاركة أي شيء.\n\nيمكنك الاستماع إليها أو تصديرها أو حذفها من «جلسات التسجيل». + تشغيل + جلسات التسجيل + استمع إلى جلساتك على صفحاتها، أو صدّرها أو احذفها + خيارات أخرى + حذف كل جلسات التسجيل؟ + مساهمة + «سجّل وساهم» مفعّل + اليوم + أمس + لا توجد جلسات تسجيل بعد + شغّل «سجّل وساهم» أو «تسجيل تلاوتي» من الإعدادات، ثم اضغط الميكروفون على الصفحة واختر الحفظ أو التلاوة. تظهر هنا كل جلسة تسجّلها. + تصدير الجلسة + حذف الجلسة + حُذفت الجلسة + تراجع + العودة إلى الكلمة + الموضع في التسجيل + رجوع ٥ ثوانٍ + تقديم ٥ ثوانٍ + مقروءة + تلقين + متروكة + أخطاء + + لا جلسات + جلسة واحدة + جلستان + %1$d جلسات + %1$d جلسة + %1$d جلسة + + + الكلمات المتروكة داخل الآية + تجاوز كلمة أو كلمتين (تُعلَّم متروكة) + يجب سماع كل كلمة + اختر جلسة لتشغيلها على صفحاتها. + الجلسة عبر الوقت: أين لُقّنت كلمات أو تُركت أو عُلّمت. اضغط للتشغيل من هناك. + diff --git a/feature/memorize/src/main/res/values/colors.xml b/feature/memorize/src/main/res/values/colors.xml new file mode 100644 index 0000000000..be4504461d --- /dev/null +++ b/feature/memorize/src/main/res/values/colors.xml @@ -0,0 +1,17 @@ + + + + #00000000 + #73E53935 + #FFEF5350 + #5900897B + #FF4DB6AC + #40FB8C00 + #FFCE93D8 + + #291F6FB2 + #38E2AF56 + #661F6FB2 + #8CE2AF56 + diff --git a/feature/memorize/src/main/res/values/strings.xml b/feature/memorize/src/main/res/values/strings.xml new file mode 100644 index 0000000000..ddbfa274b8 --- /dev/null +++ b/feature/memorize/src/main/res/values/strings.xml @@ -0,0 +1,181 @@ + + + Memorize + Recite from memory: the words are hidden and appear as you recite them correctly. If you make a mistake or stop, the next word is given to you.\n\nEverything happens on this device. Your voice is not recorded unless you turn on recording in Settings; recordings stay on this device and are never backed up or sent.\n\nAutomatic feedback can be wrong and does not replace a qualified teacher. + I understand + Download the recitation model + Following your recitation needs a speech model (%1$d MB), downloaded once. After that, memorization works fully offline.\n\nModel: %2$s, %3$s. + Download + Downloading the recitation model… + The model could not be downloaded: %1$s + Memorize needs the microphone to follow your recitation. + Listening to your recitation + Memorization paused + Pause + Resume + Stop + Memorize + Prayer corrector + When you make a mistake or stop, the next word is given to you in the reciter\'s voice, one word at a time until you continue + Wait before helping + + %1$d second + %1$d seconds + + + %1$d word at a time + %1$d words at a time + + Words given each time + Help after a mistake + A wrong word is marked (not shown); if you don\'t correct it, the right word is given + Help when I stop + Give the next word when you stay silent + Voice of the hints + Check tashkeel + Also treat wrong short vowels as mistakes (more false alarms) + Listening with the screen off + For using the prayer corrector during salah: let the app keep listening in the background + Background listening is allowed. + The phone may stop listening to save battery. + Allow unrestricted battery use + Allow autostart (Xiaomi) + Battery saver: No restrictions (Xiaomi) + Open app settings + Recitation model + Installed: %1$s + Not downloaded yet; it is downloaded the first time you memorize + %1$s, %2$s.\n\nDelete it to free space? It will be downloaded again the next time you memorize. + Delete + The recitation model (%1$d MB) is downloaded the first time you memorize. To set it up without internet, copy %2$s and %3$s (or the .zip they came in) to this phone and import them, one at a time. + Import files + The recitation model is installed + These files are not the recitation model + Privacy + Your recitation is processed only on this device. Nothing is recorded unless you turn on recording or Record and contribute, and recordings never leave the device unless you export them. Progress keeps each session\'s counts on this device (Settings > Progress). + Hints in the reciter\'s voice + To speak the hints offline, %1$s\'s recitation is needed. Download this sura, or the whole Quran so that you are never stopped? Without it, hints are only shown. Automatic downloads can be turned on in Settings. + Continue without voice + Place the phone close in front of you, at the edge of your prayer mat. It hears you best within about one meter. + Memorization could not start. If this keeps happening, delete the recitation model in Settings and download it again. + This sura + Whole Quran + Whole Quran (%1$s) + Import the recitation model + Choose %1$s (%2$s) + ✓ %1$s + Or choose the .zip with both files + Installed: %1$s + That isn\'t the right file. Choose %1$s. + That .zip doesn\'t contain the model\'s files. + Record this session? + You can listen to yourself afterwards. The recording stays on this device. + Record + Don\'t record + Record my recitation + Off + Always + Ask each time + Split recordings + A recording per sura + A recording per session + Keep recordings + Until I delete them + Replace the older recording of the same place + Play + Pause + Export all + Delete all + Exported, with its alignment (alignment.json) and a training manifest (manifest.jsonl) + The recording could not be exported + %1$s · Recording + Download automatically + Download the recitation model and the hint voice when they are needed, without asking (may use mobile data) + Download for offline use + The recitation model and the hint voice for the whole Quran, in one go + Recitation model: %1$s + Recitation model: downloaded ✓ + %1$s: %2$d of 114 suras downloaded, %3$s to go + %1$s: %2$d of 114 suras downloaded + %1$s: all 114 suras downloaded ✓ + A Wi-Fi connection is recommended. The downloads go on in the background. + Pause listening + Resume listening + Stop memorizing + Listen to my recitation + Pause my recitation + Memorize or recite + Double-check before correcting + A larger model listens again before a hint or a mistake mark, so fewer are wrong (%1$s download). + Recommended for this phone. + Recommended for this phone: a check takes about %1$s s here. + Not recommended for this phone: it has %1$s of memory, and the check needs about 300 MB more while you recite. + Not recommended for this phone: its processor is too old for it. + Not recommended for this phone: a check takes about %1$s s here, so hints would come late. + Not downloaded yet. + Downloading… %1$d%% + %1$s\n\nIts model (%2$s) is downloaded once and works offline: %3$s, %4$s. + Delete the double-check model (%1$s) too? It can be downloaded again. + Keep + Also download the double-check (%1$s), recommended for this phone: fewer wrong hints and mistake marks + Double-check model, recommended for this phone: %1$s + Double-check model: downloaded ✓ + + Recitation paused + Stop reciting + Recitation: mark mistakes + When you read with the text shown, a wrong or skipped word is marked on the page + Recitation: say the correct word + When you read with the text shown, the correct word is said in the hint voice after a mistake + + How will you recite? + Starts at %1$s + %1$s, ayah %2$d + Memorization + From memory. The page is hidden, and the words appear as you recite them. + Recitation + Reading. The page stays as it is, and the words are marked as you read. + In prayer (salah) + Hands-free with the screen off. Reminds you if you get stuck. + Recorded for Record and contribute + Recorded, as set in Record my recitation + Record this session + More ways to recite, including salah + + Record and contribute + Keeps every session on this phone with what the speech model heard, to help improve it. Nothing is sent. + Every Memorization, Recitation and salah session will be recorded on this phone, with what the speech model heard and how the app followed you. These recordings can help improve the speech model and the app.\n\nNothing is sent. The recordings stay on this phone until you delete them, and a later version will ask you before sharing anything.\n\nYou can listen to them, export or delete them in Recording sessions. + Turn on + Recording sessions + Listen to your sessions on their pages, export or delete them + More options + Delete all your recording sessions? + Contributed + Record and contribute is on + Today + Yesterday + No recording sessions yet + Turn on Record and contribute, or Record my recitation, in Settings. Then tap the microphone on a page and choose Memorization or Recitation. Each session you record appears here. + Export session + Delete session + Session deleted + Undo + Back to the word + Position in the recording + Back 5 seconds + Forward 5 seconds + Recited + Hints + Skipped + Mistakes + + %1$d session + %1$d sessions + + + Words missed inside a verse + Let a word or two pass (marked as skipped) + Every word must be heard + Choose a session to play it back on its pages. + The session over time: where words were given, skipped or marked. Tap to play from there. + diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/check/CheckGraphTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/check/CheckGraphTest.kt new file mode 100644 index 0000000000..dbbccaf293 --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/check/CheckGraphTest.kt @@ -0,0 +1,62 @@ +package com.quran.mobile.feature.memorize.check + +import com.google.common.truth.Truth.assertThat +import org.junit.Assume.assumeTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.io.IOException +import java.security.MessageDigest + +class CheckGraphTest { + + @get:Rule val folder = TemporaryFolder() + + private fun resource(name: String): File = + File(requireNotNull(javaClass.classLoader?.getResource("check/$name")).toURI()) + + @Test + fun `the conversion is the same as the reference one, byte for byte`() { + // a tiny model with the Tilawi model's inputs; tiny_converted.onnx is what onnx makes of it with + // the same changes (bench/tilawi_rename.py) + val target = folder.newFile("converted.onnx") + + CheckGraph.convert(resource("tiny.onnx"), target) + + assertThat(target.readBytes()).isEqualTo(resource("tiny_converted.onnx").readBytes()) + } + + @Test(expected = IOException::class) + fun `something that isn't a model is refused`() { + val notModel = folder.newFile("tokens.txt").apply { writeText("p0 0\n 1\n") } + CheckGraph.convert(notModel, folder.newFile("out.onnx")) + } + + @Test + fun `the real model converts to the pinned file`() { + // local only: the published model, if it was downloaded to the lab + val source = File(System.getProperty("user.home"), "quran-asr-lab/models/muhdur__tilawi-fastconformer-quran/fastconformer_full_mixed.onnx") + assumeTrue(source.exists()) + val target = folder.newFile("tilawi.onnx") + + CheckGraph.convert(source, target) + + val reference = File(System.getProperty("user.home"), "quran-asr-lab/models/tilawi_sherpa/tilawi_renamed.onnx") + if (reference.exists()) assertThat(sha256(target)).isEqualTo(sha256(reference)) + println("converted sha256 ${sha256(target)} size ${target.length()}") + } + + private fun sha256(file: File): String { + val digest = MessageDigest.getInstance("SHA-256") + file.inputStream().use { input -> + val buffer = ByteArray(1 shl 16) + while (true) { + val n = input.read(buffer) + if (n < 0) break + digest.update(buffer, 0, n) + } + } + return digest.digest().joinToString("") { "%02x".format(it) } + } +} diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/check/CheckTextTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/check/CheckTextTest.kt new file mode 100644 index 0000000000..50a67e4cef --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/check/CheckTextTest.kt @@ -0,0 +1,130 @@ +package com.quran.mobile.feature.memorize.check + +import android.content.Context +import android.util.JsonReader +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.quran.data.model.SuraAyah +import com.quran.mobile.feature.memorize.data.LexiconRepository +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.runTest +import org.junit.Assume.assumeTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +@Config(sdk = [33]) +@RunWith(RobolectricTestRunner::class) +class CheckTextTest { + + private val context: Context = ApplicationProvider.getApplicationContext() + + @Test + fun `words are reduced to the letters the model writes`() { + // hamza seats and alif wasla unified, marks and tatweel dropped, runs collapsed + assertThat(CheckText.wordSkeleton("الحمد")).isEqualTo("الحمد") + assertThat(CheckText.wordSkeleton("ٱلْعَٰلَمِينَ")).isEqualTo("العالمين") + assertThat(CheckText.wordSkeleton("أُو۟لَـٰٓئِكَ")).isEqualTo("اولاءك") + assertThat(CheckText.wordSkeleton("الرحمن")).isEqualTo("الرحمن") + assertThat(CheckText.wordSkeleton("مدد")).isEqualTo("مد") + } + + @Test + fun `a piece starting a word gets a word boundary`() { + assertThat(CheckText.pieceLetters("▁ال")).containsExactly("|", "ا", "ل").inOrder() + assertThat(CheckText.pieceLetters("ة")).containsExactly("ه") + assertThat(CheckText.pieceLetters("َ")).isEmpty() + } + + @Test + fun `a sura's first ayah is compared without the basmala the clean text starts it with`() { + val skeletons = CheckText.ayahSkeletons( + sura = 112, ayah = 1, + lexicon = listOf("قُل", "هُوَ", "للَااهُ", "ءَحَدڇ"), + clean = "بسم الله الرحمن الرحيم قل هو الله احد", + ) + + // runs collapse: الله is written اله + assertThat(skeletons).containsExactly("قل", "هو", "اله", "احد").inOrder() + } + + @Test + fun `words split differently are aligned by their letters`() { + // e.g. "ba'dama" is one word in the clean text and two in the lexicon + assertThat(CheckText.alignWords(listOf("بعد", "ما", "جاءهم"), listOf("بعدما", "جاءهم"))) + .containsExactly("بعد", "ما", "جاءهم").inOrder() + assertThat(CheckText.alignWords(listOf("يبنوم", "قال"), listOf("يبن", "ام", "قال"))) + .containsExactly("يبنام", "قال").inOrder() + } + + @Test + fun `the pieces are the lab's, for every piece of the vocabulary`() { + // local only: the lab's copy of the model's vocab.json and its export (bench/check_export.py) + val vocabulary = lab("models/muhdur__tilawi-fastconformer-quran/vocab.json") + val pieces = lab("cache/check/pieces.tsv") + assumeTrue(vocabulary.exists() && pieces.exists()) + val vocab = HashMap() + JsonReader(vocabulary.reader()).use { reader -> + reader.beginObject() + while (reader.hasNext()) vocab[reader.nextName().toInt()] = reader.nextString() + reader.endObject() + } + + for (line in pieces.readLines()) { + val id = line.substringBefore('\t').toInt() + val expected = line.substringAfter('\t').split(',').filter { it.isNotEmpty() } + assertThat(CheckText.pieceLetters(vocab.getValue(id))).isEqualTo(expected) + } + } + + @Test + fun `every word's skeleton is the lab's`() = runTest { + // local only: quran.json as published with the model, and the lab's table (bench/check_export.py) + val quran = lab("models/muhdur__tilawi-fastconformer-quran/quran.json") + val words = lab("cache/check/words.tsv") + assumeTrue(quran.exists() && words.exists()) + val clean = HashMap() + JsonReader(quran.reader()).use { reader -> + reader.beginArray() + while (reader.hasNext()) { + var sura = 0 + var ayah = 0 + var text = "" + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + "surah" -> sura = reader.nextInt() + "ayah" -> ayah = reader.nextInt() + "text_clean" -> text = reader.nextString() + else -> reader.skipValue() + } + } + reader.endObject() + clean[sura * 1000 + ayah] = text + } + reader.endArray() + } + val expected = words.readLines().associate { line -> + val (sura, ayah, word, skeleton) = line.split('\t') + Triple(sura.toInt(), ayah.toInt(), word.toInt()) to skeleton + } + val lexicon = LexiconRepository.forTest(context, StandardTestDispatcher(testScheduler)) + + var compared = 0 + for (sura in 1..114) { + val passage = lexicon.passage(SuraAyah(sura, 1)) + for ((ayah, ayahWords) in passage.words.groupBy { it.id.ayah }) { + val skeletons = CheckText.ayahSkeletons(sura, ayah, ayahWords.map { it.wasl }, clean.getValue(sura * 1000 + ayah)) + skeletons.forEachIndexed { i, skeleton -> + assertThat(skeleton).isEqualTo(expected[Triple(sura, ayah, i + 1)]) + compared++ + } + } + } + assertThat(compared).isEqualTo(77_433) + } + + private fun lab(path: String) = File(System.getProperty("user.home"), "quran-asr-lab/$path") +} diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckAdviceTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckAdviceTest.kt new file mode 100644 index 0000000000..b121319c41 --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/check/DoubleCheckAdviceTest.kt @@ -0,0 +1,37 @@ +package com.quran.mobile.feature.memorize.check + +import com.google.common.truth.Truth.assertThat +import com.quran.mobile.feature.memorize.check.DoubleCheckAdvice.Reason +import org.junit.Test + +class DoubleCheckAdviceTest { + + private val gb = 1_000_000_000L + + @Test + fun `recommended on phones with the memory for it`() { + // an 8 GB phone reports a little less + val advice = DoubleCheckAdvice.advise(7_400_000_000L, lowRamDevice = false, is64Bit = true, checkMs = 0) + + assertThat(advice.recommended).isTrue() + assertThat(advice.reason).isEqualTo(Reason.SUITS) + } + + @Test + fun `not recommended with less memory, a low-RAM phone or a 32-bit processor`() { + assertThat(DoubleCheckAdvice.advise(3_600_000_000L, false, true, 0).reason).isEqualTo(Reason.LOW_MEMORY) + assertThat(DoubleCheckAdvice.advise(8 * gb, lowRamDevice = true, is64Bit = true, checkMs = 0).reason).isEqualTo(Reason.LOW_MEMORY) + assertThat(DoubleCheckAdvice.advise(8 * gb, lowRamDevice = false, is64Bit = false, checkMs = 0).reason).isEqualTo(Reason.OLD_PROCESSOR) + } + + @Test + fun `once it has run here, how long it took decides`() { + val fast = DoubleCheckAdvice.advise(8 * gb, false, true, checkMs = 600) + assertThat(fast.recommended).isTrue() + assertThat(fast.reason).isEqualTo(Reason.FAST) + + val slow = DoubleCheckAdvice.advise(8 * gb, false, true, checkMs = 2_400) + assertThat(slow.recommended).isFalse() + assertThat(slow.reason).isEqualTo(Reason.SLOW) + } +} diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/check/TilawiDoubleCheckTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/check/TilawiDoubleCheckTest.kt new file mode 100644 index 0000000000..2337970f9b --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/check/TilawiDoubleCheckTest.kt @@ -0,0 +1,57 @@ +package com.quran.mobile.feature.memorize.check + +import com.google.common.truth.Truth.assertThat +import com.quran.mobile.feature.memorize.data.Passage +import com.quran.mobile.feature.memorize.data.PassageWord +import com.quran.mobile.feature.memorize.tracker.WordId +import org.junit.Test + +class TilawiDoubleCheckTest { + + // Al-Ikhlas 1 as the lexicon has it, and its clean text + private val passage = Passage( + listOf("قُل", "هُوَ", "للَااهُ", "ءَحَدڇ").mapIndexed { i, wasl -> PassageWord(WordId(112, 1, i + 1), wasl, wasl) }, + ) + private val clean = mapOf(112 * 1000 + 1 to "بسم الله الرحمن الرحيم قل هو الله احد") + + // a vocabulary of single letters (id = index) and a word start + private val alphabet = listOf("▁") + "قلهواحدسمع".map { it.toString() } + + /** A recognizer that "hears" [text]: one piece per letter, a word start before each word. */ + private fun hearing(text: String) = object : PieceRecognizer { + override fun pieces(audio: FloatArray): IntArray = text.split(' ').flatMap { word -> + listOf(0) + word.map { alphabet.indexOf(it.toString()) } + }.toIntArray() + } + + private fun check(heard: String) = + TilawiDoubleCheck(hearing(heard), alphabet.map { CheckText.pieceLetters(it) }) { sura, ayah -> clean[sura * 1000 + ayah] } + + private val audio = FloatArray(32_000) + + @Test + fun `a word heard right after the one before it was said`() { + assertThat(check("قل هو اله").said(audio, passage, 2)).isTrue() + // with a letter off (within a quarter of the word) + assertThat(check("قل هو احد").said(audio, passage, 3)).isFalse() + assertThat(check("هو اله احد").said(audio, passage, 3)).isTrue() + } + + @Test + fun `a word heard on its own isn't enough`() { + // short words match too much: the word before must be there too + assertThat(check("اله").said(audio, passage, 2)).isFalse() + assertThat(check("سمع اله").said(audio, passage, 2)).isFalse() + } + + @Test + fun `the first word needs the one after it`() { + assertThat(check("قل هو").said(audio, passage, 0)).isTrue() + assertThat(check("قل سمع").said(audio, passage, 0)).isFalse() + } + + @Test + fun `too little audio is never a yes`() { + assertThat(check("قل هو اله").said(FloatArray(8_000), passage, 2)).isFalse() + } +} diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/glyph/GlyphTypesTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/glyph/GlyphTypesTest.kt new file mode 100644 index 0000000000..7dcb48f401 --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/glyph/GlyphTypesTest.kt @@ -0,0 +1,55 @@ +package com.quran.mobile.feature.memorize.glyph + +import com.google.common.truth.Truth.assertThat +import com.quran.page.common.data.coordinates.GlyphSize +import org.junit.Test + +class GlyphTypesTest { + + // sizes: words are 40-130 wide and 50 high; waqf marks float above the line and are short + private val word = GlyphSize(120, 50) + private val shortWord = GlyphSize(40, 50) + private val waqf = GlyphSize(30, 20) + private val wideWaqf = GlyphSize(140, 22) // e.g. the ج in 38:26 + private val hizb = GlyphSize(60, 60) + private val sajdah = GlyphSize(50, 45) + private val end = GlyphSize(150, 60) // the ayah number can be wider than the words + + @Test + fun `the madani layout gives back the text's own sequence`() { + val glyphs = listOf(hizb, word, shortWord, waqf, word, end) + + assertThat(GlyphTypes.derive("hwwpwe", glyphs)).isEqualTo("hwwpwe") + } + + @Test + fun `a font that places its waqf marks elsewhere gets them where its glyphs are`() { + // the text has one waqf mark after the second word; this font has two, after words 1 and 3 + val glyphs = listOf(word, wideWaqf, shortWord, word, waqf, word, end) + + assertThat(GlyphTypes.derive("wwpwwe", glyphs)).isEqualTo("wpwwpwe") + } + + @Test + fun `a font without waqf marks has only words`() { + assertThat(GlyphTypes.derive("wwpwwe", listOf(word, shortWord, word, word, end))).isEqualTo("wwwwe") + } + + @Test + fun `the sajdah marker stays just before the end`() { + val glyphs = listOf(word, waqf, word, sajdah, end) + + assertThat(GlyphTypes.derive("wpwse", glyphs)).isEqualTo("wpwse") + } + + @Test + fun `a hizb marker drawn in the margin isn't taken for a word`() { + assertThat(GlyphTypes.derive("hwwe", listOf(word, word, end))).isEqualTo("wwe") + } + + @Test + fun `a font that joins words into one glyph can't be told apart`() { + assertThat(GlyphTypes.derive("wwwe", listOf(word, word, end))).isNull() + assertThat(GlyphTypes.derive("wwwe", emptyList())).isNull() + } +} diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/model/SpeechModelStoreDownloadTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/model/SpeechModelStoreDownloadTest.kt new file mode 100644 index 0000000000..d63f2635cb --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/model/SpeechModelStoreDownloadTest.kt @@ -0,0 +1,117 @@ +package com.quran.mobile.feature.memorize.model + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.sun.net.httpserver.HttpServer +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.net.InetSocketAddress +import java.security.MessageDigest +import java.util.UUID +import java.util.concurrent.atomic.AtomicInteger + +/** Downloads from a local server that can cut the connection, as mobile networks do. */ +@Config(sdk = [33]) +@RunWith(RobolectricTestRunner::class) +class SpeechModelStoreDownloadTest { + + private val context: Context = ApplicationProvider.getApplicationContext() + private val modelBytes = ByteArray(200_000) { (it % 251).toByte() } + private val tokensBytes = "a 0\nb 1\n".toByteArray() + private val modelRequests = AtomicInteger() + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0) + + /** How the model is served on its n-th request (1-based). */ + private var serve: (Int) -> Served = { Served.WHOLE } + + private enum class Served { WHOLE, CUT_SHORT, WRONG, MISSING } + + init { + server.createContext("/model.onnx") { exchange -> + when (serve(modelRequests.incrementAndGet())) { + Served.WHOLE -> exchange.sendResponseHeaders(200, modelBytes.size.toLong()).also { exchange.responseBody.write(modelBytes) } + Served.CUT_SHORT -> { + // the length is announced, then the connection drops halfway + exchange.sendResponseHeaders(200, modelBytes.size.toLong()) + exchange.responseBody.write(modelBytes, 0, modelBytes.size / 2) + exchange.responseBody.flush() + } + Served.WRONG -> exchange.sendResponseHeaders(200, modelBytes.size.toLong()).also { exchange.responseBody.write(ByteArray(modelBytes.size)) } + Served.MISSING -> exchange.sendResponseHeaders(404, -1) + } + exchange.close() + } + server.createContext("/tokens.txt") { exchange -> + exchange.sendResponseHeaders(200, tokensBytes.size.toLong()) + exchange.responseBody.write(tokensBytes) + exchange.close() + } + server.start() + } + + private val base = "http://127.0.0.1:${server.address.port}" + private val spec = SpeechModelSpec( + id = "test-${UUID.randomUUID()}", + model = ModelFile("model.onnx", "$base/model.onnx", sha(modelBytes), modelBytes.size.toLong()), + tokens = ModelFile("tokens.txt", "$base/tokens.txt", sha(tokensBytes), tokensBytes.size.toLong()), + license = "test", + attribution = "test", + ) + private val store = SpeechModelStore.forTest(context, spec, retryDelayMs = 10) + + @After + fun stop() { + server.stop(0) + } + + @Test + fun `a download cut off halfway is tried again`() { + serve = { if (it == 1) Served.CUT_SHORT else Served.WHOLE } + + assertThat(download()).isEqualTo(SpeechModelStore.State.Installed) + assertThat(modelRequests.get()).isEqualTo(2) + assertThat(store.isInstalled()).isTrue() + } + + @Test + fun `a connection that keeps dropping fails after three tries`() { + serve = { Served.CUT_SHORT } + + assertThat(download()).isInstanceOf(SpeechModelStore.State.Failed::class.java) + assertThat(modelRequests.get()).isEqualTo(3) + assertThat(store.isInstalled()).isFalse() + } + + @Test + fun `a file that isn't the one pinned is not downloaded again`() { + serve = { Served.WRONG } + + assertThat(download()).isEqualTo(SpeechModelStore.State.Failed("model.onnx failed verification")) + assertThat(modelRequests.get()).isEqualTo(1) + } + + @Test + fun `a missing file is not downloaded again`() { + serve = { Served.MISSING } + + assertThat(download()).isEqualTo(SpeechModelStore.State.Failed("HTTP 404 for model.onnx")) + assertThat(modelRequests.get()).isEqualTo(1) + } + + private fun download(): SpeechModelStore.State = runBlocking { + store.startDownload() + withTimeout(20_000) { + store.state.first { it is SpeechModelStore.State.Installed || it is SpeechModelStore.State.Failed } + } + } + + private fun sha(bytes: ByteArray): String = + MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } +} diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/model/SpeechModelStoreImportTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/model/SpeechModelStoreImportTest.kt new file mode 100644 index 0000000000..2c10618d2d --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/model/SpeechModelStoreImportTest.kt @@ -0,0 +1,106 @@ +package com.quran.mobile.feature.memorize.model + +import android.content.Context +import android.net.Uri +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File +import java.security.MessageDigest +import java.util.UUID +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream + +@Config(sdk = [33]) +@RunWith(RobolectricTestRunner::class) +class SpeechModelStoreImportTest { + + private val context: Context = ApplicationProvider.getApplicationContext() + private val modelBytes = ByteArray(5_000) { (it % 251).toByte() } + private val tokensBytes = "a 0\nb 1\n".toByteArray() + private val spec = SpeechModelSpec( + id = "test-${UUID.randomUUID()}", + model = ModelFile("model.onnx", "https://example.invalid/model.onnx", sha(modelBytes), modelBytes.size.toLong()), + tokens = ModelFile("tokens.txt", "https://example.invalid/tokens.txt", sha(tokensBytes), tokensBytes.size.toLong()), + license = "test", + attribution = "test", + ) + private val store = SpeechModelStore.forTest(context, spec) + + @Test + fun `each file can be imported on its own, under any name`() = runTest { + assertThat(store.importFile(file("renamed.bin", modelBytes))).containsExactly(spec.model) + assertThat(store.missingFiles()).containsExactly(spec.tokens) + assertThat(store.isInstalled()).isFalse() + + assertThat(store.importFile(file("tokens (1).txt", tokensBytes))).containsExactly(spec.tokens) + assertThat(store.isInstalled()).isTrue() + assertThat(store.state.value).isEqualTo(SpeechModelStore.State.Installed) + } + + @Test + fun `both files can be imported from the zip they came in`() = runTest { + val zip = File(context.cacheDir, "model-${UUID.randomUUID()}.zip") + ZipOutputStream(zip.outputStream()).use { out -> + for ((name, bytes) in listOf("folder/" to null, "folder/model.onnx" to modelBytes, "folder/tokens.txt" to tokensBytes, "README.txt" to "hi".toByteArray())) { + out.putNextEntry(ZipEntry(name)) + bytes?.let { out.write(it) } + out.closeEntry() + } + } + + assertThat(store.importFile(Uri.fromFile(zip))).containsExactly(spec.model, spec.tokens) + assertThat(store.isInstalled()).isTrue() + } + + @Test + fun `a file that isn't part of the model is ignored`() = runTest { + assertThat(store.importFile(file("photo.jpg", ByteArray(5_000) { 7 }))).isEmpty() + assertThat(store.importFile(file("big.bin", ByteArray(10_000)))).isEmpty() + assertThat(store.missingFiles()).containsExactly(spec.model, spec.tokens) + } + + @Test + fun `a file as published is converted on import and checked`() = runTest { + // e.g. the double-check's model: published as one file, used as another + val published = "published model".toByteArray() + val converted = "PUBLISHED MODEL".toByteArray() + val upper = ModelConverter { source, target -> target.writeText(source.readText().uppercase()) } + val convertedSpec = spec.copy( + id = "test-${UUID.randomUUID()}", + model = ModelFile( + "model.onnx", "https://example.invalid/published.onnx", sha(converted), converted.size.toLong(), + source = ModelFile.Source(sha(published), published.size.toLong(), upper), + ), + ) + val store = SpeechModelStore.forTest(context, convertedSpec) + + assertThat(store.importFile(file("published.onnx", published))).containsExactly(convertedSpec.model) + assertThat(store.missingFiles()).containsExactly(convertedSpec.tokens) + assertThat(store.modelFile.readBytes()).isEqualTo(converted) + assertThat(convertedSpec.downloadSize).isEqualTo(published.size.toLong() + tokensBytes.size) + + // a conversion that doesn't give the expected file installs nothing + val broken = SpeechModelStore.forTest( + context, + convertedSpec.copy( + id = "test-${UUID.randomUUID()}", + model = convertedSpec.model.copy(source = convertedSpec.model.source!!.copy(converter = { _, target -> target.writeText("?") })), + ), + ) + assertThat(broken.importFile(file("published.onnx", published))).isEmpty() + assertThat(broken.modelFile.exists()).isFalse() + } + + private fun file(name: String, bytes: ByteArray): Uri { + val file = File(context.cacheDir, "${UUID.randomUUID()}-$name") + file.writeBytes(bytes) + return Uri.fromFile(file) + } + + private fun sha(bytes: ByteArray) = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } +} diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeMasksTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeMasksTest.kt new file mode 100644 index 0000000000..1c13a9ded8 --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/presenter/MemorizeMasksTest.kt @@ -0,0 +1,191 @@ +package com.quran.mobile.feature.memorize.presenter + +import com.google.common.truth.Truth.assertThat +import com.quran.data.model.VerseRange +import com.quran.mobile.feature.memorize.data.Passage +import com.quran.mobile.feature.memorize.data.PassageWord +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.mobile.feature.memorize.tracker.WordId +import org.junit.Test + +class MemorizeMasksTest { + + // Al-Ikhlas: 4, 2, 4 and 5 words; the passage starts at 112:1 + private val passage = Passage( + listOf(4, 2, 4, 5).flatMapIndexed { ayahIndex, count -> + (1..count).map { word -> PassageWord(WordId(112, ayahIndex + 1, word), "", "") } + } + ) + private val page = VerseRange(109, 1, 114, 6, 0) + + private fun state( + cursor: Int = 0, + mistake: Int? = null, + hinted: Set = emptySet(), + missed: Set = emptySet(), + peeking: Boolean = false, + started: Boolean = true, + mode: MemorizeState.Mode = MemorizeState.Mode.MEMORIZE, + firstWord: Int = 0, + showMistakes: Boolean = true, + ) = MemorizeState( + id = "test", passage = passage, startedAt = 0, status = MemorizeState.Status.LISTENING, mode = mode, + cursor = cursor, mistake = mistake, hinted = hinted, missed = missed, peeking = peeking, started = started, + firstWord = firstWord, showMistakes = showMistakes, + ) + + private fun reading( + cursor: Int, + mistake: Int? = null, + hinted: Set = emptySet(), + missed: Set = emptySet(), + started: Boolean = true, + firstWord: Int = 0, + showMistakes: Boolean = true, + ) = state(cursor, mistake, hinted, missed, false, started, MemorizeState.Mode.RECITE, firstWord, showMistakes) + + @Test + fun `reading hides nothing and leaves a trail on the words read`() { + val marks = MemorizeMasks.marks(reading(cursor = 5), listOf(page)) + + assertThat(marks).containsExactly( + Mark(112, 1, 1, MemorizeHighlightTypes.RECITED), + Mark(112, 1, 2, MemorizeHighlightTypes.RECITED), + Mark(112, 1, 3, MemorizeHighlightTypes.RECITED), + Mark(112, 1, 4, MemorizeHighlightTypes.RECITED), + Mark(112, 2, 1, MemorizeHighlightTypes.RECITED), + ) + } + + @Test + fun `the trail starts where the reader did, once that is known`() { + assertThat(MemorizeMasks.marks(reading(cursor = 6, started = false), listOf(page))).isEmpty() + + val marks = MemorizeMasks.marks(reading(cursor = 6, firstWord = 4), listOf(page)) + assertThat(marks).containsExactly( + Mark(112, 2, 1, MemorizeHighlightTypes.RECITED), + Mark(112, 2, 2, MemorizeHighlightTypes.RECITED), + ) + } + + @Test + fun `reading marks hints, skipped words and the mistake on the visible word`() { + val marks = MemorizeMasks.marks(reading(cursor = 3, mistake = 3, hinted = setOf(1), missed = setOf(2)), listOf(page)) + + assertThat(marks).containsExactly( + Mark(112, 1, 1, MemorizeHighlightTypes.RECITED), + Mark(112, 1, 2, MemorizeHighlightTypes.HINTED), + Mark(112, 1, 3, MemorizeHighlightTypes.MISSED), + Mark(112, 1, 4, MemorizeHighlightTypes.MISTAKE), + ) + } + + @Test + fun `without marking mistakes, reading only shows the trail and the hints`() { + val marks = MemorizeMasks.marks( + reading(cursor = 3, mistake = 3, hinted = setOf(1), missed = setOf(2), showMistakes = false), + listOf(page), + ) + + assertThat(marks).containsExactly( + Mark(112, 1, 1, MemorizeHighlightTypes.RECITED), + Mark(112, 1, 2, MemorizeHighlightTypes.HINTED), + Mark(112, 1, 3, MemorizeHighlightTypes.RECITED), + ) + } + + @Test + fun `untouched ayat are hidden as a whole`() { + val marks = MemorizeMasks.marks(state(), listOf(page)) + + assertThat(marks).containsExactly( + Mark(112, 1, -1, MemorizeHighlightTypes.HIDDEN), + Mark(112, 2, -1, MemorizeHighlightTypes.HIDDEN), + Mark(112, 3, -1, MemorizeHighlightTypes.HIDDEN), + Mark(112, 4, -1, MemorizeHighlightTypes.HIDDEN), + ) + } + + @Test + fun `the ayah being recited is hidden word by word`() { + val marks = MemorizeMasks.marks(state(cursor = 2), listOf(page)) + + assertThat(marks).containsAtLeast( + Mark(112, 1, 3, MemorizeHighlightTypes.HIDDEN), + Mark(112, 1, 4, MemorizeHighlightTypes.HIDDEN), + Mark(112, 2, -1, MemorizeHighlightTypes.HIDDEN), + ) + assertThat(marks.filter { it.ayah == 1 && it.word in 1..2 }).isEmpty() + } + + @Test + fun `a mistake is marked on a word that stays hidden`() { + val marks = MemorizeMasks.marks(state(cursor = 1, mistake = 1), listOf(page)) + + assertThat(marks).containsAtLeast( + Mark(112, 1, 2, MemorizeHighlightTypes.HIDDEN), + Mark(112, 1, 2, MemorizeHighlightTypes.MISTAKE), + ) + } + + @Test + fun `hinted and skipped words are styled once revealed`() { + val marks = MemorizeMasks.marks(state(cursor = 4, hinted = setOf(1), missed = setOf(2)), listOf(page)) + + assertThat(marks).containsAtLeast( + Mark(112, 1, 2, MemorizeHighlightTypes.HINTED), + Mark(112, 1, 3, MemorizeHighlightTypes.MISSED), + ) + assertThat(marks.none { it.ayah == 1 && it.type == MemorizeHighlightTypes.HIDDEN }).isTrue() + } + + @Test + fun `peeking shows everything`() { + assertThat(MemorizeMasks.marks(state(peeking = true), listOf(page))).isEmpty() + } + + @Test + fun `only ayat on the page are masked`() { + val otherPage = VerseRange(112, 3, 112, 4, 0) + + val marks = MemorizeMasks.marks(state(), listOf(otherPage)) + + assertThat(marks.map { it.ayah }.toSet()).containsExactly(3, 4) + } + + @Test + fun `an ayah continuing onto the next page is masked on both pages`() { + val firstPage = VerseRange(112, 1, 112, 2, 0) + val secondPage = VerseRange(112, 2, 112, 4, 0) + + val first = MemorizeMasks.marks(state(), listOf(firstPage)) + val second = MemorizeMasks.marks(state(), listOf(secondPage)) + + assertThat(first).contains(Mark(112, 2, -1, MemorizeHighlightTypes.HIDDEN)) + assertThat(second).contains(Mark(112, 2, -1, MemorizeHighlightTypes.HIDDEN)) + } + + @Test + fun `everything is hidden until the user starts, and starting elsewhere marks the first word`() { + val hidden = (1..4).map { Mark(112, it, -1, MemorizeHighlightTypes.HIDDEN) } + assertThat(MemorizeMasks.marks(state(cursor = 4, started = false), listOf(page))).containsExactlyElementsIn(hidden) + + assertThat(MemorizeMasks.marks(state(cursor = 4, started = false, mistake = 0), listOf(page))) + .containsExactlyElementsIn(hidden + Mark(112, 1, 1, MemorizeHighlightTypes.MISTAKE)) + } + + @Test + fun `a page far into a long passage is found`() { + val long = Passage( + (1..114).flatMap { sura -> (1..3).flatMap { ayah -> (1..4).map { word -> PassageWord(WordId(sura, ayah, word), "", "") } } } + ) + val state = MemorizeState(id = "test", passage = long, startedAt = 0, status = MemorizeState.Status.LISTENING, cursor = 0) + + val marks = MemorizeMasks.marks(state, listOf(VerseRange(110, 2, 110, 3, 0))) + + assertThat(marks).containsExactly( + Mark(110, 2, -1, MemorizeHighlightTypes.HIDDEN), + Mark(110, 3, -1, MemorizeHighlightTypes.HIDDEN), + ) + } +} diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/prompt/WordTimingsTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/prompt/WordTimingsTest.kt new file mode 100644 index 0000000000..8f28fc44cb --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/prompt/WordTimingsTest.kt @@ -0,0 +1,72 @@ +package com.quran.mobile.feature.memorize.prompt + +import android.content.Context +import android.database.sqlite.SQLiteDatabase +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.quran.mobile.feature.memorize.tracker.WordId +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +@Config(sdk = [33]) +@RunWith(RobolectricTestRunner::class) +class WordTimingsTest { + + private val context: Context = ApplicationProvider.getApplicationContext() + private lateinit var timings: WordTimings + + @Before + fun setUp() { + val file = File(context.noBackupFilesDir, "memorize/test_timings.db").apply { + parentFile?.mkdirs() + delete() + } + SQLiteDatabase.openOrCreateDatabase(file, null).use { db -> + db.execSQL("CREATE TABLE timings(sura INTEGER, ayah INTEGER, time INTEGER, words TEXT)") + db.execSQL("CREATE TABLE audio_files(sura INTEGER PRIMARY KEY, size INTEGER, md5 TEXT)") + db.execSQL("INSERT INTO timings VALUES (112, 1, 5000, '1:5100:5600,2:5600:6000,3:6000:6900,4:6900:7800')") + db.execSQL("INSERT INTO timings VALUES (112, 2, 9000, '1:9100:9900,2:9900:11000')") + db.execSQL("INSERT INTO audio_files VALUES (112, 123456, '')") + } + timings = WordTimings.fromFile(file) + } + + @After + fun tearDown() { + timings.close() + } + + @Test + fun `a single word plays from its start to its end`() { + assertThat(timings.span(listOf(WordId(112, 1, 3)))).isEqualTo(WordTimings.Span(6000, 6900)) + } + + @Test + fun `consecutive words play as one clip, also across ayat`() { + val span = timings.span(listOf(WordId(112, 1, 4), WordId(112, 2, 1))) + + assertThat(span).isEqualTo(WordTimings.Span(6900, 9900)) + } + + @Test + fun `unknown words have no span`() { + assertThat(timings.span(listOf(WordId(112, 3, 1)))).isNull() + assertThat(timings.span(listOf(WordId(112, 1, 9)))).isNull() + } + + @Test + fun `words from different suras can't be played as one clip`() { + assertThat(timings.span(listOf(WordId(112, 2, 2), WordId(113, 1, 1)))).isNull() + } + + @Test + fun `knows the size of the file the timings were made for`() { + assertThat(timings.expectedFileSize(112)).isEqualTo(123456) + assertThat(timings.expectedFileSize(113)).isNull() + } +} diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/recording/RecordingStoreTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/recording/RecordingStoreTest.kt new file mode 100644 index 0000000000..0a40bdb4b3 --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/recording/RecordingStoreTest.kt @@ -0,0 +1,399 @@ +package com.quran.mobile.feature.memorize.recording + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.quran.data.model.SuraAyah +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.mobile.feature.memorize.settings.MemorizePreferences +import com.quran.mobile.feature.memorize.tracker.WordId +import com.quran.mobile.feature.memorize.tracker.engine.RecognizedToken +import kotlinx.coroutines.test.runTest +import org.json.JSONObject +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.ByteArrayOutputStream +import java.io.File +import java.util.zip.ZipInputStream + +/** + * Recordings with a fake encoder (raw samples to a file) and an executor that runs right away, so + * every step is done when the call returns. + */ +@Config(sdk = [33]) +@RunWith(RobolectricTestRunner::class) +class RecordingStoreTest { + + private val context: Context = ApplicationProvider.getApplicationContext() + private lateinit var preferences: MemorizePreferences + private lateinit var store: RecordingStore + private var now = 1_000_000L + + @Before + fun setUp() { + preferences = MemorizePreferences(context) + store = RecordingStore.forTest(context, preferences, ::RawWriter, { Executor { it.run() } }, { now }) + store.deleteAll() + } + + @Test + fun `a session over two suras gives a recording per sura`() = runTest { + val session = store.start(SuraAyah(112, 1), MemorizeState.Mode.MEMORIZE, contribute = false, info = emptyMap()) + // Al-Ikhlas from its start, its end reported a moment after it was said; then the basmala and + // Al-Falaq + audio(session, 3_000) + session.word(WordId(112, 1, 1), 100, 400, Recording.WordStatus.RECITED, "qul", endsSura = false) + session.word(WordId(112, 4, 5), 2_000, 2_400, Recording.WordStatus.RECITED, "ahad", endsSura = true) + audio(session, 4_000) + session.word(WordId(113, 1, 1), 6_200, 6_500, Recording.WordStatus.RECITED, "qul", endsSura = false) + audio(session, 1_000) + // what follows the last sura heard (e.g. a takbir) isn't a recording of its own + session.word(WordId(113, 5, 5), 7_200, 7_500, Recording.WordStatus.RECITED, "hasad", endsSura = true) + audio(session, 1_000) + session.finish() + + val recordings = store.list().sortedBy { it.start.sura } + assertThat(recordings.map { it.start to it.end }) + .containsExactly(SuraAyah(112, 1) to SuraAyah(112, 4), SuraAyah(113, 1) to SuraAyah(113, 5)).inOrder() + // Al-Ikhlas ends half a second after its last word; Al-Falaq's word times count from there + assertThat(recordings[0].durationMs).isEqualTo(2_900) + assertThat(recordings[1].words.first().startMs).isEqualTo(3_300) + assertThat(recordings[1].durationMs).isEqualTo(5_100) + assertThat(recordings.map { it.session }.toSet()).containsExactly(session.session) + } + + @Test + fun `a session can be one recording`() = runTest { + preferences.recordingSplit = RecordingSplit.BY_SESSION + val session = store.start(SuraAyah(112, 1), MemorizeState.Mode.MEMORIZE, contribute = false, info = emptyMap()) + audio(session, 3_000) + session.word(WordId(112, 1, 1), 100, 400, Recording.WordStatus.RECITED, "qul", endsSura = false) + session.word(WordId(112, 4, 5), 2_000, 2_400, Recording.WordStatus.RECITED, "ahad", endsSura = true) + session.word(WordId(113, 1, 1), 2_600, 2_900, Recording.WordStatus.RECITED, "qul", endsSura = false) + session.finish() + + val recording = store.list().single() + assertThat(recording.start to recording.end).isEqualTo(SuraAyah(112, 1) to SuraAyah(113, 1)) + assertThat(recording.durationMs).isEqualTo(3_000) + } + + @Test + fun `what was recorded before a pause can be played while the session goes on`() = runTest { + val session = store.start(SuraAyah(67, 1), MemorizeState.Mode.SALAH, contribute = false, info = emptyMap()) + audio(session, 2_000) + session.word(WordId(67, 1, 1), 500, 900, Recording.WordStatus.RECITED, "tabaraka", endsSura = false) + session.pause() + + val played = store.session(session.session)!! + assertThat(played.durationMs).isEqualTo(2_000) + assertThat(played.ayahAt(1_000)).isEqualTo(SuraAyah(67, 1)) + + audio(session, 1_000) + session.pause() + assertThat(store.session(session.session)!!.parts).hasSize(2) + } + + @Test + fun `a new recording can replace the older one of the same place`() = runTest { + preferences.keepRecordings = MemorizePreferences.KeepRecordings.REPLACE_SAME_PLACE + repeat(2) { + now += 60_000 + val session = store.start(SuraAyah(67, 1), MemorizeState.Mode.MEMORIZE, contribute = false, info = emptyMap()) + audio(session, 1_000) + session.word(WordId(67, 1, 1), 100, 500, Recording.WordStatus.RECITED, "tabaraka", endsSura = false) + session.finish() + } + val other = store.start(SuraAyah(68, 1), MemorizeState.Mode.MEMORIZE, contribute = false, info = emptyMap()) + audio(other, 1_000) + other.word(WordId(68, 1, 1), 100, 500, Recording.WordStatus.RECITED, "nun", endsSura = false) + other.finish() + + assertThat(store.list().map { it.start }).containsExactly(SuraAyah(68, 1), SuraAyah(67, 1)) + assertThat(store.list().first { it.start.sura == 67 }.startedAt).isEqualTo(1_120_000) + } + + @Test + fun `recordings are kept until deleted by default`() = runTest { + repeat(2) { + val session = store.start(SuraAyah(67, 1), MemorizeState.Mode.MEMORIZE, contribute = false, info = emptyMap()) + audio(session, 1_000) + session.word(WordId(67, 1, 1), 100, 500, Recording.WordStatus.RECITED, "tabaraka", endsSura = false) + session.finish() + } + assertThat(store.list()).hasSize(2) + + store.delete(store.list().first().id) + assertThat(store.list()).hasSize(1) + } + + @Test + fun `the export has the audio, its alignment and a training manifest of whole ayat`() = runTest { + val session = store.start(SuraAyah(112, 1), MemorizeState.Mode.MEMORIZE, contribute = false, info = emptyMap()) + audio(session, 4_000) + // ayah 1 recited entirely; ayah 2 with a hinted word + session.word(WordId(112, 1, 1), 300, 600, Recording.WordStatus.RECITED, "qul", endsSura = false) + session.word(WordId(112, 1, 2), 650, 900, Recording.WordStatus.RECITED, "huwa", endsSura = false) + session.word(WordId(112, 2, 1), 1_500, null, Recording.WordStatus.HINTED, "allahu", endsSura = false) + session.finish() + val recording = store.list().single() + + val entries = unzip(recording) + + val alignment = JSONObject(String(entries.getValue(entries.keys.single { it.endsWith("alignment.json") }))) + assertThat(alignment.getString("format")).isEqualTo("quran-memorize-alignment") + assertThat(alignment.getJSONArray("words").length()).isEqualTo(3) + assertThat(alignment.getJSONArray("words").getJSONObject(2).getString("status")).isEqualTo("hinted") + val manifest = String(entries.getValue("manifest.jsonl")).lines().filter { it.isNotBlank() }.map(::JSONObject) + assertThat(manifest).hasSize(1) + assertThat(manifest[0].getString("text")).isEqualTo("qul huwa") + assertThat(manifest[0].getDouble("offset")).isWithin(0.001).of(0.1) + assertThat(manifest[0].getDouble("duration")).isWithin(0.001).of(1.1) + assertThat(entries.keys).contains(manifest[0].getString("audio_filepath")) + assertThat(entries.keys).contains("README.txt") + } + + @Test + fun `a recording starts where the user started, not where the session looked from`() = runTest { + // the session may start anywhere from a few pages before the one on screen + val session = store.start(SuraAyah(65, 6), MemorizeState.Mode.MEMORIZE, contribute = false, info = emptyMap()) + audio(session, 2_000) + session.word(WordId(67, 1, 1), 500, 900, Recording.WordStatus.RECITED, "tabaraka", endsSura = false) + session.word(WordId(67, 1, 2), 950, 1_200, Recording.WordStatus.RECITED, "lladhi", endsSura = false) + session.finish() + + val recording = store.list().single() + assertThat(recording.start to recording.end).isEqualTo(SuraAyah(67, 1) to SuraAyah(67, 1)) + assertThat(recording.words).hasSize(2) + } + + @Test + fun `a recording keeps how many times a mistake was marked on each word`() = runTest { + val session = store.start(SuraAyah(112, 1), MemorizeState.Mode.MEMORIZE, contribute = false, info = emptyMap()) + audio(session, 2_000) + session.word(WordId(112, 1, 1), 100, 400, Recording.WordStatus.RECITED, "qul", endsSura = false, mistakes = 2) + session.word(WordId(112, 1, 2), 500, 800, Recording.WordStatus.HINTED, "huwa", endsSura = false) + session.finish() + + val recording = store.list().single() + assertThat(recording.words.map { it.mistakes }).containsExactly(2, 0).inOrder() + assertThat(recording.contribute).isFalse() + assertThat(recording.details).isNull() + val sessions = store.sessions() + assertThat(sessions.single().mistakes).isEqualTo(1) + assertThat(sessions.single().hinted).isEqualTo(1) + } + + @Test + fun `recordings made before mistakes were kept still read`() = runTest { + val directory = File(context.noBackupFilesDir, "memorize/recordings").apply { mkdirs() } + File(directory, "old_1.m4a").writeBytes(ByteArray(10)) + File(directory, "old.json").writeText( + """{"format": "quran-memorize-alignment", "version": 1, "id": "old", "session": "s", "mode": "salah", + | "recorded_at_ms": 5, "sample_rate": 16000, "start": "67:1", "end": "67:2", + | "audio": [{"file": "old_1.m4a", "duration_ms": 1000}], + | "words": [{"sura": 67, "ayah": 1, "word": 1, "start_ms": 10, "end_ms": 20, "status": "recited", "phonemes": "x"}]} + """.trimMargin() + ) + + val recording = store.list().single() + assertThat(recording.mode).isEqualTo(MemorizeState.Mode.SALAH) + assertThat(recording.words.single().mistakes).isNull() + assertThat(recording.contribute).isFalse() + } + + @Test + fun `a contributed recording keeps what was heard, in the sura's recording it is about`() = runTest { + val session = store.start(SuraAyah(112, 1), MemorizeState.Mode.MEMORIZE, contribute = true, info = mapOf("model" to "m")) + assertThat(session.keepsDetails).isTrue() + audio(session, 3_000) + session.heard(listOf(RecognizedToken("qu", 150, 0.9f), RecognizedToken("l", 350, null))) + session.word(WordId(112, 1, 1), 100, 400, Recording.WordStatus.RECITED, "qul", endsSura = false) + session.event(SessionEvent(2_100, SessionEvent.Kind.MISTAKE, WordId(112, 4, 5), "substitution")) + session.word(WordId(112, 4, 5), 2_000, 2_400, Recording.WordStatus.RECITED, "ahad", endsSura = true) + // reported a moment later: the next sura's basmala, said after Al-Ikhlas's recording ended + audio(session, 1_000) + session.heard(listOf(RecognizedToken("bis", 3_400, 0.8f))) + audio(session, 3_000) + session.word(WordId(113, 1, 1), 6_200, 6_500, Recording.WordStatus.RECITED, "qul", endsSura = false) + audio(session, 1_000) + session.finish() + + val recordings = store.list().sortedBy { it.start.sura } + assertThat(recordings.map { it.contribute }).containsExactly(true, true) + val (header, first) = RecordingDetails.read(recordings[0].details!!) + assertThat(header.getString("model")).isEqualTo("m") + assertThat(header.getString("recording")).isEqualTo(recordings[0].id) + assertThat(header.getString("session")).isEqualTo(session.session) + assertThat(header.has("app_version")).isTrue() + assertThat(first.map { it.toString() }).containsExactly( + """["t",150,"qu",0.8999999761581421]""", + """["t",350,"l",null]""", + """["e",2100,"mistake","112:4:5","substitution"]""", + ).inOrder() + // Al-Falaq's recording starts at 2.9 s + val (_, second) = RecordingDetails.read(recordings[1].details!!) + assertThat(second.map { it.toString() }).containsExactly("""["t",500,"bis",0.800000011920929]""") + } + + @Test + fun `details after a pause stay with the recording, at its own times`() = runTest { + val session = store.start(SuraAyah(67, 1), MemorizeState.Mode.MEMORIZE, contribute = true, info = emptyMap()) + audio(session, 1_000) + session.word(WordId(67, 1, 1), 100, 500, Recording.WordStatus.RECITED, "tabaraka", endsSura = false) + session.pause() + audio(session, 1_000) + session.heard(listOf(RecognizedToken("x", 1_500, null))) + session.finish() + + val recording = store.list().single() + assertThat(recording.parts).hasSize(2) + val (_, lines) = RecordingDetails.read(recording.details!!) + assertThat(lines.map { it.toString() }).containsExactly("""["e",1000,"paused",null,null]""", """["t",1500,"x",null]""").inOrder() + } + + @Test + fun `word times stay right when a busy phone dropped some audio`() = runTest { + val executor = QueueExecutor() + store = RecordingStore.forTest(context, preferences, ::RawWriter, { executor }, { now }) + val session = store.start(SuraAyah(67, 1), MemorizeState.Mode.MEMORIZE, contribute = false, info = emptyMap()) + // 31 s of audio while the recorder is stuck: the last second of it is dropped + audio(session, 31_000) + // said in the second that was dropped, and after it + session.word(WordId(67, 1, 1), 30_500, 30_800, Recording.WordStatus.RECITED, "tabaraka", endsSura = false) + // the recorder catches up + executor.runAll() + audio(session, 1_000) + session.word(WordId(67, 1, 2), 31_200, 31_600, Recording.WordStatus.RECITED, "lladhi", endsSura = false) + session.finish() + executor.runAll() + + val recording = store.list().single() + assertThat(recording.durationMs).isEqualTo(31_000) + assertThat(recording.words.map { it.startMs to it.endMs }).containsExactly(30_000L to 30_000L, 30_200L to 30_600L).inOrder() + } + + @Test + fun `nothing is recorded after the session is over`() = runTest { + val executor = QueueExecutor() + store = RecordingStore.forTest(context, preferences, ::RawWriter, { executor }, { now }) + val session = store.start(SuraAyah(67, 1), MemorizeState.Mode.MEMORIZE, contribute = false, info = emptyMap()) + audio(session, 1_000) + session.word(WordId(67, 1, 1), 100, 500, Recording.WordStatus.RECITED, "tabaraka", endsSura = false) + session.finish() + // a frame that was on its way when the session ended + audio(session, 1_000) + executor.runAll() + + assertThat(store.list().single().durationMs).isEqualTo(1_000) + val files = File(context.noBackupFilesDir, "memorize/recordings").list().orEmpty() + assertThat(files.count { it.endsWith(".m4a") }).isEqualTo(1) + } + + @Test + fun `sessions group their recordings, and go together`() = runTest { + val first = store.start(SuraAyah(112, 1), MemorizeState.Mode.MEMORIZE, contribute = false, info = emptyMap()) + audio(first, 3_000) + first.word(WordId(112, 4, 5), 2_000, 2_400, Recording.WordStatus.RECITED, "ahad", endsSura = true) + audio(first, 1_000) + now += 1_000 + first.word(WordId(113, 1, 1), 3_200, 3_500, Recording.WordStatus.MISSED, "qul", endsSura = false) + first.finish() + now += 60_000 + val second = store.start(SuraAyah(67, 1), MemorizeState.Mode.SALAH, contribute = true, info = emptyMap()) + audio(second, 1_000) + second.word(WordId(67, 1, 1), 100, 500, Recording.WordStatus.RECITED, "tabaraka", endsSura = false) + second.finish() + + val sessions = store.sessions() + assertThat(sessions.map { it.id }).containsExactly(second.session, first.session).inOrder() + assertThat(sessions[1].recordings).hasSize(2) + assertThat(sessions[1].start to sessions[1].end).isEqualTo(SuraAyah(112, 4) to SuraAyah(113, 1)) + assertThat(sessions[1].missed).isEqualTo(1) + assertThat(sessions.map { it.contribute }).containsExactly(true, false).inOrder() + + store.deleteSession(first.session) + assertThat(store.sessions().map { it.id }).containsExactly(second.session) + val files = File(context.noBackupFilesDir, "memorize/recordings").list().orEmpty() + assertThat(files.filter { !it.startsWith(store.list().single().id) }).isEmpty() + } + + @Test + fun `a contributed recording is never replaced`() = runTest { + preferences.keepRecordings = MemorizePreferences.KeepRecordings.REPLACE_SAME_PLACE + listOf(true, false).forEach { contribute -> + now += 60_000 + val session = store.start(SuraAyah(67, 1), MemorizeState.Mode.MEMORIZE, contribute = contribute, info = emptyMap()) + audio(session, 1_000) + session.word(WordId(67, 1, 1), 100, 500, Recording.WordStatus.RECITED, "tabaraka", endsSura = false) + session.finish() + } + assertThat(store.list().map { it.contribute }).containsExactly(false, true).inOrder() + } + + @Test + fun `the export has a contributed recording's details, and training segments end before a hint`() = runTest { + val session = store.start(SuraAyah(112, 1), MemorizeState.Mode.MEMORIZE, contribute = true, info = emptyMap()) + audio(session, 4_000) + session.heard(listOf(RecognizedToken("qu", 350, 0.9f))) + session.word(WordId(112, 1, 1), 300, 600, Recording.WordStatus.RECITED, "qul", endsSura = false) + session.word(WordId(112, 1, 2), 650, 900, Recording.WordStatus.RECITED, "huwa", endsSura = false) + // the hint voice starts just after the ayah + session.word(WordId(112, 2, 1), 1_000, null, Recording.WordStatus.HINTED, "allahu", endsSura = false) + session.finish() + + val entries = unzip(store.list().single()) + val folder = entries.keys.single { it.endsWith("alignment.json") }.substringBefore('/') + assertThat(entries.keys).contains("$folder/heard.jsonl") + assertThat(JSONObject(String(entries.getValue("$folder/alignment.json"))).getString("heard")).isEqualTo("heard.jsonl") + val manifest = String(entries.getValue("manifest.jsonl")).lines().filter { it.isNotBlank() }.map(::JSONObject) + assertThat(manifest.single().getDouble("duration")).isWithin(0.001).of(0.9) + } + + private fun audio(session: SessionRecorder, ms: Int) = repeat(ms / 100) { session.write(FloatArray(1_600) { 0.1f }) } + + /** Runs tasks only when asked to, as a phone too busy to keep up. */ + private class QueueExecutor : java.util.concurrent.Executor { + private val tasks = ArrayDeque() + + override fun execute(command: Runnable) { + tasks.addLast(command) + } + + fun runAll() { + while (tasks.isNotEmpty()) tasks.removeFirst().run() + } + } + + private fun unzip(recording: Recording): Map { + val bytes = ByteArrayOutputStream().also { RecordingExport.zip(listOf(recording), it) }.toByteArray() + val entries = HashMap() + ZipInputStream(bytes.inputStream()).use { zip -> + while (true) { + val entry = zip.nextEntry ?: break + entries[entry.name] = zip.readBytes() + } + } + return entries + } + + /** Writes the samples as they are. */ + private class RawWriter(file: File) : AudioFileWriter { + private val out = file.outputStream() + private var wrote = false + + override fun write(pcm: ShortArray, count: Int) { + for (i in 0 until count) out.write(pcm[i].toInt() and 0xff) + wrote = wrote || count > 0 + } + + override fun close(): Boolean { + out.close() + return wrote + } + } + + private fun interface Executor : java.util.concurrent.Executor +} diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/recording/SessionMarksTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/recording/SessionMarksTest.kt new file mode 100644 index 0000000000..1daabdbe03 --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/recording/SessionMarksTest.kt @@ -0,0 +1,68 @@ +package com.quran.mobile.feature.memorize.recording + +import com.google.common.truth.Truth.assertThat +import com.quran.data.model.SuraAyah +import com.quran.mobile.feature.memorize.presenter.Mark +import com.quran.mobile.feature.memorize.presenter.MemorizeHighlightTypes +import com.quran.mobile.feature.memorize.session.MemorizeState +import com.quran.mobile.feature.memorize.tracker.WordId +import org.junit.Test +import java.io.File + +class SessionMarksTest { + + // 112:1 recited (its second word after a mistake), 112:2:1 hinted, 112:2:2 skipped, 113:1:1 on another page + private val recording = Recording( + id = "s", session = "s", mode = MemorizeState.Mode.MEMORIZE, startedAt = 0, + start = SuraAyah(112, 1), end = SuraAyah(113, 1), + parts = listOf(Recording.Part(File("a"), 5_000), Recording.Part(File("b"), 5_000)), + words = listOf( + word(112, 1, 1, 100, 400), + word(112, 1, 2, 500, 800, mistakes = 1), + word(112, 2, 1, 1_000, null, Recording.WordStatus.HINTED), + word(112, 2, 2, null, null, Recording.WordStatus.MISSED), + word(113, 1, 1, 6_000, 6_300), + ), + ) + private val firstPage: (Recording.Word) -> Boolean = { it.id.sura == 112 } + + @Test + fun `before playing, the page shows how each word went`() { + assertThat(SessionMarks.marks(recording, null, firstPage)).containsExactly( + Mark(112, 1, 2, MemorizeHighlightTypes.MISTAKE), + Mark(112, 2, 1, MemorizeHighlightTypes.HINTED), + Mark(112, 2, 2, MemorizeHighlightTypes.MISSED), + ) + } + + @Test + fun `while playing, the word heard is lit and the words before it leave a trail`() { + assertThat(SessionMarks.marks(recording, 600, firstPage)).containsExactly( + Mark(112, 1, 1, MemorizeHighlightTypes.RECITED), + Mark(112, 1, 2, MemorizeHighlightTypes.PLAYING), + Mark(112, 2, 1, MemorizeHighlightTypes.HINTED), + Mark(112, 2, 2, MemorizeHighlightTypes.MISSED), + ) + // the next page's word is heard: nothing on this one is + assertThat(SessionMarks.marks(recording, 6_100, firstPage).map { it.type }).doesNotContain(MemorizeHighlightTypes.PLAYING) + } + + @Test + fun `a tap plays from the word, or from the ayah's first word heard`() { + assertThat(SessionMarks.timeOf(recording, 112, 1, 2)).isEqualTo(500) + assertThat(SessionMarks.timeOf(recording, 112, 2, 2)).isEqualTo(1_000) + assertThat(SessionMarks.timeOf(recording, 112, 3, null)).isNull() + } + + @Test + fun `a position is found in the part that holds it`() { + assertThat(RecordingPlayer.partAt(recording.parts, 4_999)).isEqualTo(0 to 4_999L) + assertThat(RecordingPlayer.partAt(recording.parts, 5_000)).isEqualTo(1 to 0L) + assertThat(RecordingPlayer.partAt(recording.parts, 12_000)).isEqualTo(1 to 5_000L) + } + + private fun word( + sura: Int, ayah: Int, word: Int, start: Long?, end: Long?, + status: Recording.WordStatus = Recording.WordStatus.RECITED, mistakes: Int = 0, + ) = Recording.Word(WordId(sura, ayah, word), start, end, status, "", mistakes) +} diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/session/MemorizeSessionControllerTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/session/MemorizeSessionControllerTest.kt new file mode 100644 index 0000000000..acade075ca --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/session/MemorizeSessionControllerTest.kt @@ -0,0 +1,1153 @@ +package com.quran.mobile.feature.memorize.session + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import app.cash.turbine.test +import com.google.common.truth.Truth.assertThat +import com.quran.data.model.SuraAyah +import com.quran.mobile.feature.memorize.audio.AudioSource +import com.quran.mobile.feature.memorize.audio.AudioSourceFactory +import com.quran.mobile.feature.memorize.check.DoubleCheck +import com.quran.mobile.feature.memorize.data.LexiconRepository +import com.quran.mobile.feature.memorize.data.LineSource +import com.quran.mobile.feature.memorize.data.PageLines +import com.quran.mobile.feature.memorize.data.Passage +import com.quran.mobile.feature.memorize.model.SpeechModelStore +import com.quran.mobile.feature.memorize.prompt.HintVoice +import com.quran.mobile.feature.memorize.recording.Recorders +import com.quran.mobile.feature.memorize.recording.Recording +import com.quran.mobile.feature.memorize.recording.SessionEvent +import com.quran.mobile.feature.memorize.recording.SessionRecorder +import com.quran.mobile.feature.memorize.settings.MemorizePreferences +import com.quran.mobile.feature.memorize.tracker.WordId +import com.quran.mobile.feature.memorize.tracker.engine.RecitationEngine +import com.quran.mobile.feature.memorize.tracker.engine.RecitationStream +import com.quran.mobile.feature.memorize.tracker.engine.RecognizedToken +import com.quran.mobile.progress.session.AyahResult +import com.quran.mobile.progress.session.SessionRecord +import com.quran.recitation.events.RecitationEventPresenter +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * The whole session pipeline with a scripted speech engine and a fake microphone: the lexicon, + * tracker, hint scheduler and state publishing are the real ones. Everything runs on the test's + * scheduler and virtual clock, so the hint delays are exact and nothing waits for real time. + */ +@OptIn(ExperimentalCoroutinesApi::class) +@Config(sdk = [33]) +@RunWith(RobolectricTestRunner::class) +class MemorizeSessionControllerTest { + + private val context: Context = ApplicationProvider.getApplicationContext() + private val events = RecitationEventPresenter() + private val engine = ScriptedEngine() + private val microphone = FakeMicrophone() + private val voice = FakeVoice() + private lateinit var preferences: MemorizePreferences + private var enginesCreated = 0 + private var engineFailure: Throwable? = null + // audio the user says while the speech model is still loading + private var duringModelLoad: (() -> Unit)? = null + private var inCall = false + + @Before + fun setUp() { + preferences = MemorizePreferences(context).apply { + correctorEnabled = true + hintDelaySeconds = 15 // long enough that no hint is given on its own unless a test wants one + } + } + + private val recorders = FakeRecorders() + private val loadedSuras = mutableListOf() + + private val doubleCheck = FakeDoubleCheck() + private val results = mutableListOf() + + private fun TestScope.controller( + lookaheadWords: Int = 300, + lines: LineSource = LineSource { emptyMap() }, + ): MemorizeSessionController = MemorizeSessionController.forTest( + lexicon = LexiconRepository.forTest(context, StandardTestDispatcher(testScheduler)), + models = SpeechModelStore(context), + preferences = preferences, + recitationEventPresenter = events, + engineFactory = { + engineFailure?.let { throw it } + enginesCreated++ + duringModelLoad?.invoke() + engine + }, + promptPlayer = voice, + audioSources = microphone, + callState = { inCall }, + scope = backgroundScope, + worker = StandardTestDispatcher(testScheduler), + clock = { testScheduler.currentTime }, + lines = lines, + upcoming = { loadedSuras += it }, + recorders = recorders, + lookaheadWords = lookaheadWords, + doubleChecks = { doubleCheck.also { it.opened++ } }, + results = { results += it }, + ) + + @Test + fun `words are revealed as they are recited and the session follows the ayah`() = runTest { + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + + // Al-Ikhlas 1: قُل هُوَ ٱللَّهُ أَحَدٌ (as pronounced) + recite("قُل", "هُوَ", "للَااهُ", "ءَحَدڇ") + + val state = controller.state.value!! + assertThat(state.cursor).isEqualTo(4) + assertThat(state.isHidden(3)).isFalse() + assertThat(state.isHidden(4)).isTrue() + assertThat(state.currentAyah).isEqualTo(SuraAyah(112, 2)) + assertThat(events.recitationSession()?.currentAyah()).isEqualTo(SuraAyah(112, 2)) + } + + @Test + fun `a wrong word is marked but not revealed`() = runTest { + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + + recite("قُل", "هُوَ", "سَمِعَ", "مُوسَاا", "كَتَبَ") + + assertThat(controller.state.value!!.mistake).isEqualTo(2) + assertThat(controller.state.value!!.isHidden(2)).isTrue() + } + + @Test + fun `an ayah left out is held at, nothing after it revealed and its first word marked`() = runTest { + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + + // ayah 1, then ayah 3: ayah 2 left out + recite(*pronunciations(SuraAyah(112, 1), 4)) + recite(*pronunciations(SuraAyah(112, 3), 4)) + + val state = controller.state.value!! + assertThat(state.cursor).isEqualTo(4) + assertThat(state.missed).isEmpty() + assertThat(state.mistake).isEqualTo(4) + assertThat(state.isHidden(8)).isTrue() + } + + @Test + fun `with hints off, an ayah left out is held for the hint delay, then the user is followed on`() = runTest { + preferences.correctorEnabled = false + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + + // ayah 1, then ayah 3: ayah 2 left out + recite(*pronunciations(SuraAyah(112, 1), 4)) + recite(*pronunciations(SuraAyah(112, 3), 4)) + assertThat(controller.state.value!!.cursor).isEqualTo(4) + + // the user goes on (no hint will give them ayah 2) + advanceTimeBy(3_000) + recite(*pronunciations(SuraAyah(112, 4), 5)) + + val state = controller.state.value!! + assertThat(state.cursor).isEqualTo(15) + assertThat(state.missed).containsAtLeast(4, 5) + assertThat(voice.played).isEmpty() + } + + @Test + fun `when every word must be heard, an unheard word holds the session`() = runTest { + preferences.everyWordHeard = true + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + + // the last word of ayah 1 isn't heard + recite(*pronunciations(SuraAyah(112, 1), 3)) + recite(*pronunciations(SuraAyah(112, 2), 2)) + + assertThat(controller.state.value!!.cursor).isEqualTo(3) + assertThat(controller.state.value!!.missed).isEmpty() + } + + @Test + fun `a hint reveals and speaks the next word`() = runTest { + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + + controller.requestHint() + runCurrent() + + assertThat(controller.state.value!!.cursor).isEqualTo(1) + assertThat(controller.state.value!!.hinted).containsExactly(0) + assertThat(voice.played).containsExactly(listOf(WordId(112, 1, 1))) + } + + @Test + fun `reading hides nothing and the session follows the reader`() = runTest { + val controller = controller() + controller.start(SuraAyah(112, 1), MemorizeState.Mode.RECITE) + runCurrent() + assertThat(controller.state.value!!.isHidden(0)).isFalse() + + recite("قُل", "هُوَ", "للَااهُ", "ءَحَدڇ") + + val state = controller.state.value!! + assertThat(state.cursor).isEqualTo(4) + assertThat(state.isHidden(4)).isFalse() + assertThat(state.showMistakes).isTrue() + } + + @Test + fun `a mistake while reading is marked, and the correct word said after the delay`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(112, 1), MemorizeState.Mode.RECITE) + runCurrent() + recite("قُل", "هُوَ", "سَمِعَ", "مُوسَاا", "كَتَبَ") + assertThat(controller.state.value!!.mistake).isEqualTo(2) + + microphone.silence(3) + advanceTimeBy(5_000) + + assertThat(voice.played.first()).containsExactly(WordId(112, 1, 3)) + assertThat(controller.state.value!!.hinted).containsExactly(2) + } + + @Test + fun `without saying the correct word, a mistake while reading is only marked`() = runTest { + preferences.hintDelaySeconds = 2 + preferences.reciteSayFix = false + val controller = controller() + controller.start(SuraAyah(112, 1), MemorizeState.Mode.RECITE) + runCurrent() + recite("قُل", "هُوَ", "سَمِعَ", "مُوسَاا", "كَتَبَ") + + microphone.silence(3) + advanceTimeBy(10_000) + + assertThat(voice.played).isEmpty() + assertThat(controller.state.value!!.mistake).isEqualTo(2) + } + + @Test + fun `without marking mistakes, a mistake while reading isn't shown but the word is still said`() = runTest { + preferences.hintDelaySeconds = 2 + preferences.reciteMarkMistakes = false + val controller = controller() + controller.start(SuraAyah(112, 1), MemorizeState.Mode.RECITE) + runCurrent() + recite("قُل", "هُوَ", "سَمِعَ", "مُوسَاا", "كَتَبَ") + assertThat(controller.state.value!!.mistake).isNull() + assertThat(controller.state.value!!.showMistakes).isFalse() + + microphone.silence(3) + advanceTimeBy(5_000) + + assertThat(voice.played.first()).containsExactly(WordId(112, 1, 3)) + } + + @Test + fun `a reader who leaves out an ayah is held at it, and given its first word after the delay`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(112, 1), MemorizeState.Mode.RECITE) + runCurrent() + + // ayah 1, then ayah 3: ayah 2 left out + recite(*pronunciations(SuraAyah(112, 1), 4)) + recite(*pronunciations(SuraAyah(112, 3), 4)) + assertThat(controller.state.value!!.cursor).isEqualTo(4) + assertThat(controller.state.value!!.mistake).isEqualTo(4) + + microphone.silence(3) + advanceTimeBy(5_000) + + assertThat(voice.played.first()).containsExactly(WordId(112, 2, 1)) + } + + @Test + fun `without saying the correct word, a reader who left out an ayah is followed on after the delay`() = runTest { + preferences.hintDelaySeconds = 2 + preferences.reciteSayFix = false + val controller = controller() + controller.start(SuraAyah(112, 1), MemorizeState.Mode.RECITE) + runCurrent() + + recite(*pronunciations(SuraAyah(112, 1), 4)) + recite(*pronunciations(SuraAyah(112, 3), 4)) + assertThat(controller.state.value!!.cursor).isEqualTo(4) + + advanceTimeBy(3_000) + recite(*pronunciations(SuraAyah(112, 4), 5)) + + val state = controller.state.value!! + assertThat(state.cursor).isEqualTo(15) + assertThat(state.missed).containsAtLeast(4, 5) + assertThat(voice.played).isEmpty() + } + + @Test + fun `a reader who stops gets no help, the next word is in front of them`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(112, 1), MemorizeState.Mode.RECITE) + runCurrent() + recite("قُل", "هُوَ") + + microphone.silence(3) + advanceTimeBy(10_000) + + assertThat(voice.played).isEmpty() + assertThat(controller.state.value!!.cursor).isEqualTo(2) + } + + @Test + fun `a session recorded to contribute keeps what the model heard and what the session did`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(112, 1), contribute = true) + runCurrent() + recite("قُل", "هُوَ", "سَمِعَ", "مُوسَاا", "كَتَبَ") + microphone.silence(3) + advanceTimeBy(5_000) + controller.stop() + runCurrent() + + val recorder = recorders.started.single() + assertThat(recorder.keepsDetails).isTrue() + assertThat(recorder.heard).containsAtLeast("قُل", "هُوَ", "سَمِعَ").inOrder() + val kinds = recorder.details.map { it.kind } + assertThat(kinds).containsAtLeast( + SessionEvent.Kind.SPEECH, SessionEvent.Kind.MISTAKE, SessionEvent.Kind.MARK_SHOWN, SessionEvent.Kind.HINT, + ).inOrder() + assertThat(recorder.details.first { it.kind == SessionEvent.Kind.HINT }.word).isEqualTo(WordId(112, 1, 3)) + // the hinted word had a mistake marked on it + assertThat(recorder.words).contains(WordId(112, 1, 3) to Recording.WordStatus.HINTED) + assertThat(recorder.mistakes).containsExactly(WordId(112, 1, 3), 1) + assertThat(recorder.events.last()).isEqualTo("finish") + } + + @Test + fun `a session that isn't contributing tells its recording nothing more`() = runTest { + val controller = controller() + controller.start(SuraAyah(112, 1), record = true) + runCurrent() + recite("قُل", "هُوَ", "سَمِعَ", "مُوسَاا", "كَتَبَ") + controller.stop() + runCurrent() + + val recorder = recorders.started.single() + assertThat(recorder.heard).isEmpty() + assertThat(recorder.details).isEmpty() + } + + @Test + fun `stopping ends the session`() = runTest { + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + + controller.stop() + runCurrent() + + assertThat(controller.state.value).isNull() + assertThat(events.recitationSession()).isNull() + assertThat(microphone.running).isFalse() + } + + @Test + fun `starting again while the session is being prepared is ignored`() = runTest { + val controller = controller() + + controller.start(SuraAyah(112, 1)) + controller.start(SuraAyah(113, 1)) + runCurrent() + + assertThat(controller.state.value!!.passage.start).isEqualTo(SuraAyah(112, 1)) + assertThat(enginesCreated).isEqualTo(1) + } + + @Test + fun `what is recited while the model loads isn't lost`() = runTest { + val controller = controller() + duringModelLoad = { + // the microphone is already on: the user starts reciting at once + assertThat(microphone.running).isTrue() + engine.script += listOf("قُل", "هُوَ") + repeat(4) { microphone.frame() } + } + + controller.start(SuraAyah(112, 1)) + runCurrent() + + assertThat(controller.state.value!!.cursor).isEqualTo(2) + } + + @Test + fun `stopping while the session is being prepared loads nothing`() = runTest { + val controller = controller() + + controller.start(SuraAyah(112, 1)) + controller.stop() + runCurrent() + + assertThat(controller.state.value).isNull() + assertThat(enginesCreated).isEqualTo(0) + assertThat(microphone.running).isFalse() + } + + @Test + fun `a session that can't start is reported and ended`() = runTest { + val controller = controller() + engineFailure = OutOfMemoryError("model too large") + + controller.failures.test { + controller.start(SuraAyah(112, 1)) + awaitItem() + } + runCurrent() + + assertThat(controller.state.value).isNull() + assertThat(events.recitationSession()).isNull() + assertThat(microphone.running).isFalse() + + // and the next start works + engineFailure = null + controller.start(SuraAyah(112, 1)) + runCurrent() + assertThat(controller.state.value!!.status).isEqualTo(MemorizeState.Status.LISTENING) + } + + @Test + fun `in salah a stall while reciting the passage gets a hint`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(112, 1), MemorizeState.Mode.SALAH) + runCurrent() + recite("قُل", "هُوَ") + + microphone.silence(3) + advanceTimeBy(5_000) + + assertThat(voice.played.first()).containsExactly(WordId(112, 1, 3)) + } + + @Test + fun `in salah no hint is given once the next rak'ah's Al-Fatiha begins`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(108, 1), MemorizeState.Mode.SALAH) + runCurrent() + // إِنَّا أَعْطَيْنَاكَ ... + recite(*pronunciations(SuraAyah(108, 1), 2)) + assertThat(controller.state.value!!.cursor).isEqualTo(2) + + // ruku, sujud... and the next rak'ah starts with Al-Fatiha + recite(*pronunciations(SuraAyah(1, 2), 8)) + microphone.silence(3) + advanceTimeBy(10_000) + + assertThat(voice.played).isEmpty() + assertThat(controller.state.value!!.cursor).isEqualTo(2) + } + + @Test + fun `after too many hints in a row it stays quiet until the user recites again`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + recite("قُل", "هُوَ") + microphone.silence(3) + + // ten hints without the user going on, then it gives up + advanceTimeBy(60_000) + assertThat(voice.played).hasSize(10) + + // something that isn't the next word doesn't bring the hints back... + recite("سَمِعَ", "مُوسَاا", "كَتَبَ") + microphone.silence(3) + advanceTimeBy(20_000) + assertThat(voice.played).hasSize(10) + + // ...reciting the next words does (a few: a single word can start several ayat) + val state = controller.state.value!! + recite(*state.passage.words.drop(state.cursor).take(3).map { it.wasl }.toTypedArray()) + assertThat(controller.state.value!!.cursor).isEqualTo(state.cursor + 3) + microphone.silence(3) + advanceTimeBy(3_000) + assertThat(voice.played).hasSize(11) + } + + @Test + fun `no hints during a phone call`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + recite("قُل", "هُوَ") + + // the call silences the microphone: that's not the user being stuck + inCall = true + advanceTimeBy(1_000) + microphone.silence(3) + advanceTimeBy(10_000) + assertThat(voice.played).isEmpty() + assertThat(controller.state.value!!.cursor).isEqualTo(2) + + // after the call, hints are back + inCall = false + advanceTimeBy(5_000) + assertThat(voice.played).isNotEmpty() + } + + @Test + fun `after the microphone fails and the user resumes, the wait for a hint starts over`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + recite("قُل", "هُوَ") + + microphone.fail() + runCurrent() + assertThat(controller.state.value!!.status).isEqualTo(MemorizeState.Status.PAUSED) + advanceTimeBy(30_000) + + controller.pauseOrResume() + runCurrent() + assertThat(controller.state.value!!.status).isEqualTo(MemorizeState.Status.LISTENING) + microphone.silence(3) + // a pause right after resuming isn't being stuck yet: the delay counts from the resume + advanceTimeBy(1_200) + assertThat(controller.state.value!!.cursor).isEqualTo(2) + assertThat(voice.played).isEmpty() + + advanceTimeBy(5_000) + assertThat(voice.played).isNotEmpty() + } + + @Test + fun `the session goes on into the next sura instead of ending with this one`() = runTest { + val controller = controller(lookaheadWords = 5) + controller.start(SuraAyah(112, 1)) + runCurrent() + assertThat(controller.state.value!!.passage.words.last().id.sura).isEqualTo(112) + + recite(*pronunciations(SuraAyah(112, 1), 15)) + + val state = controller.state.value!! + assertThat(state.status).isEqualTo(MemorizeState.Status.LISTENING) + assertThat(state.cursor).isEqualTo(15) + // Al-Falaq is there before the user gets to it, and hidden + assertThat(state.passage.words[15].id).isEqualTo(WordId(113, 1, 1)) + assertThat(state.isHidden(15)).isTrue() + + recite(basmala()) + recite(*pronunciations(SuraAyah(113, 1), 4)) + assertThat(controller.state.value!!.cursor).isEqualTo(19) + assertThat(controller.state.value!!.mistake).isNull() + assertThat(events.recitationSession()?.currentAyah()).isEqualTo(SuraAyah(113, 2)) + } + + @Test + fun `after Al-Fatiha the basmala of the next sura isn't a mistake`() = runTest { + val controller = controller(lookaheadWords = 5) + controller.start(SuraAyah(1, 1)) + runCurrent() + val fatiha = controller.state.value!!.passage.words.count { it.id.sura == 1 } + + recite(*pronunciations(SuraAyah(1, 1), fatiha)) + recite(basmala()) + recite(*pronunciations(SuraAyah(2, 1), 3)) + + val state = controller.state.value!! + assertThat(state.cursor).isEqualTo(fatiha + 3) + assertThat(state.mistake).isNull() + assertThat(state.passage.words[fatiha].id).isEqualTo(WordId(2, 1, 1)) + } + + @Test + fun `a stopped session's results are handed on once, with counts per ayah`() = runTest { + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + recite("قُل", "هُوَ", "للَااهُ", "ءَحَدڇ") + controller.requestHint() + runCurrent() + + controller.stop() + runCurrent() + controller.stop() + runCurrent() + + val record = results.single() + assertThat(record.mode).isEqualTo("MEMORIZE") + assertThat(record.words).isEqualTo(5) + assertThat(record.hinted).isEqualTo(1) + assertThat(record.recited).isEqualTo(4) + assertThat(record.finished).isFalse() + assertThat(record.startSura to record.startAyah).isEqualTo(112 to 1) + assertThat(record.endSura to record.endAyah).isEqualTo(112 to 2) + assertThat(record.ayahs).containsExactly( + AyahResult(112, 1, ayahWords = 4, words = 4, hinted = 0, missed = 0, mistakes = 0), + AyahResult(112, 2, ayahWords = 2, words = 1, hinted = 1, missed = 0, mistakes = 0), + ).inOrder() + } + + @Test + fun `a session stopped before anything was revealed has no results`() = runTest { + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + controller.stop() + runCurrent() + assertThat(results).isEmpty() + } + + @Test + fun `a session that can't start has no results`() = runTest { + val controller = controller() + engineFailure = OutOfMemoryError("model too large") + controller.start(SuraAyah(112, 1)) + runCurrent() + assertThat(results).isEmpty() + } + + @Test + fun `a finished session's results are handed on when it finishes, and not again when it's closed`() = runTest { + val controller = controller(lookaheadWords = 5) + controller.start(SuraAyah(114, 1)) + runCurrent() + recite(*pronunciations(SuraAyah(114, 1), 20)) + runCurrent() + assertThat(results.single().finished).isTrue() + + controller.stop() + runCurrent() + assertThat(results).hasSize(1) + assertThat(results.single().ayahs.map { it.ayah }).containsExactly(1, 2, 3, 4, 5, 6).inOrder() + } + + @Test + fun `a session only finishes at the end of the Quran`() = runTest { + val controller = controller(lookaheadWords = 5) + controller.start(SuraAyah(114, 1)) + runCurrent() + + recite(*pronunciations(SuraAyah(114, 1), 20)) + + assertThat(controller.state.value!!.status).isEqualTo(MemorizeState.Status.FINISHED) + assertThat(microphone.running).isFalse() + } + + @Test + fun `after three single words the hints give the rest of the ayah or of the line`() = runTest { + preferences.hintDelaySeconds = 2 + // Al-Ikhlas 3 on one line; 4 starts with two words at the end of the next line + val lines = LineSource { + mapOf(PageLines.key(112, 3) to intArrayOf(11, 11, 11, 11), PageLines.key(112, 4) to intArrayOf(12, 12, 13, 13, 13)) + } + val controller = controller(lines = lines) + controller.start(SuraAyah(112, 3)) + runCurrent() + + microphone.silence(3) + advanceTimeBy(40_000) + + fun words(ayah: Int, vararg numbers: Int) = numbers.map { WordId(112, ayah, it) } + assertThat(voice.played.take(6)).containsExactly( + words(3, 1), words(3, 2), words(3, 3), + // the rest of ayah 3 (one word), the rest of the line, then the rest of ayah 4 (it fits its line) + words(3, 4), words(4, 1, 2), words(4, 3, 4, 5), + ).inOrder() + } + + @Test + fun `a recorded session records what it hears and what happened to each word`() = runTest { + val controller = controller() + controller.start(SuraAyah(112, 1), record = true) + runCurrent() + val recorder = recorders.started.single() + assertThat(controller.state.value!!.recordingId).isEqualTo(recorder.session) + + recite("قُل", "هُوَ") + controller.requestHint() + runCurrent() + controller.pauseOrResume() + runCurrent() + // nothing is recorded while paused + val frames = recorder.frames + microphone.frame() + runCurrent() + controller.stop() + runCurrent() + + assertThat(recorder.frames).isEqualTo(frames) + assertThat(frames).isGreaterThan(0) + assertThat(recorder.words.map { it.first to it.second }).containsExactly( + WordId(112, 1, 1) to Recording.WordStatus.RECITED, + WordId(112, 1, 2) to Recording.WordStatus.RECITED, + WordId(112, 1, 3) to Recording.WordStatus.HINTED, + ).inOrder() + assertThat(recorder.events).containsExactly("pause", "finish").inOrder() + } + + @Test + fun `a session isn't recorded unless asked to`() = runTest { + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + recite("قُل") + + assertThat(recorders.started).isEmpty() + assertThat(controller.state.value!!.recordingId).isNull() + } + + @Test + fun `the suras a session loads are announced, e g to download their hint voice`() = runTest { + val controller = controller(lookaheadWords = 5) + controller.start(SuraAyah(112, 1)) + runCurrent() + assertThat(loadedSuras).containsExactly(112..112) + + recite(*pronunciations(SuraAyah(112, 1), 15)) + assertThat(loadedSuras).containsExactly(112..112, 113..113).inOrder() + } + + @Test + fun `the user can start anywhere on screen, which is hidden from the start`() = runTest { + val controller = controller() + // Al-Ikhlas on screen, up to its last ayah + controller.start(SuraAyah(112, 1), startAnywhereUntil = SuraAyah(112, 4)) + runCurrent() + assertThat(controller.state.value!!.started).isFalse() + assertThat(controller.state.value!!.isHidden(0)).isTrue() + assertThat(controller.state.value!!.isHidden(14)).isTrue() + + // starting at ayah 2 (اللَّهُ الصَّمَدُ, words 4 and 5) and on into ayah 3 + recite(*pronunciations(SuraAyah(112, 2), 4)) + + val state = controller.state.value!! + assertThat(state.started).isTrue() + assertThat(state.firstWord).isEqualTo(4) + assertThat(state.cursor).isEqualTo(8) + // the words before the start are shown again, without counting as skipped + assertThat(state.isHidden(0)).isFalse() + assertThat(state.missed).isEmpty() + assertThat(state.isHidden(8)).isTrue() + } + + @Test + fun `reciting what isn't on screen marks the first word, which is then given`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(112, 1), startAnywhereUntil = SuraAyah(112, 4)) + runCurrent() + + // Al-Falaq instead + recite(*pronunciations(SuraAyah(113, 1), 12)) + assertThat(controller.state.value!!.mistake).isEqualTo(0) + assertThat(controller.state.value!!.started).isFalse() + + microphone.silence(3) + advanceTimeBy(5_000) + assertThat(voice.played.first()).containsExactly(WordId(112, 1, 1)) + assertThat(controller.state.value!!.started).isTrue() + } + + @Test + fun `no hint before the user starts, however long they wait`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(112, 1), startAnywhereUntil = SuraAyah(112, 4)) + runCurrent() + + microphone.silence(3) + advanceTimeBy(30_000) + + assertThat(voice.played).isEmpty() + assertThat(controller.state.value!!.started).isFalse() + } + + @Test + fun `in salah a passage that isn't on screen is shown, not spoken`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(112, 1), MemorizeState.Mode.SALAH, startAnywhereUntil = SuraAyah(112, 4)) + runCurrent() + // Al-Fatiha, then Al-Falaq instead of the page's sura + recite(*pronunciations(SuraAyah(1, 2), 29)) + recite(*pronunciations(SuraAyah(113, 1), 20)) + + assertThat(controller.state.value!!.mistake).isEqualTo(0) + microphone.silence(3) + advanceTimeBy(10_000) + assertThat(voice.played).isEmpty() + } + + @Test + fun `the user can start a few pages before or after the one on screen`() = runTest { + val controller = controller() + // the page on screen starts with Al-Ikhlas; Al-Masad before it and Al-Falaq after it are in reach + controller.start(SuraAyah(111, 1), startAnywhereUntil = SuraAyah(113, 5), home = SuraAyah(112, 1)) + runCurrent() + val home = controller.state.value!!.passage.words.indexOfFirst { it.id == WordId(112, 1, 1) } + // until the user starts, the session is where the user is + assertThat(controller.state.value!!.currentAyah).isEqualTo(SuraAyah(112, 1)) + + recite(basmala()) + recite(*pronunciations(SuraAyah(113, 1), 4)) + + val state = controller.state.value!! + assertThat(state.started).isTrue() + assertThat(state.firstWord).isEqualTo(home + 15) + assertThat(state.currentAyah).isEqualTo(SuraAyah(113, 2)) + } + + @Test + fun `no hint while the start is heard at two places alike, and a pause settles it`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + // 2:149 and 2:150 open with the same 8 words + controller.start(SuraAyah(2, 147), startAnywhereUntil = SuraAyah(2, 151)) + runCurrent() + val passage = controller.state.value!!.passage.words + // recited elsewhere first: the first word on screen is marked, and would be given after the delay + recite(*pronunciations(SuraAyah(1, 2), 8)) + assertThat(controller.state.value!!.mistake).isNotNull() + + recite(*pronunciations(SuraAyah(2, 149), 5)) + advanceTimeBy(5_000) + assertThat(voice.played).isEmpty() + assertThat(controller.state.value!!.started).isFalse() + + microphone.silence(12) + advanceTimeBy(1_000) + runCurrent() + val state = controller.state.value!! + assertThat(state.started).isTrue() + assertThat(passage[state.firstWord].id).isEqualTo(WordId(2, 149, 1)) + assertThat(passage[state.cursor].id).isEqualTo(WordId(2, 149, 6)) + } + + @Test + fun `starting outside the pages around marks the first word on screen`() = runTest { + preferences.hintDelaySeconds = 2 + val controller = controller() + controller.start(SuraAyah(111, 1), startAnywhereUntil = SuraAyah(113, 5), home = SuraAyah(112, 1)) + runCurrent() + val home = controller.state.value!!.passage.words.indexOfFirst { it.id == WordId(112, 1, 1) } + + // Al-Fatiha is nowhere near + recite(*pronunciations(SuraAyah(1, 2), 8)) + assertThat(controller.state.value!!.mistake).isEqualTo(home) + + microphone.silence(3) + advanceTimeBy(5_000) + assertThat(voice.played.first()).containsExactly(WordId(112, 1, 1)) + } + + @Test + fun `with the double-check on, a hint for a word the user did say is dropped`() = runTest { + preferences.doubleCheck = true + preferences.hintDelaySeconds = 4 + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + recite("قُل", "هُوَ") + // the user said the next word, but the speech model missed it + doubleCheck.saidWords += 2 + + microphone.silence(3) + advanceTimeBy(5_000) + + val state = controller.state.value!! + assertThat(doubleCheck.asked).contains(2) + assertThat(voice.played).isEmpty() + // counted as recited: not hinted + assertThat(state.cursor).isEqualTo(3) + assertThat(state.hinted).isEmpty() + } + + @Test + fun `with the double-check on, a hint for a word the user didn't say is given`() = runTest { + preferences.doubleCheck = true + preferences.hintDelaySeconds = 4 + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + recite("قُل", "هُوَ") + + microphone.silence(3) + advanceTimeBy(5_000) + + assertThat(doubleCheck.asked).contains(2) + assertThat(voice.played).contains(listOf(WordId(112, 1, 3))) + assertThat(controller.state.value!!.hinted).contains(2) + } + + @Test + fun `with the double-check on, a mistake is only shown if the word wasn't said`() = runTest { + preferences.doubleCheck = true + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + + recite("قُل", "هُوَ", "سَمِعَ", "مُوسَاا", "كَتَبَ") + // not before the check has listened again + assertThat(controller.state.value!!.mistake).isNull() + advanceTimeBy(1_500) + runCurrent() + + assertThat(doubleCheck.asked).contains(2) + assertThat(controller.state.value!!.mistake).isEqualTo(2) + } + + @Test + fun `with the double-check on, a mistake on a word that was said isn't shown`() = runTest { + preferences.doubleCheck = true + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + doubleCheck.saidWords += 2 + + recite("قُل", "هُوَ", "سَمِعَ", "مُوسَاا", "كَتَبَ") + advanceTimeBy(1_500) + runCurrent() + + assertThat(doubleCheck.asked).contains(2) + assertThat(controller.state.value!!.mistake).isNull() + } + + @Test + fun `the double-check never hears the hints`() = runTest { + preferences.doubleCheck = true + preferences.hintDelaySeconds = 4 + voice.hold = true + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + recite("قُل") + microphone.silence(3) + advanceTimeBy(5_000) + assertThat(voice.played).hasSize(1) + + // the microphone hears the hint being played + microphone.loud(10) + runCurrent() + voice.finish() + advanceTimeBy(1_000) + // the next hint's check gets what the user said only + microphone.silence(3) + advanceTimeBy(5_000) + + assertThat(doubleCheck.asked).hasSize(2) + assertThat(doubleCheck.heardHint).isFalse() + } + + @Test + fun `the double-check is off unless turned on, and released with the session`() = runTest { + val controller = controller() + controller.start(SuraAyah(112, 1)) + runCurrent() + assertThat(doubleCheck.opened).isEqualTo(0) + controller.stop() + runCurrent() + + preferences.doubleCheck = true + controller.start(SuraAyah(112, 1)) + runCurrent() + assertThat(doubleCheck.opened).isEqualTo(1) + controller.stop() + runCurrent() + assertThat(doubleCheck.closed).isEqualTo(1) + } + + // ------------------------------------------------------------------------------------ helpers + + /** Each word comes out of the engine for one microphone frame. */ + private fun TestScope.recite(vararg words: String) { + engine.script += words + repeat(words.size + 2) { microphone.frame() } + runCurrent() + } + + /** How the first [count] words from [start] sound, as the speech model would hear them. */ + private suspend fun TestScope.pronunciations(start: SuraAyah, count: Int): Array = + LexiconRepository.forTest(context, StandardTestDispatcher(testScheduler)).passage(start) + .words.take(count).map { it.wasl }.toTypedArray() + + /** The basmala as the speech model would hear it. */ + private suspend fun TestScope.basmala(): String = + LexiconRepository.forTest(context, StandardTestDispatcher(testScheduler)).phrases(setOf("basmala")).first().second + + private class ScriptedEngine : RecitationEngine { + val script = ArrayDeque() + private var time = 0L + + override fun newStream(): RecitationStream = object : RecitationStream { + override fun accept(samples: FloatArray, count: Int, speech: Boolean): List { + time += 100 + val word = script.removeFirstOrNull() ?: return emptyList() + return listOf(RecognizedToken(word, time)) + } + + override fun finish(): List = emptyList() + override fun close() {} + } + + override fun close() {} + } + + private class FakeMicrophone : AudioSourceFactory { + var running = false + private var onFrame: ((FloatArray, Int, Boolean) -> Unit)? = null + private var onError: ((Throwable) -> Unit)? = null + + override fun create( + onFrame: (FloatArray, Int, Boolean) -> Unit, + onError: (Throwable) -> Unit, + ): AudioSource { + this.onFrame = onFrame + this.onError = onError + return object : AudioSource { + override fun start() { running = true } + override fun stop() { running = false } + } + } + + fun frame() = send(FloatArray(1_600) { 0.1f }, speech = true) + + fun silence(frames: Int) = repeat(frames) { send(FloatArray(1_600), speech = false) } + + /** What the microphone hears while a hint plays. */ + fun loud(frames: Int) = repeat(frames) { send(FloatArray(1_600) { LOUD }, speech = true) } + + fun fail() { + running = false + onError?.invoke(IllegalStateException("microphone taken")) + } + + private fun send(samples: FloatArray, speech: Boolean) { + if (running) onFrame?.invoke(samples, samples.size, speech) + } + } + + private class FakeRecorders : Recorders { + val started = mutableListOf() + + override fun start(start: SuraAyah, mode: MemorizeState.Mode, contribute: Boolean, info: Map): SessionRecorder = + FakeRecorder(contribute).also { started += it } + } + + private class FakeRecorder(override val keepsDetails: Boolean) : SessionRecorder { + override val session = "recorded-session" + var frames = 0 + val words = mutableListOf>() + val mistakes = mutableMapOf() + val events = mutableListOf() + val heard = mutableListOf() + val details = mutableListOf() + + override fun heard(tokens: List) { + heard += tokens.map { it.text } + } + + override fun event(event: SessionEvent) { + details += event + } + + override fun write(samples: FloatArray) { + frames++ + } + + override fun word( + word: WordId, + startMs: Long?, + endMs: Long?, + status: Recording.WordStatus, + phonemes: String, + endsSura: Boolean, + mistakes: Int, + ) { + words += word to status + if (mistakes > 0) this.mistakes[word] = mistakes + } + + override fun pause() { + events += "pause" + } + + override fun finish() { + events += "finish" + } + } + + private companion object { + const val LOUD = 0.5f + } + + private class FakeDoubleCheck : DoubleCheck { + var opened = 0 + var closed = 0 + val saidWords = mutableSetOf() + val asked = mutableListOf() + // whether it was given what the microphone heard while a hint played (FakeMicrophone.loud) + var heardHint = false + + override val lastMs: Long = 600 + + override fun said(audio: FloatArray, passage: Passage, k: Int): Boolean { + asked += k + if (audio.any { it == LOUD }) heardHint = true + return k in saidWords + } + + override fun close() { + closed++ + } + } + + private class FakeVoice : HintVoice { + val played = mutableListOf>() + // keep playing until finish() + var hold = false + private var playing: (() -> Unit)? = null + + fun finish() { + playing?.invoke() + playing = null + } + + private class Words(val words: List) : HintVoice.Clip + + override fun prepare(qariId: Int, words: List): HintVoice.Clip = Words(words) + + override fun play(clip: HintVoice.Clip, onStarted: () -> Unit, onFinished: () -> Unit) { + played += (clip as Words).words + onStarted() + if (hold) playing = onFinished else onFinished() + } + + override fun stop() {} + } +} diff --git a/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/ui/MemorizeScreensRenderTest.kt b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/ui/MemorizeScreensRenderTest.kt new file mode 100644 index 0000000000..32b2bb420e --- /dev/null +++ b/feature/memorize/src/test/kotlin/com/quran/mobile/feature/memorize/ui/MemorizeScreensRenderTest.kt @@ -0,0 +1,254 @@ +package com.quran.mobile.feature.memorize.ui + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Paint +import android.view.View +import android.os.Looper +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.widthIn +import androidx.compose.ui.unit.dp +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SnackbarHostState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import com.quran.data.model.SuraAyah +import com.quran.mobile.feature.memorize.recording.Recording +import com.quran.mobile.feature.memorize.recording.RecordingPlayer +import com.quran.mobile.feature.memorize.recording.SessionCounts +import com.quran.mobile.feature.memorize.recording.SessionListScreen +import com.quran.mobile.feature.memorize.recording.SessionRow +import com.quran.mobile.feature.memorize.recording.SessionScreen +import com.quran.mobile.feature.memorize.recording.SessionsSideBySide +import com.quran.mobile.feature.memorize.tracker.WordId +import com.quran.recitation.pages.PagePreview +import com.quran.recitation.pages.PageRenderer +import com.quran.recitation.presenter.RecitationHighlightsPresenter.HighlightAction +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import com.quran.labs.androidquran.common.ui.core.QuranTheme +import com.quran.mobile.feature.memorize.session.MemorizeState +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import java.io.File +import java.time.Duration + +/** + * Draws the feature's screens to PNG files (build/outputs/memorize-renders) so they can be looked at + * without a phone: light and dark, English and Arabic, phone and tablet. Only with -Pmemorize.render. + */ +@Config(sdk = [34]) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@RunWith(RobolectricTestRunner::class) +class MemorizeScreensRenderTest { + + private val output = File("build/outputs/memorize-renders").apply { mkdirs() } + + @Before + fun onlyWhenAsked() { + assumeTrue(System.getProperty("memorize.render") != null) + } + + @Test + fun `the mode window`() { + val all = listOf(MemorizeState.Mode.MEMORIZE, MemorizeState.Mode.RECITE) + val withSalah = all + MemorizeState.Mode.SALAH + eachLook("mode_window") { arabic -> + ModeSheetOnScrim(ModeSheetState(if (arabic) "الملك، الآية ١" else "Al-Mulk, ayah 1", all, ModeSheetState.RecordLine.Off)) + } + eachLook("mode_window_contribute") { arabic -> + ModeSheetOnScrim( + ModeSheetState(if (arabic) "الملك، الآية ١" else "Al-Mulk, ayah 1", withSalah, ModeSheetState.RecordLine.Contributing) + ) + } + eachLook("mode_window_ask", tablet = false) { arabic -> + ModeSheetOnScrim(ModeSheetState(if (arabic) "الملك، الآية ١" else "Al-Mulk, ayah 1", all, ModeSheetState.RecordLine.Ask)) + } + } + + @Test + fun `the recording sessions`() { + eachLook("sessions") { arabic -> + SessionListScreen( + rows = sessionRows(arabic), + summary = if (arabic) "٤ جلسات · ٨٤ م.ب · «سجّل وساهم» مفعّل" else "4 sessions · 84 MB · Record and contribute is on", + snackbar = remember { SnackbarHostState() }, + onOpen = {}, onDelete = {}, onExportAll = {}, onDeleteAll = {}, onBack = {}, + ) + } + eachLook("sessions_empty", tablet = false) { + SessionListScreen( + rows = emptyList(), summary = null, snackbar = remember { SnackbarHostState() }, + onOpen = {}, onDelete = {}, onExportAll = {}, onDeleteAll = {}, onBack = {}, + ) + } + } + + @Test + fun `a session played back on its pages`() { + eachLook("session_window") { arabic -> Session(arabic) } + } + + @Test + fun `the recording sessions side by side on a tablet`() { + eachLook("sessions_side_by_side", phone = false) { arabic -> + SessionsSideBySide( + width = LocalConfiguration.current.screenWidthDp.dp, + list = { + SessionListScreen( + rows = sessionRows(arabic), + summary = if (arabic) "٤ جلسات · ٨٤ م.ب · «سجّل وساهم» مفعّل" else "4 sessions · 84 MB · Record and contribute is on", + snackbar = remember { SnackbarHostState() }, + onOpen = {}, onDelete = {}, onExportAll = {}, onDeleteAll = {}, onBack = {}, + selectedId = sessionRows(arabic).first().id, + ) + }, + session = { Session(arabic) }, + ) + } + } + + /** Al-Mulk 1–15 at 1:04, with two words given, one skipped and one marked. */ + @Composable + private fun Session(arabic: Boolean) { + val recording = Recording( + id = "s", session = "s", mode = MemorizeState.Mode.MEMORIZE, startedAt = 0, + start = SuraAyah(67, 1), end = SuraAyah(67, 15), + parts = listOf(Recording.Part(File("a"), 252_000)), + words = (1..120).map { + val status = when (it) { + 23, 71 -> Recording.WordStatus.HINTED + 96 -> Recording.WordStatus.MISSED + else -> Recording.WordStatus.RECITED + } + Recording.Word(WordId(67, 1 + it / 8, 1 + it % 8), it * 2_000L, it * 2_000L + 600, status, "", mistakes = if (it == 48) 1 else 0) + }, + ) + SessionScreen( + title = if (arabic) "الملك ١–١٥" else "Al-Mulk 1–15", + subtitle = if (arabic) "الحفظ · ١٢ نوفمبر ٢٠٢٦، ٩:٤٠ م" else "Memorization · 12 Nov 2026, 21:40", + recording = recording, + counts = SessionCounts(recited = 52, hinted = 2, missed = 1, mistakes = 1), + pages = listOf(562, 563), + pageOf = { if (it.id.ayah < 13) 562 else 563 }, + playback = RecordingPlayer.Playback(recording, 64_000, isPlaying = true), + renderer = FakePages(LocalContext.current), + onBack = {}, onExport = {}, onDelete = {}, onPlay = {}, onPause = {}, onSeek = {}, onSkip = {}, + ) + } + + private fun sessionRows(arabic: Boolean): List { + fun row(id: String, mode: MemorizeState.Mode, en: String, ar: String, detailsEn: String, detailsAr: String, day: Int, contributed: Boolean) = + SessionRow( + id, mode, if (arabic) ar else en, if (arabic) detailsAr else detailsEn, + listOf(if (arabic) "اليوم" else "Today", if (arabic) "أمس" else "Yesterday", if (arabic) "الاثنين، ١٠ نوفمبر" else "Monday, November 10")[day], + contributed, + ) + return listOf( + row("1", MemorizeState.Mode.MEMORIZE, "Al-Mulk 1–15", "الملك ١–١٥", "Memorization · 21:40 · 4:12", "الحفظ · ٩:٤٠ م · ٤:١٢", 0, true), + row("2", MemorizeState.Mode.RECITE, "Al-Kahf 1–10", "الكهف ١–١٠", "Recitation · 08:05 · 6:30", "التلاوة · ٨:٠٥ ص · ٦:٣٠", 0, true), + row("3", MemorizeState.Mode.SALAH, "Al-Ala 1 – Al-Ghashiyah 26", "الأعلى ١ – الغاشية ٢٦", "In prayer (salah) · 20:10 · 9:48", "في الصلاة · ٨:١٠ م · ٩:٤٨", 1, false), + row("4", MemorizeState.Mode.MEMORIZE, "An-Naba 1–40", "النبأ ١–٤٠", "Memorization · 06:30 · 11:02", "الحفظ · ٦:٣٠ ص · ١١:٠٢", 2, false), + ) + } + + /** Stands in for the app's pages: a page with lines of text. */ + private class FakePages(private val context: Context) : PageRenderer { + override val isNightMode: Boolean = false + + override fun page(page: Int, onTapped: (SuraAyah, Int?) -> Unit): PagePreview = object : PagePreview { + override val view: View = object : View(context) { + private val paint = Paint().apply { color = 0xFFD8CFBE.toInt() } + + override fun onDraw(canvas: Canvas) { + canvas.drawColor(0xFFFFFBF2.toInt()) + val lineHeight = height / 17f + for (line in 1..15) { + val top = line * lineHeight + lineHeight * 0.3f + canvas.drawRect(width * 0.08f, top, width * 0.92f, top + lineHeight * 0.4f, paint) + } + } + } + + override fun apply(actions: List) {} + + override fun release() {} + } + + override fun close() {} + } + + @Composable + private fun ModeSheetOnScrim(state: ModeSheetState) { + Box(modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.32f)), contentAlignment = Alignment.BottomCenter) { + // the sheet is at most 840dp wide (on a tablet) + ModeSheetContent(state, Modifier.widthIn(max = 840.dp), onChoose = { _, _ -> }) + } + } + + /** Renders [content] light and dark, in English and Arabic, on a phone (and a tablet). */ + private fun eachLook(name: String, tablet: Boolean = true, phone: Boolean = true, content: @Composable (arabic: Boolean) -> Unit) { + // size, density + val devices = listOfNotNull( + Triple("phone", "w411dp-h891dp", "xxhdpi").takeIf { phone }, + Triple("phone_landscape", "w891dp-h411dp", "xxhdpi").takeIf { phone }, + Triple("small_phone", "w360dp-h640dp", "xhdpi").takeIf { phone }, + Triple("tablet", "w840dp-h1280dp", "mdpi").takeIf { tablet }, + // the Huawei MatePad 12 X, 2800×1840 at xhdpi + Triple("matepad_landscape", "w1400dp-h920dp", "xhdpi").takeIf { tablet }, + Triple("matepad_portrait", "w920dp-h1400dp", "xhdpi").takeIf { tablet }, + ) + for ((device, size, density) in devices) { + for (arabic in listOf(false, true)) { + for (dark in listOf(false, true)) { + // in Android's order: locale, size, night mode, density + val qualifiers = listOf(if (arabic) "ar" else "en", size, if (dark) "night" else "notnight", density).joinToString("-") + render("${name}_${device}_${if (arabic) "ar" else "en"}_${if (dark) "dark" else "light"}", qualifiers, dark, arabic) { + content(arabic) + } + } + } + } + } + + private fun render(file: String, qualifiers: String, dark: Boolean, rtl: Boolean, content: @Composable () -> Unit) { + RuntimeEnvironment.setQualifiers(qualifiers) + val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup() + val activity = controller.get() + activity.actionBar?.hide() + activity.setContent { + // the app declares right-to-left support; this test's manifest doesn't + CompositionLocalProvider(LocalLayoutDirection provides if (rtl) LayoutDirection.Rtl else LayoutDirection.Ltr) { + QuranTheme(useDarkTheme = dark) { + Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surface)) { content() } + } + } + } + // a few frames: lazy layouts (the pager) place their content after the first + repeat(3) { shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100)) } + val view = activity.window.decorView + val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888) + view.draw(Canvas(bitmap)) + File(output, "$file.png").outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } + controller.pause().stop().destroy() + } +} diff --git a/feature/memorize/src/test/resources/check/tiny.onnx b/feature/memorize/src/test/resources/check/tiny.onnx new file mode 100644 index 0000000000..6729500ba1 Binary files /dev/null and b/feature/memorize/src/test/resources/check/tiny.onnx differ diff --git a/feature/memorize/src/test/resources/check/tiny_converted.onnx b/feature/memorize/src/test/resources/check/tiny_converted.onnx new file mode 100644 index 0000000000..5bc7bf183a Binary files /dev/null and b/feature/memorize/src/test/resources/check/tiny_converted.onnx differ diff --git a/feature/memorize/tracker/build.gradle.kts b/feature/memorize/tracker/build.gradle.kts new file mode 100644 index 0000000000..2b27ca18fa --- /dev/null +++ b/feature/memorize/tracker/build.gradle.kts @@ -0,0 +1,8 @@ +plugins { + id("quran.android.library") +} + +dependencies { + testImplementation(libs.junit) + testImplementation(libs.truth) +} diff --git a/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/PhonemeNormalizer.kt b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/PhonemeNormalizer.kt new file mode 100644 index 0000000000..5e53afafd8 --- /dev/null +++ b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/PhonemeNormalizer.kt @@ -0,0 +1,38 @@ +package com.quran.mobile.feature.memorize.tracker + +/** + * Folds the quran-transcript phonetic script (what the speech model emits and what the lexicon + * stores) to the letter level used for memorization: tajweed markers map to their base letter or + * are dropped, madd letters map to their letter class, and runs of the same symbol collapse (madd + * lengths, gemination, ghunna). Short vowels are kept unless [keepShortVowels] is false. + */ +object PhonemeNormalizer { + + private val special = mapOf( + 'ڇ' to null, // qalqala + 'ۜ' to null, // sakt + 'ـ' to null, // elongation marker + 'ں' to 'ن', // noon mokhfah (ikhfa) + '۾' to 'م', // meem mokhfah + 'ٲ' to 'ء', // hamza mosahala + 'ؙ' to 'ُ', // dama mokhtalasa + '۪' to 'َ', // fatha momala (imala) + ) + + private val longVowels = mapOf('ا' to 'ا', 'ۥ' to 'و', 'ۦ' to 'ي') + + val shortVowels: Set = setOf('َ', 'ُ', 'ِ') + + fun normalize(phonemes: String, keepShortVowels: Boolean = true): String { + val out = StringBuilder(phonemes.length) + for (raw in phonemes) { + if (raw.isWhitespace()) continue + val mapped = if (special.containsKey(raw)) special[raw] ?: continue else raw + val ch = longVowels[mapped] ?: mapped + if (!keepShortVowels && ch in shortVowels) continue + if (out.isNotEmpty() && out[out.length - 1] == ch) continue + out.append(ch) + } + return out.toString() + } +} diff --git a/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTracker.kt b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTracker.kt new file mode 100644 index 0000000000..e822f8366a --- /dev/null +++ b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTracker.kt @@ -0,0 +1,1103 @@ +package com.quran.mobile.feature.memorize.tracker + +import com.quran.mobile.feature.memorize.tracker.TrackerEvent.Mistake +import com.quran.mobile.feature.memorize.tracker.TrackerEvent.NonTarget +import com.quran.mobile.feature.memorize.tracker.TrackerEvent.Repetition +import com.quran.mobile.feature.memorize.tracker.TrackerEvent.WordMissed +import com.quran.mobile.feature.memorize.tracker.TrackerEvent.WordRecited +import kotlin.math.abs + +/** + * Follows a user reciting a known passage from memory. + * + * [words] are the passage's words as normalized phoneme strings ([PhonemeNormalizer]). The + * recognizer's output is fed in as [TimedPhoneme]s; the tracker answers with [TrackerEvent]s: + * which words were recited (to reveal them), where the user made a mistake, repeated themselves or + * skipped ahead. + * + * On every update the phonemes heard since the last recited word are aligned with a window of + * expected words using a weighted edit distance in which: + * - the alignment may start at any word at or before the cursor (going back to repeat is normal), + * - leading phonemes may be skipped as "garbage" (false starts, coughs, wrong attempts), + * - substitutions between vowels and between commonly confused consonants are cheaper, + * - insertions/deletions near word boundaries are cheaper (wasl/waqf pronunciation differences), + * - the end of the expected side is free (the user is in the middle of the passage). + * When nothing near the cursor matches after a mistake, a wider search finds where the user is. + * + * With a [startWindow] the user may start anywhere in the first [startWindow] words (e.g. the pages + * around the one on screen): the tracker first finds where they started, and reports a + * [Mistake.Kind.ELSEWHERE] on the word they were expected to start at (startIndex: e.g. the first + * word on screen) if what they recite isn't there. While what was heard is the same, word for word, + * at another place there (two ayat that open alike), the start waits for the words that differ. + * + * With [ayahs] (which ayah each word is in), going back to the start of the ayah is a repetition, + * and when lost, a restart behind the cursor is preferred to a jump ahead. [TrackerConfig.skipAyat] + * off (memorization), the user can't leave ayat out: the tracker holds at the first word not recited + * instead of catching up past it (see [TrackerConfig.maxMissedWords]). + * + * This is a port of the reference implementation used to benchmark the speech models; keep the + * two in sync (see the golden tests). + */ +class RecitationTracker( + words: List, + private val config: TrackerConfig = TrackerConfig(), + startIndex: Int = 0, + /** Phrases said around the passage that aren't mistakes: (kind, normalized phonemes). */ + phrases: List> = emptyList(), + /** How many of the first words the user may start at; 0 or 1: the first word. */ + private val startWindow: Int = 0, + /** Which ayah each word is in (any id per ayah), or empty when not known. */ + ayahs: List = emptyList(), +) { + + private val words = ArrayList(words) + private val phrases = ArrayList(phrases) + private val ayahs = ArrayList(ayahs) + // words left out so far, by ayah (only counted when the ayat are known) + private val missedInAyah = HashMap() + // the next catch-up may pass over what the tracker holds at (see releaseHold) + private var release = false + // where a repetition in progress (behind the cursor) goes on: the word after the last repeated + private var repeatNext: Int? = null + + /** Diagnostics: why the tracker decided what it did (e.g. why no start was found yet). */ + var trace: ((String) -> Unit)? = null + + var cursor: Int = startIndex + private set + + /** + * Whether what the user started with is the same, word for word, at two places in the start window, + * and the start waits for the words that tell them apart (a pause settles it at the nearer place). + */ + val startPending: Boolean get() = !anchored && waitedForStart + + /** Whether it is known where the user started (always, without a [startWindow]). */ + var anchored: Boolean = startWindow <= 1 + private set + + // where the user is expected to start, and how many words they recited from the start found: until a + // few have been, a mistake means the start was wrong and is looked for again. The start dropped that + // way becomes where they are expected: the search prefers it, and a mark or hint before a new start + // is there (not back at the first ayah on screen) + private var home = startIndex + private var sinceStart = if (startWindow <= 1) CONFIRMED_START_WORDS else 0 + // where a start was dropped that way: a word heard clearly right there takes it up again (the start + // was right, a word was misheard), while a new start elsewhere needs a run of words again + private var dropped: Int? = null + // the start was alike elsewhere and is being waited out + private var waitedForStart = false + + /** Whether every word loaded so far has been recited (see [extend]). */ + val isDone: Boolean get() = cursor >= words.size + + /** More of the passage, e.g. the next sura once the user nears the end of this one. */ + fun extend(more: List, moreAyahs: List = emptyList()) { + words.addAll(more) + if (ayahs.isNotEmpty()) ayahs.addAll(moreAyahs) + } + + /** Phrases that become possible later, e.g. the basmala once the passage leaves Al-Fatiha. */ + fun addPhrases(more: List>) { + phrases.addAll(more.filter { it !in phrases }) + } + + private val pending = ArrayList() + // what was heard before the pending phonemes since anything last explained it (they fell out of + // pending, which keeps the last maxPending): evidence of words said but misheard + private val overflow = ArrayList() + private var mistakeAt: Int? = null + + fun feed(phonemes: List): List { + pending.addAll(phonemes) + if (pending.size > config.maxPending) { + val dropped = pending.subList(0, pending.size - config.maxPending) + overflow.addAll(dropped) + if (overflow.size > OVERFLOW_MAX) overflow.subList(0, overflow.size - OVERFLOW_MAX).clear() + dropped.clear() + } + if (isDone || pending.isEmpty()) return emptyList() + return update() + } + + /** + * The user stopped making sound. A phrase heard completely up to now is complete even though + * nothing follows it (e.g. the takbir before ruku). + */ + fun onPause(): List { + // the user stopped while their start is the same at two places: the one nearest where they were + // expected (they may be stuck, and only a known start can be helped) + if (startPending) return findStart(settle = true) + if (pending.isEmpty() || phrases.isEmpty()) return emptyList() + val heard = CharArray(pending.size) { pending[it].symbol } + for ((kind, phrase) in phrases) { + if (!saidByPassage(phrase) && phraseCost(heard, phrase) <= 0.5 + 0.2 * phrase.length) { + val event = NonTarget(cursor, pending.last().timeMs, kind) + clearPending() + mistakeAt = null + return listOf(event) + } + } + return emptyList() + } + + /** What [count] sounds heard before a phrase cost (e.g. the rest of the last word, or an earlier phrase). */ + private fun phraseGarbage(count: Int): Double = minOf(count * config.garbageCost, config.phraseGarbageCap) + + /** Cost of [heard] being exactly [phrase] (allowing leading garbage). */ + private fun phraseCost(heard: CharArray, phrase: String): Double { + val n = heard.size + val m = phrase.length + val width = m + 1 + val cost = DoubleArray((n + 1) * width) { Double.POSITIVE_INFINITY } + for (i in 0..n) cost[i * width] = phraseGarbage(i) + for (i in 0..n) { + for (j in 1..m) { + var c = Double.POSITIVE_INFINITY + if (i > 0) { + c = minOf( + cost[(i - 1) * width + j - 1] + sub(heard[i - 1], phrase[j - 1]), + cost[(i - 1) * width + j] + config.indelCost + ) + } + cost[i * width + j] = minOf(c, cost[i * width + j - 1] + config.indelCost) + } + } + return cost[n * width + m] + } + + /** Forgets what was heard since the last recited word (it belonged to something else). */ + fun discardPending() { + clearPending() + mistakeAt = null + } + + /** The app revealed/played the next [count] words: they count as recited. */ + fun markHinted(count: Int) { + // a hint before the user found the start: they start where they were expected to + if (!anchored) cursor = home + anchored = true + sinceStart = CONFIRMED_START_WORDS + dropped = null + cursor = minOf(words.size, cursor + count) + // what was heard stays evidence (the user may have gone on) + setAside() + mistakeAt = null + } + + // ----------------------------------------------------------------------------------------- ayat + + private fun knowsAyat(): Boolean = ayahs.size == words.size && words.isNotEmpty() + + /** The first word of the ayah word [index] is in. */ + private fun ayahStart(index: Int): Int { + val ayah = ayahs[index] + var i = index + while (i > 0 && ayahs[i - 1] == ayah) i-- + return i + } + + private fun ayahLength(index: Int): Int { + var end = index + while (end + 1 < ayahs.size && ayahs[end + 1] == ayahs[index]) end++ + return end - ayahStart(index) + 1 + } + + /** + * The first word of the ayah of the last word reached, when a restart of it starts further back than + * [TrackerConfig.backWords] (at most [TrackerConfig.farBackWords]), else null. + */ + private fun restartStart(): Int? { + if (!knowsAyat() || cursor == 0) return null + val start = ayahStart(minOf(cursor, words.size) - 1) + return start.takeIf { it >= cursor - config.farBackWords && it < cursor - config.backWords } + } + + /** + * Where a repetition may start: [TrackerConfig.backWords] before the cursor, or (a restart) the + * start of the ayah of the last word reached, or where a repetition in progress goes on. + */ + private fun backStart(): Int = + listOfNotNull(maxOf(0, cursor - config.backWords), restartStart(), repeatNext).min() + + /** + * The app gave up hinting the words the tracker holds at (the user went on regardless): the next + * catch-up may pass over them, as if ayat could be left out. + */ + fun releaseHold() { + release = true + } + + /** Whether the words [missed] may be left behind as missed (see [TrackerConfig.skipAyat]). */ + private fun canPass(missed: List): Boolean { + if (config.skipAyat || missed.isEmpty() || release) return true + if (missed.size > config.maxMissedWords) return false + if (knowsAyat()) { + val perAyah = LinkedHashMap>() + for (x in missed) perAyah.getOrPut(ayahs[x]) { ArrayList() }.add(x) + for ((ayah, xs) in perAyah) { + if ((missedInAyah[ayah] ?: 0) + xs.size > ayahLength(xs[0]) / 2) return false + } + } + return true + } + + /** Words left out (not said), counted against their ayah. */ + private fun noteMissed(indexes: List) { + if (!knowsAyat()) return + for (x in indexes) { + val ayah = ayahs[x] + missedInAyah[ayah] = (missedInAyah[ayah] ?: 0) + 1 + } + } + + /** + * Of the words [missed] (not recited), those that count as left out: the ones not [said], and with + * every word to be heard ([TrackerConfig.maxMissedWords] 0), the ones said but misheard too. + */ + private fun leftOut(said: Set, missed: List): List = + if (config.maxMissedWords == 0) missed else missed.filter { it !in said } + + /** + * Which of words[[first], [last]) the [speech] heard (in order, before what came after them) was for: + * per word, the phonemes heard for it and their cost, aligning all of the words with all of it. + */ + private fun evidence(first: Int, last: Int, speech: CharArray): Map> { + val win = window(first, last) + val n = speech.size + val m = win.symbols.size + val width = m + 1 + val cost = DoubleArray((n + 1) * width) { Double.POSITIVE_INFINITY } + val back = CharArray((n + 1) * width) + cost[0] = 0.0 + // leading sounds: the end of the word before, a hesitation + for (i in 1..n) { + cost[i * width] = i * config.garbageCost + back[i * width] = 'g' + } + for (j in 1..m) { + cost[j] = cost[j - 1] + indel(win.symbols[j - 1], win.pos[j - 1], words[win.word[j - 1]].length) + back[j] = 'd' + } + for (i in 1..n) { + for (j in 1..m) { + val length = words[win.word[j - 1]].length + var best = cost[(i - 1) * width + j - 1] + sub(speech[i - 1], win.symbols[j - 1]) + var op = 's' + val ins = cost[(i - 1) * width + j] + indel(speech[i - 1], win.pos[j - 1], length) + if (ins < best) { + best = ins + op = 'i' + } + val del = cost[i * width + j - 1] + indel(win.symbols[j - 1], win.pos[j - 1], length) + if (del < best) { + best = del + op = 'd' + } + cost[i * width + j] = best + back[i * width + j] = op + } + } + val heard = IntArray(last - first) + val costs = DoubleArray(last - first) + var i = n + var j = m + while (i > 0 || j > 0) { + when (back[i * width + j]) { + 'g' -> i-- + 's' -> { + val w = win.word[j - 1] - first + heard[w]++ + costs[w] += sub(speech[i - 1], win.symbols[j - 1]) + i-- + j-- + } + 'i' -> { + costs[win.word[j - 1] - first] += indel(speech[i - 1], win.pos[j - 1], words[win.word[j - 1]].length) + i-- + } + else -> { + costs[win.word[j - 1] - first] += indel(win.symbols[j - 1], win.pos[j - 1], words[win.word[j - 1]].length) + j-- + } + } + } + return (first until last).associateWith { heard[it - first] to costs[it - first] } + } + + // ---------------------------------------------------------------------------------------- costs + + private fun sub(a: Char, b: Char): Double { + if (a == b) return 0.0 + val aVowel = a in PhonemeNormalizer.shortVowels + val bVowel = b in PhonemeNormalizer.shortVowels + if (aVowel && bVowel) return config.vowelSub + if (aVowel || bVowel) return config.consonantSub + if (CONFUSABLE.any { a in it && b in it }) return config.confusableSub + return config.consonantSub + } + + private fun indel(symbol: Char, pos: Int, length: Int): Double = when { + pos < config.edge || pos >= length - config.edge -> config.edgeIndelCost + symbol in PhonemeNormalizer.shortVowels -> config.vowelIndel + else -> config.indelCost + } + + // ------------------------------------------------------------------------------------ alignment + + private class Step(val op: Char, val pendingIndex: Int, val column: Int) + + private class Window(val first: Int, val symbols: CharArray, val word: IntArray, val pos: IntArray) + + private fun window(first: Int, last: Int): Window { + val symbols = StringBuilder() + val word = ArrayList() + val pos = ArrayList() + for (w in first until last) { + words[w].forEachIndexed { i, ch -> + symbols.append(ch) + word.add(w) + pos.add(i) + } + } + return Window(first, symbols.toString().toCharArray(), word.toIntArray(), pos.toIntArray()) + } + + /** + * Semi-global alignment of [heard] with the window; returns the path (garbage step first). Of + * equally good ends, the furthest one, or with [nearest] the one closest to that word. + */ + private fun align(heard: CharArray, win: Window, nearest: Int? = null, restart: Int? = null, next: Int? = null): List { + val n = heard.size + val m = win.symbols.size + val width = m + 1 + val cost = DoubleArray((n + 1) * width) { Double.POSITIVE_INFINITY } + val back = CharArray((n + 1) * width) + + // behind the cursor (with a [restart]): within backWords, or at the start of the ayah, not the + // words between (a phrase an ayah says twice, as 5:46, is otherwise taken for the earlier one) + val near = if (restart != null || next != null) cursor - config.backWords else Int.MIN_VALUE + val allowedStarts = BooleanArray(width) + for (j in 0 until m) { + val w = win.word[j] + if ((j == 0 || win.word[j - 1] != w) && w <= cursor && (w >= near || w == restart || w == next)) allowedStarts[j] = true + } + for (i in 0..n) { + for (j in 0..m) { + if (allowedStarts[j]) { + cost[i * width + j] = i * config.garbageCost + back[i * width + j] = 'g' + } + } + } + + for (i in 0..n) { + for (j in (if (i == 0) 1 else 0)..m) { + val idx = i * width + j + var best = cost[idx] + var op = back[idx] + if (i > 0 && j > 0) { + val diag = cost[(i - 1) * width + j - 1] + sub(heard[i - 1], win.symbols[j - 1]) + if (diag < best) { + best = diag + op = if (heard[i - 1] == win.symbols[j - 1]) 'm' else 's' + } + val length = words[win.word[j - 1]].length + val ins = cost[(i - 1) * width + j] + indel(heard[i - 1], win.pos[j - 1], length) + if (ins < best) { + best = ins + op = 'i' + } + } + if (j > 0) { + val length = words[win.word[j - 1]].length + val del = cost[i * width + j - 1] + indel(win.symbols[j - 1], win.pos[j - 1], length) + if (del < best) { + best = del + op = 'd' + } + } + cost[idx] = best + back[idx] = op + } + } + + // best end column for all of the heard phonemes (ties: the furthest column) + var jBest = 0 + for (j in 1..m) { + if (cost[n * width + j] <= cost[n * width + jBest]) jBest = j + } + if (nearest != null) { + // as good (within half a phoneme), and starting closer to where the user is expected: e.g. a + // phrase that the Quran repeats on several pages + fun startWord(end: Int): Int { + var i = n + var j = end + while ((i > 0 || j > 0) && back[i * width + j] != '\u0000' && back[i * width + j] != 'g') { + when (back[i * width + j]) { + 'm', 's' -> { i--; j-- } + 'i' -> i-- + else -> j-- + } + } + return win.word[minOf(j, m - 1)] + } + val best = cost[n * width + jBest] + var bestDistance = abs(startWord(jBest) - nearest) + for (j in 1..m) { + if (cost[n * width + j] > best + 0.5) continue + val distance = abs(startWord(j) - nearest) + if (distance < bestDistance) { + jBest = j + bestDistance = distance + } + } + } + + val path = ArrayList() + var i = n + var j = jBest + while ((i > 0 || j > 0) && back[i * width + j] != '\u0000') { + val op = back[i * width + j] + if (op == 'g') { + path.add(Step('g', i, j)) + break + } + path.add(Step(op, if (op == 'd') -1 else i - 1, j - 1)) + when (op) { + 'm', 's' -> { i--; j-- } + 'i' -> i-- + else -> j-- + } + } + path.reverse() + return path + } + + private class WordStats { + var cost = 0.0 + val covered = HashSet() + var firstPending = -1 + var lastPending = -1 + var matched = 0 + var heard = 0 + } + + private fun update(): List { + if (!anchored) return findStart() + val events = ArrayList() + val first = backStart() + val last = minOf(words.size, cursor + config.aheadWords) + val heard = CharArray(pending.size) { pending[it].symbol } + val win = window(first, last) + val path = align(heard, win, restart = restartStart(), next = repeatNext) + + val stats = HashMap() + for (step in path) { + if (step.op == 'g') continue + val col = maxOf(step.column, 0) + val w = win.word[col] + val pos = win.pos[col] + val word = words[w] + val s = stats.getOrPut(w) { WordStats() } + s.cost += when (step.op) { + 'm' -> 0.0 + 's' -> sub(heard[step.pendingIndex], word[pos]) + 'i' -> indel(heard[step.pendingIndex], pos, word.length) + else -> indel(word[pos], pos, word.length) + } + if (step.op == 'm' || step.op == 's' || step.op == 'd') s.covered.add(col) + if (step.op == 'm' || step.op == 's' || step.op == 'i') { + if (s.firstPending < 0) s.firstPending = step.pendingIndex + s.lastPending = step.pendingIndex + } + if (step.op == 'm') s.matched++ + if (step.op == 'm' || step.op == 's') s.heard++ + } + val columnStart = HashMap() + win.word.forEachIndexed { col, w -> columnStart.putIfAbsent(w, col) } + + fun complete(w: Int): Boolean { + val s = stats[w] ?: return false + val start = columnStart[w] ?: return false + return (start until start + words[w].length).all { it in s.covered } + } + + fun good(w: Int): Boolean { + val s = stats[w] ?: return false + return s.lastPending >= 0 && s.matched > 0 && s.cost <= config.allowance(words[w].length) + } + + fun timeOf(pendingIndex: Int): Long = pending[minOf(pendingIndex, pending.size - 1)].timeMs + val lastTime = pending.last().timeMs + + val repeated = stats.keys.filter { it < cursor && stats.getValue(it).lastPending >= 0 }.sorted() + + fun recited(w: Int): WordRecited { + val s = stats.getValue(w) + return WordRecited(w, timeOf(s.lastPending), s.cost, startMs = timeOf(s.firstPending)) + } + + var w = cursor + var lastPending = -1 + while (w < words.size && complete(w) && good(w)) { + lastPending = stats.getValue(w).lastPending + events += recited(w) + w++ + } + + // A known phrase can start like the passage (takbir "Allahu akbar" vs. a next word "Allahu"). + // While what was heard is still the beginning of a phrase, wait; once the phrase is complete + // and explains more than the passage words would, it wins. + if (lastPending >= 0 && phrases.isNotEmpty()) { + val phrase = matchPhrase(heard) + if (phrase != null) { + val (kind, completedAt) = phrase + if (completedAt == null) return emptyList() + if (completedAt > lastPending) { + val event = NonTarget(cursor, timeOf(completedAt), kind) + consumePending(completedAt) + mistakeAt = null + return listOf(event) + } + } + } + + // Re-synchronization: the user is confidently reciting words after the cursor (the model + // misheard a word, or the user skipped one). Catch up so the reader never gets stuck. + if (lastPending < 0) { + fun fromContext(x: Int): Boolean { + val s = stats[x] ?: return false + val length = words[x].length + return s.heard >= config.contextMinHeard * length && s.cost <= config.contextCost * length + } + var anchor = resyncAnchor(stats, ::complete, ::good) + // words left out may only be passed over within the limits (TrackerConfig.skipAyat); a word heard + // but not recognized was said + fun heard(x: Int): Boolean = (stats[x]?.heard ?: 0) >= config.contextMinHeard * words[x].length + val notRecited = if (anchor != null) (cursor until anchor).filter { !fromContext(it) } else emptyList() + val leftOut = leftOut(notRecited.filter { heard(it) }.toSet(), notRecited) + if (anchor != null && !canPass(leftOut)) anchor = null + if (anchor != null) { + for (x in cursor until anchor) { + val s = stats[x] + if (s != null && fromContext(x)) { + val time = if (s.lastPending >= 0) timeOf(s.lastPending) else lastTime + val start = if (s.firstPending >= 0) timeOf(s.firstPending) else null + events += WordRecited(x, time, s.cost, fromContext = true, startMs = start) + } else { + events += WordMissed(x, lastTime) + } + } + noteMissed(leftOut) + release = false + w = anchor + while (w < words.size && complete(w) && good(w)) { + lastPending = stats.getValue(w).lastPending + events += recited(w) + w++ + } + } + } + + if (lastPending >= 0) { + sinceStart += w - cursor + if (repeated.isNotEmpty()) { + events.add(0, Repetition(repeated.first(), repeated.last(), timeOf(stats.getValue(repeated.last()).lastPending))) + } + cursor = w + repeatNext = null + consumePending(lastPending) + mistakeAt = null + return events + } + + // No new word. A completed repetition is consumed so it doesn't count as unexplained speech. + if (repeated.isNotEmpty() && repeated.all { complete(it) && good(it) }) { + val lp = stats.getValue(repeated.last()).lastPending + events += Repetition(repeated.first(), repeated.last(), timeOf(lp)) + consumePending(lp) + repeatNext = (repeated.last() + 1).takeIf { it < cursor && knowsAyat() } + return events + } + + // Lost? The user kept reciting after a mistake but nothing near the cursor matches. + if (mistakeAt == cursor) { + val recovered = recover() + if (recovered != null) return events + recovered + } + + // A known phrase (isti'adha, basmala, takbir...) in progress or completed? + val phrase = matchPhrase(heard) + if (phrase != null) { + val (kind, completedAt) = phrase + if (completedAt != null) { + events += NonTarget(cursor, timeOf(completedAt), kind) + consumePending(completedAt) + mistakeAt = null + } + return events + } + + // Still repeating (e.g. starting the ayah again): what is being said now is a good match for a word + // behind the cursor, which isn't complete yet. Not a mistake. + if (repeated.isNotEmpty() && knowsAyat()) { + val heardWords = stats.filterValues { it.lastPending >= 0 }.keys + if (heardWords.all { it < cursor } && heardWords.all { stats.getValue(it).cost <= config.allowance(words[it].length) }) { + return events + } + } + + // Mistake? Right after the start was found, rather a wrong start: look for it again. + if (heard.size >= words[cursor].length + config.mistakeMargin && sinceStart < CONFIRMED_START_WORDS) { + trace?.invoke("start at $cursor not confirmed after $sinceStart words: searching again, expected there") + anchored = false + home = cursor + dropped = cursor + mistakeAt = null + return findStart() + } + if (heard.size >= words[cursor].length + config.mistakeMargin && mistakeAt != cursor) { + val skipped = cursor + 1 < words.size && good(cursor + 1) && (stats[cursor]?.matched ?: 0) == 0 + mistakeAt = cursor + events += Mistake(cursor, lastTime, if (skipped) Mistake.Kind.SKIP else Mistake.Kind.SUBSTITUTION) + } + return events + } + + /** + * Before it is known where the user started: the start is where what they recite matches a run of + * words in the start window. A known phrase (isti'adha, basmala...) is waited out; anything else + * long enough that matches nowhere in the window is recited elsewhere. + */ + private fun findStart(settle: Boolean = false): List { + val heard = CharArray(pending.size) { pending[it].symbol } + val windowEnd = minOf(startWindow, words.size) + // align as if the user could be repeating any word of the window + val saved = cursor + cursor = windowEnd - 1 + val win = window(0, minOf(words.size, windowEnd + config.aheadWords)) + val path = align(heard, win, nearest = home) + cursor = saved + val firstWords = LinkedHashMap() + for (step in path) { + if (step.op == 'g') continue + val col = maxOf(step.column, 0) + val w = win.word[col] + val pos = win.pos[col] + val s = firstWords.getOrPut(w) { WordStats() } + s.cost += when (step.op) { + 'm' -> 0.0 + 's' -> sub(heard[step.pendingIndex], words[w][pos]) + 'i' -> indel(heard[step.pendingIndex], pos, words[w].length) + else -> indel(words[w][pos], pos, words[w].length) + } + if (step.op == 'm' || step.op == 's' || step.op == 'd') s.covered.add(col) + if (step.op == 'm' || step.op == 'i' || step.op == 's') { + if (s.firstPending < 0) s.firstPending = step.pendingIndex + s.lastPending = step.pendingIndex + } + if (step.op == 'm') s.matched++ + } + val columnStart = HashMap() + win.word.forEachIndexed { col, w -> columnStart.putIfAbsent(w, col) } + fun confident(w: Int): Boolean { + val s = firstWords[w] ?: return false + val start = columnStart[w] ?: return false + val complete = (start until start + words[w].length).all { it in s.covered } + return complete && s.lastPending >= 0 && s.cost <= config.allowance(words[w].length) && + s.matched >= 0.6 * words[w].length + } + // the start dropped after a misheard word, and the user heard going on from it: it was right, twice + // over, and is no longer doubted. The words before the one heard clearly were said (misheard, as the + // one that dropped the start), unless nothing was heard there; it goes on after it + val at = dropped + val resumed = at?.let { + (at..minOf(at + RESUME_WORDS, words.size - 1)).firstOrNull { confident(it) && words[it].length >= RESUME_PHONEMES } + } + if (at != null && resumed != null) { + trace?.invoke("start at $at taken up again: ${words[resumed]} heard clearly at $resumed") + anchored = true + sinceStart = CONFIRMED_START_WORDS + dropped = null + waitedForStart = false + mistakeAt = null + val clear = firstWords.getValue(resumed) + val events = ArrayList() + for (x in at until resumed) { + val s = firstWords[x] + events += if (s != null && s.lastPending >= 0) { + WordRecited(x, timeOf(s.lastPending), s.cost, fromContext = true, startMs = s.firstPending.takeIf { it >= 0 }?.let(::timeOf)) + } else { + WordMissed(x, timeOf(clear.firstPending)) + } + } + events += WordRecited(resumed, timeOf(clear.lastPending), clear.cost, startMs = timeOf(clear.firstPending)) + consumePending(clear.lastPending) + cursor = resumed + 1 + return if (pending.isEmpty()) events else events + update() + } + // enough to tell the place: a few words in a row, and more of them if they are short ones (the + // window is large) + val start = firstWords.keys.filter { it < windowEnd }.firstOrNull { j -> + var count = 0 + var phonemes = 0 + while (j + count < words.size && confident(j + count) && (count < START_WORDS || phonemes < START_PHONEMES)) { + phonemes += words[j + count].length + count++ + } + count >= START_WORDS && phonemes >= START_PHONEMES + } + trace?.let { trace -> + val runs = firstWords.keys.filter { it < windowEnd }.map { j -> + var count = 0 + while (j + count < words.size && confident(j + count)) count++ + j to count + } + val best = runs.maxByOrNull { it.second } + trace( + "search heard=${String(heard)} confident=${firstWords.keys.filter { confident(it) }.take(12)} " + + "best=${best?.let { "${it.first}x${it.second}" }} start=$start window=$windowEnd home=$home", + ) + } + if (start != null) { + // what was heard is the same, word for word, at another place (e.g. two ayat that open alike): + // wait for the words that tell them apart, as long as there is room to keep listening + var run = 0 + while (start + run < words.size && confident(start + run)) run++ + val elsewhere = (0 until windowEnd).firstOrNull { k -> + k != start && k + run <= words.size && (0 until run).all { words[k + it] == words[start + it] } + } + if (elsewhere != null && !settle && pending.size < config.maxPending - AMBIGUOUS_ROOM) { + trace?.invoke("start at $start or $elsewhere ($run words alike): waiting") + waitedForStart = true + return emptyList() + } + anchored = true + sinceStart = 0 + cursor = start + dropped = null + mistakeAt = null + if (!waitedForStart) return update() + // after waiting, more words may have been heard than a normal update looks ahead: they count + waitedForStart = false + val events = ArrayList() + for (w in start until start + run) { + val s = firstWords.getValue(w) + events += WordRecited(w, timeOf(s.lastPending), s.cost, startMs = timeOf(s.firstPending)) + } + consumePending(firstWords.getValue(start + run - 1).lastPending) + cursor = start + run + sinceStart = run + return if (pending.isEmpty()) events else events + update() + } + + // no start (any more): nothing to wait for + waitedForStart = false + val phrase = matchPhrase(heard) + val completedAt = phrase?.second + if (phrase != null && completedAt != null) { + val event = NonTarget(cursor, timeOf(completedAt), phrase.first) + consumePending(completedAt) + // then whatever followed it + return listOf(event) + if (pending.isEmpty()) emptyList() else findStart() + } + // the beginning of a phrase (what is heard is cleared after each one, so it starts with it) + if (phrases.any { (_, phrase) -> prefixCost(heard, phrase) <= 0.5 + 0.2 * heard.size }) return emptyList() + // long enough to be several words, and nowhere in the window + if (heard.size >= ELSEWHERE_PHONEMES && mistakeAt != cursor) { + mistakeAt = cursor + val event = Mistake(cursor, pending.last().timeMs, Mistake.Kind.ELSEWHERE) + // what was recited elsewhere can't help finding the start + clearPending() + return listOf(event) + } + // only recent speech can be the start + if (pending.size > 2 * ELSEWHERE_PHONEMES) { + overflow.clear() + pending.subList(0, pending.size - 2 * ELSEWHERE_PHONEMES).clear() + } + return emptyList() + } + + private fun timeOf(pendingIndex: Int): Long = pending[minOf(pendingIndex, pending.size - 1)].timeMs + + /** Cost of [heard] being the beginning of [phrase] (from its first sound). */ + private fun prefixCost(heard: CharArray, phrase: String): Double { + val n = heard.size + val m = phrase.length + val width = m + 1 + val cost = DoubleArray((n + 1) * width) + for (j in 1..m) cost[j] = j * config.indelCost + for (i in 1..n) { + cost[i * width] = i * config.indelCost + for (j in 1..m) { + cost[i * width + j] = minOf( + cost[(i - 1) * width + j - 1] + sub(heard[i - 1], phrase[j - 1]), + cost[(i - 1) * width + j] + config.indelCost, + cost[i * width + j - 1] + config.indelCost, + ) + } + } + // the rest of the phrase may still be coming + return (1..m).minOf { cost[n * width + it] } + } + + /** Pending isn't explained by anything, but stays evidence of what was said. */ + private fun setAside() { + overflow.addAll(pending) + if (overflow.size > OVERFLOW_MAX) overflow.subList(0, overflow.size - OVERFLOW_MAX).clear() + pending.clear() + } + + /** What is still to be explained; anything heard before it is no longer evidence. */ + private fun clearPending() { + pending.clear() + overflow.clear() + } + + private fun consumePending(throughIndex: Int) { + overflow.clear() + pending.subList(0, minOf(pending.size, throughIndex + 1)).clear() + } + + private fun resyncAnchor( + stats: Map, + complete: (Int) -> Boolean, + good: (Int) -> Boolean, + ): Int? { + val run = config.resyncRun + for (j in cursor + 1 until minOf(words.size, cursor + config.aheadWords)) { + val end = minOf(words.size, j + run) + if (end - j != run) continue + if ((j until end).all { complete(it) && good(it) && stats.getValue(it).matched >= 0.6 * words[it].length }) { + return j + } + } + return null + } + + /** + * A place in the recovery window that matches what was heard last. [elsewhere]: behind, in the middle + * of the ayah before (further back than backWords), rather a phrase said again than a restart. + */ + private class Candidate( + val cost: Double, + val ahead: Boolean, + val distance: Int, + val end: Int, + val first: Int, + val last: Int, + val elsewhere: Boolean = false, + ) { + /** Restarts and going on first, then jumps ahead, then a phrase said again behind. */ + val rank: Int get() = if (elsewhere) 2 else if (ahead) 1 else 0 + } + + /** + * Searches words[cursor, cursor + farWords) for the most recent phonemes heard, and with the words' + * ayat also back to the start of the previous ayah. A confident match at or behind the cursor is a + * repetition (a restart); one ahead of it leaves the words before it missed and recites the matched + * ones, if they may be left out ([TrackerConfig.skipAyat]). Otherwise the tracker holds where it + * is: an empty list. + */ + private fun recover(): List? { + val tailLength = minOf(pending.size, config.recoverTail) + if (tailLength < config.recoverMinTail) return null + val tail = CharArray(tailLength) { pending[pending.size - tailLength + it].symbol } + var first = cursor + var current = -1 + var previous = -1 + if (knowsAyat() && cursor > 0) { + current = ayahStart(minOf(cursor, words.size - 1)) + previous = if (current > 0) ayahStart(current - 1) else current + first = maxOf(previous, cursor - config.farBackWords, 0) + } + val win = window(first, minOf(words.size, cursor + config.farWords)) + val n = tail.size + val m = win.symbols.size + if (m == 0) return null + val width = m + 1 + val cost = DoubleArray((n + 1) * width) + val start = IntArray((n + 1) * width) + for (j in 0..m) start[j] = j + for (i in 1..n) { + cost[i * width] = i * config.indelCost + start[i * width] = 0 + for (j in 1..m) { + var best = cost[(i - 1) * width + j - 1] + sub(tail[i - 1], win.symbols[j - 1]) + var st = start[(i - 1) * width + j - 1] + val up = cost[(i - 1) * width + j] + config.indelCost + if (up < best) { + best = up + st = start[(i - 1) * width + j] + } + val left = cost[i * width + j - 1] + config.indelCost + if (left < best) { + best = left + st = start[i * width + j - 1] + } + cost[i * width + j] = best + start[i * width + j] = st + } + } + val limit = config.recoverCost * n + val lastTime = pending.last().timeMs + val candidates = ArrayList() + for (j in 1..m) { + if (cost[n * width + j] > limit) continue + val startWord = win.word[minOf(start[n * width + j], m - 1)] + val endWord = win.word[j - 1] + if (endWord - startWord + 1 < 2) continue + val ahead = startWord > cursor + val distance = if (ahead) startWord - cursor else maxOf(0, cursor - 1 - endWord) + // behind, in the middle of the ayah before: rather a phrase said again further on (5:44 and 5:45 + // both end "wa man lam yahkum bima anzala llahu fa-ula'ika hum") than a restart + val elsewhere = current >= 0 && startWord < current && startWord > previous + 1 && + startWord < cursor - config.backWords && startWord != repeatNext + candidates += Candidate(cost[n * width + j], ahead, distance, j, startWord, endWord, elsewhere) + } + // Of the matches as good as the best (within half a phoneme), the nearest the cursor: a restart + // (at or behind it) before a jump ahead. A weaker match behind (a phrase the passage repeats) + // doesn't stand for one ahead that is better. Without the ayat, as before: the earliest end. + val ordered = if (knowsAyat()) { + val best = candidates.minOfOrNull { it.cost } ?: 0.0 + candidates.filter { it.cost <= best + 0.5 }.sortedWith(compareBy({ it.rank }, { it.distance }, { it.end })) + } else { + candidates + } + var held = false + for (candidate in ordered) { + // the match ahead was the user going on, held back: not a restart of the ayah before + if (candidate.elsewhere && held) continue + // only words fully covered by the match count; the last one may still be in progress + val endComplete = candidate.end == m || win.word[candidate.end] != candidate.last + val lastWord = if (endComplete) candidate.last else candidate.last - 1 + if (!candidate.ahead) { + // a restart (from behind the cursor), or the user simply going on + val events = ArrayList() + if (candidate.first < cursor) events += Repetition(candidate.first, minOf(candidate.last, cursor - 1), lastTime) + for (x in cursor..lastWord) events += WordRecited(x, lastTime, 0.0, recovered = true) + repeatNext = (lastWord + 1).takeIf { it < cursor && knowsAyat() } + cursor = maxOf(cursor, lastWord + 1) + clearPending() + mistakeAt = null + return events + } + val missed = (cursor until candidate.first).toList() + val said = HashSet() + val context = HashSet() + if (missed.isNotEmpty() && !config.skipAyat) { + // what was heard before the match: were the words between said (and misheard)? + val heard = overflow + pending + val speech = CharArray(heard.size - tailLength) { heard[it].symbol } + for ((x, evidence) in evidence(cursor, candidate.first, speech)) { + if (evidence.first >= config.contextMinHeard * words[x].length) { + said += x + if (evidence.second <= config.contextCost * words[x].length) context += x + } + } + } + val leftOut = leftOut(said, missed.filter { it !in context }) + if (!canPass(leftOut)) { + held = true + continue + } + val events = ArrayList() + missed.forEach { events += if (it in context) WordRecited(it, lastTime, 0.0, fromContext = true) else WordMissed(it, lastTime) } + noteMissed(leftOut) + release = false + for (x in candidate.first..lastWord) events += WordRecited(x, lastTime, 0.0, recovered = true) + cursor = lastWord + 1 + clearPending() + mistakeAt = null + return events + } + if (held) { + // the user went on past words that can't be left out: hold at the first of them (its mistake + // stands); what was heard of the later words is set aside (still evidence) + trace?.invoke("holding at $cursor: what was heard is further on") + setAside() + return emptyList() + } + return null + } + + /** + * If the heard phonemes are (the beginning of) a known phrase, returns its kind and the index of + * the last heard phoneme of the completed phrase, or null for the index while it's in progress. + */ + /** + * Whether the passage itself says [phrase] here: its words from the cursor (or one of the next two) + * spell it out (27:30 says the basmala). + */ + private fun saidByPassage(phrase: String): Boolean = (0..2).any { k -> + val from = cursor + k + from < words.size && words.subList(from, minOf(words.size, from + 12)).joinToString("").startsWith(phrase) + } + + private fun matchPhrase(heard: CharArray): Pair? { + var best: Pair? = null + for ((kind, phrase) in phrases) { + if (saidByPassage(phrase)) continue + val n = heard.size + val m = phrase.length + if (n == 0 || m == 0) continue + val width = m + 1 + val cost = DoubleArray((n + 1) * width) { Double.POSITIVE_INFINITY } + for (i in 0..n) cost[i * width] = phraseGarbage(i) + for (i in 0..n) { + for (j in 1..m) { + var c = Double.POSITIVE_INFINITY + if (i > 0) { + c = minOf( + cost[(i - 1) * width + j - 1] + sub(heard[i - 1], phrase[j - 1]), + cost[(i - 1) * width + j] + config.indelCost + ) + } + cost[i * width + j] = minOf(c, cost[i * width + j - 1] + config.indelCost) + } + } + // Completed: the best place for the phrase to end is before the end of what was heard (the + // user has moved on). Ending exactly at the end means its last sounds may still be coming. + var iEnd = 1 + for (i in 2..n) { + if (cost[i * width + m] <= cost[iEnd * width + m]) iEnd = i + } + if (cost[iEnd * width + m] <= 0.5 + 0.2 * m && iEnd < n) { + if (best == null || best.second == null) best = kind to (iEnd - 1) + continue + } + var jBest = 0 + for (j in 1..m) { + if (cost[n * width + j] < cost[n * width + jBest]) jBest = j + } + if (jBest > 0 && cost[n * width + jBest] <= 0.5 + 0.2 * n && best == null) { + best = kind to null + } + } + return best + } + + private companion object { + /** Phonemes heard (about six words) before a start that matches nowhere is a mistake. */ + const val ELSEWHERE_PHONEMES = 30 + /** Words, and phonemes in them, that must be heard confidently to know where the user started. */ + const val START_WORDS = 3 + const val START_PHONEMES = 10 + /** Words recited from the start found after which it is no longer doubted. */ + const val CONFIRMED_START_WORDS = 6 + /** A start dropped after a misheard word is taken up again on one clear word there or right after, this long. */ + const val RESUME_WORDS = 1 + const val RESUME_PHONEMES = 4 + /** Phonemes kept as evidence beyond pending. */ + const val OVERFLOW_MAX = 280 + /** Phonemes left in the pending buffer when a start alike elsewhere is chosen anyway (the nearest). */ + const val AMBIGUOUS_ROOM = 10 + + val CONFUSABLE: List> = listOf( + setOf('س', 'ص'), setOf('ت', 'ط'), setOf('د', 'ض'), setOf('ذ', 'ز', 'ظ'), setOf('ح', 'ه'), + setOf('ء', 'ع'), setOf('ق', 'ك'), setOf('ث', 'س'), setOf('ا', 'ء'), + ) + } +} diff --git a/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/TrackerConfig.kt b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/TrackerConfig.kt new file mode 100644 index 0000000000..34e7b53907 --- /dev/null +++ b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/TrackerConfig.kt @@ -0,0 +1,57 @@ +package com.quran.mobile.feature.memorize.tracker + +/** + * Tuning of [RecitationTracker]. The defaults come from the reference implementation + * (tools/memorize tracker) and the benchmark on real recordings. + */ +data class TrackerConfig( + /** How far back (in words) a repetition may start. */ + val backWords: Int = 8, + /** Expected words considered past the cursor for normal tracking. */ + val aheadWords: Int = 6, + /** Cost per heard phoneme skipped before the alignment starts (false starts, noise). */ + val garbageCost: Double = 0.55, + val consonantSub: Double = 1.0, + val confusableSub: Double = 0.6, + val vowelSub: Double = 0.5, + val vowelIndel: Double = 0.5, + val indelCost: Double = 1.0, + /** Insert/delete cost within [edge] phonemes of a word boundary (wasl/waqf differences). */ + val edgeIndelCost: Double = 0.35, + val edge: Int = 2, + /** Extra phonemes heard past the expected word before a mistake is declared. */ + val mistakeMargin: Int = 3, + val maxPending: Int = 80, + /** Confidently recited words needed to catch up past an unmatched word. */ + val resyncRun: Int = 2, + /** Fraction of a word that must have been heard to accept it from its context. */ + val contextMinHeard: Double = 0.4, + /** Cost per phoneme allowed when accepting a word from its context. */ + val contextCost: Double = 0.7, + /** How far ahead (in words) to look when the user is lost. */ + val farWords: Int = 40, + val recoverTail: Int = 18, + val recoverMinTail: Int = 12, + val recoverCost: Double = 0.2, + /** + * The most that sounds heard before a phrase may cost (the rest of a drawn-out word, or an earlier + * phrase that went unrecognized), so a takbir is still recognized after them. + */ + val phraseGarbageCap: Double = 1.0, + /** + * Whether the user may leave out ayat: catching up may then pass over any number of words (salah, + * where it is how a rak'ah picks the passage up again). Without it (memorization), a catch-up may + * pass over at most [maxMissedWords] words in a row and never more than half of an ayah; otherwise + * the tracker holds at the first word not recited (needs the words' ayat). + */ + val skipAyat: Boolean = true, + val maxMissedWords: Int = Int.MAX_VALUE, + /** How far back (in words) a restart is looked for. */ + val farBackWords: Int = 40, +) { + fun allowance(length: Int): Double = when { + length <= 3 -> 0.5 + length <= 7 -> 1.0 + else -> 0.18 * length + } +} diff --git a/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/TrackerEvent.kt b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/TrackerEvent.kt new file mode 100644 index 0000000000..025e4b8459 --- /dev/null +++ b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/TrackerEvent.kt @@ -0,0 +1,42 @@ +package com.quran.mobile.feature.memorize.tracker + +/** A recognized phoneme (a single normalized symbol) and when it was heard. */ +data class TimedPhoneme(val symbol: Char, val timeMs: Long) + +/** Events produced by [RecitationTracker]. Indexes refer to the passage's word list. */ +sealed interface TrackerEvent { + val index: Int + val timeMs: Long + + /** The word was recited (reveal it); [timeMs] is when its last sound was heard. */ + data class WordRecited( + override val index: Int, + override val timeMs: Long, + val cost: Double, + /** Accepted from its context: the words around it were clearly recited. */ + val fromContext: Boolean = false, + /** Found again after the user was lost. */ + val recovered: Boolean = false, + /** When its first sound was heard, if known. */ + val startMs: Long? = null, + ) : TrackerEvent + + /** The user moved on without saying this word. */ + data class WordMissed(override val index: Int, override val timeMs: Long) : TrackerEvent + + /** The user went back and repeated words [index]..[lastIndex] (normal while memorizing). */ + data class Repetition(override val index: Int, val lastIndex: Int, override val timeMs: Long) : TrackerEvent + + /** The user said something other than the word at [index]. */ + data class Mistake(override val index: Int, override val timeMs: Long, val kind: Kind) : TrackerEvent { + enum class Kind { + SUBSTITUTION, + SKIP, + /** What the user recites isn't anywhere the session may start (e.g. the pages on screen). */ + ELSEWHERE, + } + } + + /** A phrase that isn't part of the passage (isti'adha, basmala, takbir...) was said. */ + data class NonTarget(override val index: Int, override val timeMs: Long, val kind: String) : TrackerEvent +} diff --git a/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/WordId.kt b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/WordId.kt new file mode 100644 index 0000000000..0c4557b88e --- /dev/null +++ b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/WordId.kt @@ -0,0 +1,16 @@ +package com.quran.mobile.feature.memorize.tracker + +/** + * A word on the madani page: [word] is the 1-based glyph word number within the ayah, the same + * numbering the page images use (WordGlyph.wordPosition). + */ +data class WordId(val sura: Int, val ayah: Int, val word: Int) : Comparable { + + override fun compareTo(other: WordId): Int = when { + sura != other.sura -> sura.compareTo(other.sura) + ayah != other.ayah -> ayah.compareTo(other.ayah) + else -> word.compareTo(other.word) + } + + override fun toString(): String = "$sura:$ayah:$word" +} diff --git a/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/engine/RecitationEngine.kt b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/engine/RecitationEngine.kt new file mode 100644 index 0000000000..41acd3637b --- /dev/null +++ b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/engine/RecitationEngine.kt @@ -0,0 +1,29 @@ +package com.quran.mobile.feature.memorize.tracker.engine + +/** + * An on-device speech recognizer that turns recitation audio into phoneme tokens of the + * quran-transcript phonetic script. Implementations must not send audio anywhere. + */ +interface RecitationEngine : AutoCloseable { + /** Starts recognizing a new, independent audio stream. */ + fun newStream(): RecitationStream +} + +interface RecitationStream : AutoCloseable { + /** + * Feeds 16 kHz mono samples in [-1, 1] and returns the tokens recognized since the previous + * call. Tokens are final once returned. [speech] is whether the caller's voice activity detector + * heard sound in them: the stream may start over in real silence, but must never cut a word. + */ + fun accept(samples: FloatArray, count: Int = samples.size, speech: Boolean = true): List + + /** Signals the end of the audio and returns any remaining tokens. */ + fun finish(): List +} + +/** + * @param text a unit of the phonetic script (may be several characters, e.g. a letter and its vowel) + * @param timeMs when it was heard, relative to the start of the stream + * @param probability the model's confidence in it, if available + */ +data class RecognizedToken(val text: String, val timeMs: Long, val probability: Float? = null) diff --git a/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/hint/HintScheduler.kt b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/hint/HintScheduler.kt new file mode 100644 index 0000000000..16835970fb --- /dev/null +++ b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/hint/HintScheduler.kt @@ -0,0 +1,252 @@ +package com.quran.mobile.feature.memorize.tracker.hint + +import com.quran.mobile.feature.memorize.tracker.WordId + +/** + * Decides when the prayer corrector gives the user the next word. + * + * The behaviour is the one requested for memorization: a wrong word is only *marked* (never + * revealed); if the user doesn't recover within [HintConfig.delayMs], one hint is given (the + * caller reveals and plays the next [HintConfig.wordsPerHint] words). A user who tries the word + * again and gets it wrong again is given it at their next pause, without waiting for the delay. If + * the user still doesn't continue on their own, another hint follows after the same delay, and so + * on; after [HintConfig.wordHintsBeforeLonger] of them each hint gives the rest of the ayah or of + * the line ([Extent.AYAH_OR_LINE]). A pause without a mistake (the user is stuck) is treated the + * same way once the user has been silent long enough. When mistakes aren't hinted, a user who went + * on past one is followed on after the same delay ([Effect.FollowOn]). + * + * The scheduler is a pure state machine: every input carries the current time and every output is + * returned as a list of [Effect]s, so it can be driven by a real clock on the device and by a fake + * one in tests. While a hint is being played, time doesn't count towards the next hint. + */ +class HintScheduler(private val config: HintConfig) { + + sealed interface Effect { + /** Mark the hidden word the user should have said, without revealing it. */ + data class MarkMistake(val word: WordId) : Effect + + /** Remove a mistake mark (the user recovered, or a hint revealed the word). */ + data class ClearMistake(val word: WordId) : Effect + + /** Reveal and play the next [count] words (or more, see [extent]) from the current position. */ + data class GiveHint(val count: Int, val extent: Extent = Extent.WORDS) : Effect + + /** Too many hints in a row without the user continuing: stop hinting until re-anchored. */ + data object GiveUp : Effect + + /** + * The user went on past a mistake that no hint will settle (mistakes aren't hinted, or only + * marked) and didn't come back to it within the delay: follow them on (what they left out is + * marked as skipped). A mark stays until they do. + */ + data object FollowOn : Effect + } + + enum class Extent { + /** The configured number of words. */ + WORDS, + /** The rest of the ayah if it is short, else the rest of the line on the page. */ + AYAH_OR_LINE, + } + + private var armed = false + private var prompting = false + private var atAyahBoundary = false + private var lastProgressMs = 0L + private var speechActive = false + private var speechEndedMs = 0L + private var mistake: WordId? = null + private var mistakeSinceMs = 0L + // how many times the user has tried the word of the pending mistake and stopped + private var attempts = 0 + private var consecutiveHints = 0 + // a mistake no hint will settle, and since when (or the user's last try at it) + private var unsettled: WordId? = null + private var unsettledSinceMs = 0L + + val isArmed: Boolean get() = armed + + /** + * Starts (or restarts) hinting. [atAyahBoundary] is true when the user is between ayat: the next + * word starts an ayah, or ends one (see [onWordRecited]). + */ + fun arm(nowMs: Long, atAyahBoundary: Boolean): List { + val effects = clearMistake() + armed = true + prompting = false + unsettled = null + consecutiveHints = 0 + lastProgressMs = nowMs + speechEndedMs = nowMs + this.atAyahBoundary = atAyahBoundary + return effects + } + + /** Stops hinting, e.g. between rak'ahs or when the session pauses. */ + fun disarm(): List { + armed = false + prompting = false + unsettled = null + return clearMistake() + } + + /** + * The user recited a new word correctly. [atAyahBoundary] is true when the next word starts an + * ayah or is its last word: a reciter who stops there has usually finished the ayah (its last + * word may still be on its way through the recognizer). + */ + fun onWordRecited(nowMs: Long, atAyahBoundary: Boolean): List { + lastProgressMs = nowMs + consecutiveHints = 0 + unsettled = null + this.atAyahBoundary = atAyahBoundary + return clearMistake() + } + + /** + * The user repeated words they already said (normal while memorizing): they're still going. After + * a mistake it is them going back to try the word again: its mark goes, and its hint waits. + */ + fun onRepetition(nowMs: Long): List { + lastProgressMs = nowMs + if (unsettled != null) unsettledSinceMs = nowMs + return clearMistake() + } + + /** The user said something other than [expected]. */ + fun onMistake(nowMs: Long, expected: WordId): List { + if (!armed) return emptyList() + if (!config.onMistakes || !config.hintAfterMistake) { + // no hint will give it + if (unsettled != expected) { + unsettled = expected + unsettledSinceMs = nowMs + } + if (!config.onMistakes) return emptyList() + } + if (mistake == expected) return emptyList() + val effects = clearMistake().toMutableList() + mistake = expected + mistakeSinceMs = nowMs + // recognized only after the user stopped: that attempt is over already + attempts = if (speechActive) 0 else 1 + effects += Effect.MarkMistake(expected) + return effects + } + + fun onSpeechActivity(nowMs: Long, active: Boolean) { + if (speechActive && !active) { + speechEndedMs = nowMs + if (mistake != null) attempts++ + } + speechActive = active + } + + /** + * A hint started playing; the delay is suspended until [onHintFinished]. The hint gives the word a + * pending mistake was about, so the mistake is settled (its mark was cleared with the reveal). + */ + fun onHintStarted() { + prompting = true + mistake = null + unsettled = null + } + + /** The hint finished playing (or there was no audio to play). The delay restarts now. */ + fun onHintFinished(nowMs: Long) { + prompting = false + lastProgressMs = nowMs + speechEndedMs = maxOf(speechEndedMs, nowMs) + } + + /** The time at which [onTick] will next do something, or null if nothing is pending. */ + fun nextDeadlineMs(): Long? { + if (!armed || prompting) return null + return listOfNotNull(hintDeadlineMs(), followOnDeadlineMs()).minOrNull() + } + + private fun followOnDeadlineMs(): Long? = if (unsettled != null) unsettledSinceMs + config.delayMs else null + + private fun hintDeadlineMs(): Long? { + if (mistake != null) { + // the mistake stays marked until the user recovers, without a hint + if (!config.hintAfterMistake) return null + val due = mistakeSinceMs + config.delayMs + val afterDelay = when { + !config.mistakesWaitForPause -> due + speechActive -> null + else -> maxOf(due, speechEndedMs + minSilenceMs()) + } + // wrong again: give the word at this pause, once the recognizer has had time to catch up + val repeated = if (attempts >= config.mistakeAttemptsBeforeHint && !speechActive) { + speechEndedMs + minSilenceMs() + } else { + null + } + return listOfNotNull(afterDelay, repeated).minOrNull() + } + if (!config.onPauses || speechActive) return null + val delay = if (atAyahBoundary) config.ayahBoundaryDelayMs ?: return null else config.delayMs + return maxOf(lastProgressMs + delay, speechEndedMs + minSilenceMs()) + } + + fun onTick(nowMs: Long): List { + val deadline = nextDeadlineMs() ?: return emptyList() + if (nowMs < deadline) return emptyList() + + val followOn = followOnDeadlineMs() + if (followOn != null && nowMs >= followOn) { + unsettled = null + return listOf(Effect.FollowOn) + } + if (consecutiveHints >= config.maxConsecutiveHints) { + armed = false + return clearMistake() + Effect.GiveUp + } + consecutiveHints++ + prompting = true + // the hint gives the word the user went on past + unsettled = null + val extent = if (consecutiveHints > config.wordHintsBeforeLonger) Extent.AYAH_OR_LINE else Extent.WORDS + return clearMistake() + Effect.GiveHint(config.wordsPerHint, extent) + } + + // Long madd (up to 6 counts) is silence-free but produces no new words, and the recognizer only + // hears the end of a word up to a second after it was said, so a pause only counts once the user + // has actually been silent for a while. + private fun minSilenceMs(): Long = minOf(2_000L, config.delayMs / 2) + + private fun clearMistake(): List { + val pending = mistake ?: return emptyList() + mistake = null + attempts = 0 + return listOf(Effect.ClearMistake(pending)) + } +} + +data class HintConfig( + val delayMs: Long = 4_000L, + val wordsPerHint: Int = 1, + /** Whether mistakes are followed (marked, see [hintAfterMistake]). */ + val onMistakes: Boolean = true, + /** Whether a mistake is followed by a hint after [delayMs]; if not, it is only marked. */ + val hintAfterMistake: Boolean = true, + val onPauses: Boolean = true, + /** + * How long a pause between ayat (before an ayah's first word or on its last) must last to count + * as being stuck, or null if it never does. In salah such a pause is often ruku, which the takbir + * then confirms. + */ + val ayahBoundaryDelayMs: Long? = delayMs, + /** + * Whether a mistake is only hinted once the reciter pauses. In salah the hint is spoken: a reciter + * who carries on fluently has more often been misheard than mistaken, and is corrected at their + * next pause otherwise. + */ + val mistakesWaitForPause: Boolean = false, + val maxConsecutiveHints: Int = 10, + /** Wrong attempts at the same word after which it is given at the user's next pause. */ + val mistakeAttemptsBeforeHint: Int = 2, + /** Hints of [wordsPerHint] words in a row after which hints give the rest of the ayah or line. */ + val wordHintsBeforeLonger: Int = 3, +) diff --git a/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/salah/SalahFlow.kt b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/salah/SalahFlow.kt new file mode 100644 index 0000000000..08b8e6a5d9 --- /dev/null +++ b/feature/memorize/tracker/src/main/kotlin/com/quran/mobile/feature/memorize/tracker/salah/SalahFlow.kt @@ -0,0 +1,151 @@ +package com.quran.mobile.feature.memorize.tracker.salah + +import com.quran.mobile.feature.memorize.tracker.RecitationTracker +import com.quran.mobile.feature.memorize.tracker.TimedPhoneme +import com.quran.mobile.feature.memorize.tracker.TrackerConfig +import com.quran.mobile.feature.memorize.tracker.TrackerEvent + +/** + * Follows a passage recited during salah. Besides the passage the person says Al-Fatiha in every + * rak'ah and the phrases of the prayer (takbir, tasmi', tahmid, tasbeeh, tasleem...), and pauses + * for ruku and sujud. None of that may be treated as a mistake, and the passage continues in the + * next rak'ah from where it stopped. + * + * Two trackers listen to the same phonemes: one for the passage (with the prayer phrases as known + * non-target speech) and one for Al-Fatiha. While Al-Fatiha is being recited, whatever the passage + * tracker made of it is discarded. + */ +class SalahFlow( + passageWords: List, + private val fatihaWords: List, + phrases: List>, + private val config: TrackerConfig = TrackerConfig(), + /** Where the passage may start (see [RecitationTracker]): e.g. the pages around the one on screen. */ + startWindow: Int = 0, + /** Where the user is expected to start (e.g. the page on screen), within [startWindow]. */ + startIndex: Int = 0, + /** Which ayah each passage word is in (see [RecitationTracker]); empty when not known. */ + passageAyahs: List = emptyList(), + /** The same for Al-Fatiha's words. */ + private val fatihaAyahs: List = emptyList(), +) { + enum class Phase { + /** Before the passage starts in this rak'ah (opening takbir, istiftah, Al-Fatiha...). */ + AWAITING, + /** Reciting Al-Fatiha. */ + FATIHA, + /** Reciting the passage: the only phase in which the corrector may help. */ + PASSAGE, + /** After the passage in this rak'ah: ruku, sujud, tashahhud... until the next Al-Fatiha. */ + BETWEEN_RAKAHS, + } + + val passage = RecitationTracker(passageWords, config, startIndex, phrases, startWindow, passageAyahs) + private var fatiha = newFatihaTracker() + // this rak'ah's Al-Fatiha is over: what follows should be the passage + private var afterFatiha = false + // phonemes heard since the last word of Al-Fatiha: while it is recited, the passage's start isn't + // looked for (in a few pages of Quran, some of its words match nearly anything) + private var sinceFatiha = FATIHA_QUIET_PHONEMES + + var phase: Phase = Phase.AWAITING + private set(value) { + if (value != field) trace?.invoke("phase $field -> $value") + field = value + } + + /** Diagnostics (see [RecitationTracker.trace]). */ + var trace: ((String) -> Unit)? = null + set(value) { + field = value + passage.trace = value + } + + /** Feeds the phonemes to both trackers; returns the passage's events that matter. */ + fun feed(phonemes: List): List { + val fatihaEvents = fatiha.feed(phonemes) + val inFatiha = fatihaEvents.any { it is TrackerEvent.WordRecited } + if (inFatiha) trace?.invoke("al-fatiha word ${fatiha.cursor}/${fatihaWords.size}") + sinceFatiha = if (inFatiha) 0 else minOf(sinceFatiha + phonemes.size, FATIHA_QUIET_PHONEMES) + if (!passage.anchored && sinceFatiha < FATIHA_QUIET_PHONEMES) { + phase = Phase.FATIHA + passage.discardPending() + if (fatiha.isDone) { + fatiha = newFatihaTracker() + phase = Phase.AWAITING + afterFatiha = true + } + return emptyList() + } + val passageEvents = passage.feed(phonemes) + + val passageProgress = passageEvents.any { it is TrackerEvent.WordRecited } + + if (inFatiha && !passageProgress) { + phase = Phase.FATIHA + passage.discardPending() + if (fatiha.isDone) { + // ready for the next rak'ah; the passage continues where it stopped + fatiha = newFatihaTracker() + phase = Phase.AWAITING + afterFatiha = true + } + return emptyList() + } + + if (passageProgress) { + phase = Phase.PASSAGE + afterFatiha = false + // the user moved on to the passage: Al-Fatiha starts from its beginning next time + if (fatiha.cursor > 0) fatiha = newFatihaTracker() + } else if (phase == Phase.PASSAGE && passageEvents.any { it.endsPassage() }) { + phase = Phase.BETWEEN_RAKAHS + } + if (passageEvents.any { it.endsPassage() }) afterFatiha = false + + if (phase != Phase.PASSAGE) { + // outside the passage nothing is a mistake, except a passage recited after Al-Fatiha that + // isn't where the user said it would be + return passageEvents.filter { + it !is TrackerEvent.Mistake || (afterFatiha && it.kind == TrackerEvent.Mistake.Kind.ELSEWHERE) + } + } + return passageEvents + } + + /** More of the passage (the next sura); the session doesn't end with the current one. */ + fun extendPassage(more: List, moreAyahs: List = emptyList()) = passage.extend(more, moreAyahs) + + /** The user stopped making sound (e.g. after the takbir, for ruku). */ + fun onPause(): List { + val events = passage.onPause() + if (phase == Phase.PASSAGE && events.any { it.endsPassage() }) { + phase = Phase.BETWEEN_RAKAHS + } + if (events.any { it.endsPassage() }) afterFatiha = false + return events + } + + // Any phrase of ruku or sujud means the passage of this rak'ah is over, even if the takbir before + // it wasn't recognized. + private fun TrackerEvent.endsPassage() = this is TrackerEvent.NonTarget && kind in ENDS_PASSAGE + + /** Whether the corrector may help now. */ + val isReadingPassage: Boolean get() = phase == Phase.PASSAGE + + private fun newFatihaTracker() = RecitationTracker(fatihaWords, config, ayahs = fatihaAyahs) + + companion object { + const val TAKBIR = "takbir" + /** Phonemes after Al-Fatiha's last recognized word before the passage's start is looked for. */ + private const val FATIHA_QUIET_PHONEMES = 12 + + /** Phrases said only once the passage of a rak'ah is over. */ + val ENDS_PASSAGE = setOf(TAKBIR, "tasmi", "tahmid", "ruku", "sujud", "tasleem") + + /** The phrase kinds (from the lexicon) said during salah that aren't part of the passage. */ + val PRAYER_PHRASES = setOf( + "takbir", "tasmi", "tahmid", "ruku", "sujud", "ameen", "isti'adha", "basmala", "istiftah", "tasleem", + ) + } +} diff --git a/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/PhonemeNormalizerTest.kt b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/PhonemeNormalizerTest.kt new file mode 100644 index 0000000000..5cdbce0365 --- /dev/null +++ b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/PhonemeNormalizerTest.kt @@ -0,0 +1,31 @@ +package com.quran.mobile.feature.memorize.tracker + +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +class PhonemeNormalizerTest { + + @Test + fun `madd lengths, gemination and ghunna collapse`() { + // ٱلرَّحِيمِ as recited: doubled raa, long yaa madd + assertThat(PhonemeNormalizer.normalize("ررَحِۦۦۦۦم")).isEqualTo("رَحِيم") + // ghunna on a doubled meem + assertThat(PhonemeNormalizer.normalize("ممممُبِۦۦۦۦن")).isEqualTo("مُبِين") + } + + @Test + fun `tajweed markers map to their letters or are dropped`() { + assertThat(PhonemeNormalizer.normalize("ءَحَدڇ")).isEqualTo("ءَحَد") // qalqala + assertThat(PhonemeNormalizer.normalize("مِںكُم")).isEqualTo("مِنكُم") // ikhfa + } + + @Test + fun `spaces are ignored`() { + assertThat(PhonemeNormalizer.normalize("قُل هُوَ")).isEqualTo("قُلهُوَ") + } + + @Test + fun `lenient mode drops short vowels`() { + assertThat(PhonemeNormalizer.normalize("بِسمِ للَااهِ", keepShortVowels = false)).isEqualTo("بسملاه") + } +} diff --git a/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTrackerAyatTest.kt b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTrackerAyatTest.kt new file mode 100644 index 0000000000..17b0dbd7b5 --- /dev/null +++ b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTrackerAyatTest.kt @@ -0,0 +1,153 @@ +package com.quran.mobile.feature.memorize.tracker + +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +/** + * Ayat left out, restarts and ayat that open alike (as 2:149 and 2:150, which share their first 8 + * words), with the words' ayat known. Latin stand-ins for phonemes keep the scenarios readable. + */ +class RecitationTrackerAyatTest { + + // ayah 1; ayat 2 and 3 open alike (7 words); ayah 4 + private val ayat = listOf( + listOf("faqadkaf", "arnabiha", "tamaman"), + listOf("wamin", "haythu", "kharajta", "fawalli", "wajhaka", "shatra", "masjidi", "wainnahu", "lalhaqqu", "minrabbik"), + listOf("wamin", "haythu", "kharajta", "fawalli", "wajhaka", "shatra", "masjidi", "wahaythu", "makuntum", "fawallu"), + listOf("liallayakuna", "linnasi", "alaykum", "hujjatun"), + ) + private val words = ayat.flatten() + private val ayahs = ayat.flatMapIndexed { a, ws -> List(ws.size) { a + 1 } } + private fun index(ayah: Int, word: Int) = ayat.take(ayah - 1).sumOf { it.size } + word - 1 + + private val memorize = TrackerConfig(skipAyat = false, maxMissedWords = 2) + private val strict = TrackerConfig(skipAyat = false, maxMissedWords = 0) + + private var time = 0L + + private fun RecitationTracker.say(vararg text: String): List = + text.flatMap { word -> feed(word.map { TimedPhoneme(it, (time++) * 80) }) } + + private fun RecitationTracker.sayAyah(ayah: Int, from: Int = 1, to: Int = ayat[ayah - 1].size, skip: Set = emptySet()) = + say(*(from..to).filter { it !in skip }.map { ayat[ayah - 1][it - 1] }.toTypedArray()) + + private fun List.missed() = filterIsInstance().map { it.index } + private fun List.mistakes() = filterIsInstance().map { it.index } + + @Test + fun `an ayah left out is held at, not stepped over`() { + val tracker = RecitationTracker(words, memorize, ayahs = ayahs) + + // ayah 1, then ayah 3 (ayah 2 left out; it opens like ayah 3), then ayah 4 + val events = tracker.sayAyah(1) + tracker.sayAyah(3) + tracker.sayAyah(4) + + // the opening the two share counts for ayah 2; where they differ, it holds + assertThat(tracker.cursor).isEqualTo(index(2, 8)) + assertThat(events.missed()).isEmpty() + assertThat(events.mistakes()).containsExactly(index(2, 8)) + } + + @Test + fun `once the user goes back to the ayah left out, it goes on`() { + val tracker = RecitationTracker(words, memorize, ayahs = ayahs) + tracker.sayAyah(1) + tracker.sayAyah(3) + + val events = tracker.sayAyah(2, from = 8) + tracker.sayAyah(3) + tracker.sayAyah(4) + + assertThat(events.missed()).isEmpty() + assertThat(tracker.isDone).isTrue() + } + + @Test + fun `where ayat may be left out, as in salah, the session follows the reciter past one`() { + val tracker = RecitationTracker(words, ayahs = ayahs) + + val events = tracker.sayAyah(1) + tracker.sayAyah(3) + tracker.sayAyah(4) + + assertThat(events.missed()).isNotEmpty() + assertThat(tracker.isDone).isTrue() + } + + @Test + fun `starting the ayah again from far back is a repetition, not a jump to the ayah alike`() { + listOf(TrackerConfig(), memorize).forEach { config -> + val tracker = RecitationTracker(words, config, startIndex = index(2, 1), ayahs = ayahs) + + val events = tracker.sayAyah(2, to = 9) + tracker.sayAyah(2, to = 7) + + assertThat(tracker.cursor).isEqualTo(index(2, 10)) + assertThat(events.missed()).isEmpty() + assertThat(events.mistakes()).isEmpty() + assertThat(events.filterIsInstance()).isNotEmpty() + } + } + + @Test + fun `a word the recognizer didn't hear at the end of an ayah passes, unless every word must be heard`() { + val loose = RecitationTracker(words, memorize, startIndex = index(3, 1), ayahs = ayahs) + val looseEvents = loose.sayAyah(3, skip = setOf(10)) + loose.sayAyah(4) + assertThat(looseEvents.missed()).containsExactly(index(3, 10)) + assertThat(loose.isDone).isTrue() + + val held = RecitationTracker(words, strict, startIndex = index(3, 1), ayahs = ayahs) + val heldEvents = held.sayAyah(3, skip = setOf(10)) + held.sayAyah(4) + assertThat(heldEvents.missed()).isEmpty() + assertThat(held.cursor).isEqualTo(index(3, 10)) + } + + @Test + fun `an ayah of one word is never left out`() { + val short = listOf(listOf("qadnara", "taqalluba", "wajhika"), listOf("mudhammatan"), listOf("fabiayyi", "alai", "rabbikuma")) + val tracker = RecitationTracker(short.flatten(), memorize, ayahs = listOf(1, 1, 1, 2, 3, 3, 3)) + + val events = tracker.say("qadnara", "taqalluba", "wajhika", "fabiayyi", "alai", "rabbikuma") + + assertThat(events.missed()).isEmpty() + assertThat(tracker.cursor).isEqualTo(3) + } + + @Test + fun `a start alike in two places waits for the words that tell them apart`() { + // the user may start anywhere in ayat 1 to 4 and is expected at ayah 1; they start at ayah 3 + val tracker = RecitationTracker(words, memorize, startIndex = 0, startWindow = words.size, ayahs = ayahs) + + val events = tracker.sayAyah(3) + tracker.sayAyah(4) + + assertThat(events.mistakes()).isEmpty() + assertThat(events.missed()).isEmpty() + assertThat(events.filterIsInstance().map { it.index }.first()).isEqualTo(index(3, 1)) + assertThat(tracker.isDone).isTrue() + } + + @Test + fun `a start dropped after a misheard word stays where the user is expected, not back at the page`() { + // expected at ayah 3 (the page on screen); the user starts at ayah 1, then a word is misheard + val tracker = RecitationTracker(words, memorize, startIndex = index(3, 1), startWindow = words.size, ayahs = ayahs) + tracker.sayAyah(1) + assertThat(tracker.anchored).isTrue() + tracker.say("zzzzzzzzzzzz") + assertThat(tracker.anchored).isFalse() + + // a hint before a new start gives the word where they were, not the first word on screen + tracker.markHinted(1) + + assertThat(tracker.cursor).isEqualTo(index(2, 2)) + } + + @Test + fun `a start alike in two places is settled at the nearer one when the user stops`() { + val tracker = RecitationTracker(words, memorize, startIndex = 0, startWindow = words.size, ayahs = ayahs) + + assertThat(tracker.sayAyah(2, to = 5)).isEmpty() + assertThat(tracker.startPending).isTrue() + + val events = tracker.onPause() + + assertThat(tracker.startPending).isFalse() + assertThat(tracker.anchored).isTrue() + assertThat(events.filterIsInstance().map { it.index }) + .containsExactlyElementsIn(index(2, 1)..index(2, 5)).inOrder() + assertThat(tracker.cursor).isEqualTo(index(2, 6)) + } +} diff --git a/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTrackerGoldenTest.kt b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTrackerGoldenTest.kt new file mode 100644 index 0000000000..c36285e1c2 --- /dev/null +++ b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTrackerGoldenTest.kt @@ -0,0 +1,91 @@ +package com.quran.mobile.feature.memorize.tracker + +import com.google.common.truth.Truth.assertWithMessage +import org.junit.Test +import java.io.File + +/** + * Replays fixtures exported from the reference implementation (tools: tracker/export_golden.py) + * and checks that this port produces exactly the same events. Fixtures cover synthetic edge cases + * and phoneme streams the speech model produced for real recitations. + */ +class RecitationTrackerGoldenTest { + + @Test + fun `matches the reference implementation on every fixture`() { + val fixtures = goldenDirectory().listFiles { file -> file.extension == "tsv" }!!.sortedBy { it.name } + assertWithMessage("no fixtures found").that(fixtures).isNotEmpty() + fixtures.forEach { replay(it) } + } + + private fun replay(file: File) { + val words = mutableListOf() + val phrases = mutableListOf>() + val actions = mutableListOf() + val expected = mutableMapOf>() + var ayahs = emptyList() + var config = TrackerConfig() + file.readLines().filter { it.isNotEmpty() }.forEach { line -> + val parts = line.split('\t') + when (parts[0]) { + "W" -> words += parts[1] + "P" -> phrases += parts[1] to parts[2] + "F" -> actions += Action.Feed(parts[1].split(';').map { + val (symbol, ms) = it.split(',') + TimedPhoneme(symbol.single(), ms.toLong()) + }) + "H" -> actions += Action.Hint(parts[1].toInt()) + "S" -> actions += Action.Pause + "A" -> ayahs = parts[1].split(',').map { it.toInt() } + "C" -> parts[1].split(';').forEach { + val (key, value) = it.split('=') + config = when (key) { + "skip_ayat" -> config.copy(skipAyat = value == "1") + "max_missed_words" -> config.copy(maxMissedWords = value.toInt()) + else -> error("unknown setting $key in ${file.name}") + } + } + "E" -> expected.getOrPut(parts[1].toInt()) { mutableListOf() } += parts.drop(2).joinToString("\t") + } + } + + val tracker = RecitationTracker(words, config, phrases = phrases, ayahs = ayahs) + actions.forEachIndexed { index, action -> + when (action) { + is Action.Hint -> tracker.markHinted(action.count) + Action.Pause -> { + val actual = tracker.onPause().map { it.describe() } + assertWithMessage("${file.name}, pause #$index") + .that(actual) + .containsExactlyElementsIn(expected[index].orEmpty()) + .inOrder() + } + is Action.Feed -> { + val actual = tracker.feed(action.phonemes).map { it.describe() } + assertWithMessage("${file.name}, feed #$index") + .that(actual) + .containsExactlyElementsIn(expected[index].orEmpty()) + .inOrder() + } + } + } + } + + private fun TrackerEvent.describe(): String = when (this) { + is TrackerEvent.WordRecited -> + "word\t$index\t$timeMs\t${if (fromContext) "ctx" else if (recovered) "rec" else ""}" + is TrackerEvent.WordMissed -> "missed\t$index\t$timeMs\t" + is TrackerEvent.Mistake -> "mistake\t$index\t$timeMs\t${kind.name}" + is TrackerEvent.Repetition -> "repetition\t$index\t$timeMs\t$lastIndex" + is TrackerEvent.NonTarget -> "nontarget\t$index\t$timeMs\t$kind" + } + + private sealed interface Action { + data class Feed(val phonemes: List) : Action + data class Hint(val count: Int) : Action + data object Pause : Action + } + + private fun goldenDirectory(): File = + File(javaClass.classLoader!!.getResource("golden")!!.toURI()) +} diff --git a/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTrackerLiveStartTest.kt b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTrackerLiveStartTest.kt new file mode 100644 index 0000000000..cace3470b5 --- /dev/null +++ b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTrackerLiveStartTest.kt @@ -0,0 +1,88 @@ +package com.quran.mobile.feature.memorize.tracker + +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import java.io.File + +/** + * Starts the phone heard (tools: the lab's tracker/export_live_start.py), replayed through the start + * search, which the reference implementation doesn't have: what the speech model heard on the Mi 11, + * with its pauses, in a session that may start anywhere in a window of words. + */ +class RecitationTrackerLiveStartTest { + + // 95:1-114:6, expected at 100:10 (word 297): 102:1 is word 342, 102:2:2 (زرتم) 345, 102:3 347-349, + // 102:4 350-353, 102:5 354-358. In each, the start is found on 102:1-2, then زرتم is misheard; كلا and + // سوف are often misheard too, so three clear words in a row don't come again. + + @Test + fun `a start dropped after a misheard word is taken up again when the user goes on from it`() { + // Husary recites 102:1-3 then 102:5, leaving 102:4 out + val (tracker, events) = replay("live_mi11_102_dropped_start") + val recited = events.filterIsInstance().map { it.index } + val mistakes = events.filterIsInstance() + + // 102:1 is where the user started; the misheard زرتم passes, and 102:3 is followed + assertThat(recited).containsAtLeast(342, 343, 344, 345, 346, 347, 348, 349) + // nothing marked as recited elsewhere: the user was where the start had been found + assertThat(mistakes.filter { it.kind == TrackerEvent.Mistake.Kind.ELSEWHERE }).isEmpty() + // 102:4 left out: the session holds at its first word (the hint gives it), 102:5 isn't taken as recited + assertThat(recited.filter { it >= 350 }).isEmpty() + assertThat(tracker.cursor).isEqualTo(350) + } + + @Test + fun `a start dropped after a misheard word is followed to the end of a correct recitation`() { + // Husary recites 102:1-5; the session stopped him with hints before he could go on + val (tracker, events) = replay("live_mi11_102_dropped_start_correct") + val recited = events.filterIsInstance().map { it.index } + + assertThat(recited).containsAtLeast(342, 345, 349, 350, 353, 354, 358) + assertThat(tracker.cursor).isEqualTo(359) + } + + private fun replay(name: String): Pair> { + val words = mutableListOf() + val phrases = mutableListOf>() + var ayahs = emptyList() + var config = TrackerConfig() + var start = 0 + var window = 0 + val actions = mutableListOf?>() + fixture(name).readLines().filter { it.isNotEmpty() }.forEach { line -> + val parts = line.split('\t') + when (parts[0]) { + "W" -> words += parts[1] + "P" -> phrases += parts[1] to parts[2] + "A" -> ayahs = parts[1].split(',').map { it.toInt() } + "C" -> parts[1].split(';').forEach { + val (key, value) = it.split('=') + config = when (key) { + "skip_ayat" -> config.copy(skipAyat = value == "1") + "max_missed_words" -> config.copy(maxMissedWords = value.toInt()) + else -> error("unknown setting $key in $name") + } + } + "I" -> parts[1].split(';').forEach { + val (key, value) = it.split('=') + when (key) { + "start" -> start = value.toInt() + "window" -> window = value.toInt() + else -> error("unknown start setting $key in $name") + } + } + "F" -> actions += parts[1].split(';').map { + val (symbol, ms) = it.split(',') + TimedPhoneme(symbol.single(), ms.toLong()) + } + "S" -> actions += null + } + } + val tracker = RecitationTracker(words, config, startIndex = start, phrases = phrases, startWindow = window, ayahs = ayahs) + val events = actions.flatMap { phonemes -> if (phonemes == null) tracker.onPause() else tracker.feed(phonemes) } + return tracker to events + } + + private fun fixture(name: String): File = + File(javaClass.classLoader!!.getResource("live_start/$name.tsv")!!.toURI()) +} diff --git a/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTrackerTest.kt b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTrackerTest.kt new file mode 100644 index 0000000000..63c26ad8b9 --- /dev/null +++ b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/RecitationTrackerTest.kt @@ -0,0 +1,146 @@ +package com.quran.mobile.feature.memorize.tracker + +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +class RecitationTrackerTest { + + // Latin stand-ins for phonemes keep the scenarios readable. + private val ikhlas = listOf("qulhuwa", "llahu", "ahadun", "llahu", "ssamadu") + private val falaq = listOf("qulauzu", "birabbi", "lfalaqi") + private val basmala = "basmala" to "bismillahirrahmanirrahim" + + private var time = 0L + + private fun RecitationTracker.say(text: String): List = + feed(text.map { TimedPhoneme(it, (time++) * 80) }) + + private fun recited(events: List) = + events.filterIsInstance().map { it.index } + + @Test + fun `the passage can grow while the user recites`() { + val tracker = RecitationTracker(ikhlas) + tracker.say("qulhuwallahuahadunallahussamadu") + assertThat(tracker.isDone).isTrue() + + tracker.extend(falaq) + + assertThat(tracker.isDone).isFalse() + assertThat(recited(tracker.say("qulauzubirabbilfalaqi"))).containsExactly(5, 6, 7).inOrder() + assertThat(tracker.isDone).isTrue() + } + + @Test + fun `the basmala between suras is not a mistake once it is a known phrase`() { + val tracker = RecitationTracker(ikhlas, phrases = listOf(basmala)) + tracker.say("qulhuwallahuahadunallahussamadu") + tracker.extend(falaq) + + val events = tracker.say("bismillahirrahmanirrahimqulauzubirabbilfalaqi") + + assertThat(events.filterIsInstance()).isEmpty() + assertThat(recited(events)).containsExactly(5, 6, 7).inOrder() + } + + @Test + fun `phrases added later are recognized`() { + val tracker = RecitationTracker(ikhlas) + tracker.say("qulhuwallahuahadunallahussamadu") + tracker.extend(falaq) + tracker.addPhrases(listOf(basmala, basmala)) + + val events = tracker.say("bismillahirrahmanirrahimqulauzubirabbilfalaqi") + + assertThat(events.filterIsInstance()).isEmpty() + assertThat(recited(events)).containsExactly(5, 6, 7).inOrder() + } + + // two "pages" on screen: Al-Ikhlas then Al-Falaq + private val screen = ikhlas + falaq + + @Test + fun `the user can start anywhere on the pages on screen`() { + val tracker = RecitationTracker(screen + listOf("qulauzu", "birabbi", "nnasi"), startWindow = screen.size) + assertThat(tracker.anchored).isFalse() + + val events = tracker.say("qulauzubirabbilfalaqi") + + assertThat(tracker.anchored).isTrue() + assertThat(recited(events)).containsExactly(5, 6, 7).inOrder() + // the words before the start weren't skipped: the user started there + assertThat(events.filterIsInstance()).isEmpty() + assertThat(events.filterIsInstance()).isEmpty() + } + + @Test + fun `the basmala before the start is fine`() { + val tracker = RecitationTracker(screen, phrases = listOf(basmala), startWindow = screen.size) + + val events = tracker.say("bismillahirrahmanirrahimllahussamaduqulauzu") + + assertThat(events.filterIsInstance()).isEmpty() + assertThat(recited(events)).containsExactly(3, 4, 5).inOrder() + } + + @Test + fun `reciting something that isn't on screen marks the first word`() { + val tracker = RecitationTracker(screen, startWindow = screen.size) + + val events = tracker.say("waddhuhawallayliidhasajamawaddaakarabbukawamaqala") + + assertThat(events).containsExactly(TrackerEvent.Mistake(0, events.single().timeMs, TrackerEvent.Mistake.Kind.ELSEWHERE)) + assertThat(tracker.anchored).isFalse() + + // once the user recites something on screen, that is where they start + val start = tracker.say("qulhuwallahuahadun") + assertThat(tracker.anchored).isTrue() + assertThat(recited(start)).containsExactly(0, 1, 2).inOrder() + } + + @Test + fun `a hint before the start starts at the first word`() { + val tracker = RecitationTracker(screen, startWindow = screen.size) + + tracker.markHinted(1) + + assertThat(tracker.anchored).isTrue() + assertThat(tracker.cursor).isEqualTo(1) + assertThat(recited(tracker.say("llahuahadun"))).containsExactly(1, 2).inOrder() + } + + @Test + fun `two short words that happen to match somewhere aren't a start`() { + val tracker = RecitationTracker(listOf("qulhuwa", "allahu", "ma", "lakum", "min", "ilahin", "ghayruhu"), startWindow = 7) + + tracker.say("malakum") + + assertThat(tracker.anchored).isFalse() + } + + @Test + fun `a phrase that is repeated is placed by the words that follow it`() { + // the same three words twice in the window, followed by different words + val words = listOf("yaqawmi", "budullaha", "malakum", "wailaa", "thamuda", "yaqawmi", "budullaha", "malakum", "minilahin") + val tracker = RecitationTracker(words, startIndex = 3, startWindow = words.size) + + // which of the two isn't known yet + assertThat(recited(tracker.say("yaqawmibudullahamalakum"))).isEmpty() + + assertThat(recited(tracker.say("minilahin"))).containsExactly(5, 6, 7, 8).inOrder() + } + + @Test + fun `a start contradicted right away is looked for again`() { + val words = listOf("qulhuwa", "llahu", "ahadun", "llahu", "ssamadu", "lamyalid", "walamyulad", "walamyakun") + val tracker = RecitationTracker(words, startWindow = words.size) + tracker.say("qulhuwallahuahadun") + assertThat(tracker.anchored).isTrue() + + // not what follows: the start was a guess + val events = tracker.say("wassamaiwattariqi") + + assertThat(tracker.anchored).isFalse() + assertThat(events.filterIsInstance().map { it.kind }).doesNotContain(TrackerEvent.Mistake.Kind.SUBSTITUTION) + } +} diff --git a/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/hint/HintSchedulerTest.kt b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/hint/HintSchedulerTest.kt new file mode 100644 index 0000000000..56e08df148 --- /dev/null +++ b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/hint/HintSchedulerTest.kt @@ -0,0 +1,317 @@ +package com.quran.mobile.feature.memorize.tracker.hint + +import com.google.common.truth.Truth.assertThat +import com.quran.mobile.feature.memorize.tracker.WordId +import com.quran.mobile.feature.memorize.tracker.hint.HintScheduler.Effect +import org.junit.Test + +class HintSchedulerTest { + + private val word = WordId(67, 1, 3) + + @Test + fun `a mistake is marked without revealing anything`() { + val scheduler = armed() + + val effects = scheduler.onMistake(1_000, word) + + assertThat(effects).containsExactly(Effect.MarkMistake(word)) + } + + @Test + fun `one word is hinted after the delay following a mistake`() { + val scheduler = armed() + scheduler.onMistake(1_000, word) + + assertThat(scheduler.onTick(4_999)).isEmpty() + assertThat(scheduler.onTick(5_000)).containsExactly(Effect.ClearMistake(word), Effect.GiveHint(1)) + } + + @Test + fun `hints escalate one word at a time until the user continues`() { + val scheduler = armed() + scheduler.onMistake(1_000, word) + assertThat(scheduler.onTick(5_000)).contains(Effect.GiveHint(1)) + + // no further hint while the first one is playing + assertThat(scheduler.onTick(20_000)).isEmpty() + scheduler.onHintFinished(21_000) + + assertThat(scheduler.onTick(24_999)).isEmpty() + assertThat(scheduler.onTick(25_000)).containsExactly(Effect.GiveHint(1)) + scheduler.onHintFinished(26_000) + + // the user continues on their own: the escalation stops + assertThat(scheduler.onWordRecited(27_000, atAyahBoundary = false)).isEmpty() + assertThat(scheduler.onTick(30_999)).isEmpty() + } + + @Test + fun `recovering from a mistake clears the mark and cancels the hint`() { + val scheduler = armed() + scheduler.onMistake(1_000, word) + + assertThat(scheduler.onWordRecited(2_000, atAyahBoundary = false)).containsExactly(Effect.ClearMistake(word)) + assertThat(scheduler.nextDeadlineMs()).isEqualTo(6_000) + } + + @Test + fun `a pause only counts once the user has been silent`() { + val scheduler = armed() + scheduler.onWordRecited(1_000, atAyahBoundary = false) + scheduler.onSpeechActivity(1_500, active = true) + + // still making sound (e.g. a long madd): no hint even after the delay + assertThat(scheduler.onTick(10_000)).isEmpty() + + // the recognizer may still be about to hear the end of the last word + scheduler.onSpeechActivity(10_000, active = false) + assertThat(scheduler.nextDeadlineMs()).isEqualTo(12_000) + assertThat(scheduler.onTick(12_000)).containsExactly(Effect.GiveHint(1)) + } + + @Test + fun `a hint settles the mistake it was given for`() { + val scheduler = armed() + scheduler.onMistake(1_000, word) + + // e.g. the user asked for the word before the delay was over + scheduler.onHintStarted() + scheduler.onHintFinished(2_000) + + // no second hint for the same mistake; only the usual wait for the user to go on + assertThat(scheduler.onTick(5_000)).isEmpty() + assertThat(scheduler.nextDeadlineMs()).isEqualTo(6_000) + } + + @Test + fun `repetition keeps the user from being treated as stuck`() { + val scheduler = armed() + scheduler.onRepetition(3_000) + + assertThat(scheduler.nextDeadlineMs()).isEqualTo(7_000) + } + + @Test + fun `going back to repeat after a mistake takes its mark down and waits`() { + val scheduler = armed() + scheduler.onMistake(1_000, word) + + assertThat(scheduler.onRepetition(2_000)).containsExactly(Effect.ClearMistake(word)) + // the hint for the mistake no longer comes 4 s after it + assertThat(scheduler.onTick(5_000)).isEmpty() + } + + @Test + fun `pauses at the end of an ayah are ignored when configured`() { + val scheduler = HintScheduler(HintConfig(ayahBoundaryDelayMs = null)) + scheduler.arm(0, atAyahBoundary = false) + scheduler.onWordRecited(1_000, atAyahBoundary = true) + + assertThat(scheduler.nextDeadlineMs()).isNull() + + // a mistake at the start of the next ayah is still hinted + scheduler.onMistake(30_000, WordId(67, 2, 1)) + assertThat(scheduler.nextDeadlineMs()).isEqualTo(34_000) + } + + @Test + fun `pauses at the end of an ayah can take longer to count`() { + val scheduler = HintScheduler(HintConfig(delayMs = 4_000, ayahBoundaryDelayMs = 8_000)) + scheduler.arm(0, atAyahBoundary = false) + scheduler.onWordRecited(1_000, atAyahBoundary = true) + + assertThat(scheduler.nextDeadlineMs()).isEqualTo(9_000) + scheduler.onWordRecited(10_000, atAyahBoundary = false) + assertThat(scheduler.nextDeadlineMs()).isEqualTo(14_000) + } + + @Test + fun `a mistake can wait for the reciter to pause (salah)`() { + val scheduler = HintScheduler(HintConfig(delayMs = 4_000, mistakesWaitForPause = true)) + scheduler.arm(0, atAyahBoundary = false) + scheduler.onSpeechActivity(500, active = true) + scheduler.onMistake(1_000, word) + + // still reciting fluently: no hint, however long it takes + assertThat(scheduler.onTick(30_000)).isEmpty() + + scheduler.onSpeechActivity(30_000, active = false) + assertThat(scheduler.nextDeadlineMs()).isEqualTo(32_000) + assertThat(scheduler.onTick(32_000)).containsExactly(Effect.ClearMistake(word), Effect.GiveHint(1)) + } + + @Test + fun `pause hints can be turned off while mistake hints stay on`() { + val scheduler = HintScheduler(HintConfig(onPauses = false)) + scheduler.arm(0, atAyahBoundary = false) + + assertThat(scheduler.nextDeadlineMs()).isNull() + scheduler.onMistake(1_000, word) + assertThat(scheduler.nextDeadlineMs()).isEqualTo(5_000) + } + + @Test + fun `with mistake hints off a mistake isn't marked and the user is followed on after the delay`() { + val scheduler = HintScheduler(HintConfig(onMistakes = false, onPauses = false)) + scheduler.arm(0, atAyahBoundary = false) + + assertThat(scheduler.onMistake(1_000, word)).isEmpty() + assertThat(scheduler.onTick(4_999)).isEmpty() + assertThat(scheduler.onTick(5_000)).containsExactly(Effect.FollowOn) + // once + assertThat(scheduler.onTick(100_000)).isEmpty() + assertThat(scheduler.isArmed).isTrue() + } + + @Test + fun `with mistake hints off going back to the word waits again, and reciting it cancels`() { + val scheduler = HintScheduler(HintConfig(onMistakes = false, onPauses = false)) + scheduler.arm(0, atAyahBoundary = false) + scheduler.onMistake(1_000, word) + + scheduler.onRepetition(3_000) + assertThat(scheduler.onTick(5_000)).isEmpty() + assertThat(scheduler.nextDeadlineMs()).isEqualTo(7_000) + + scheduler.onWordRecited(6_000, atAyahBoundary = false) + assertThat(scheduler.nextDeadlineMs()).isNull() + } + + @Test + fun `with mistake hints off pause hints still come`() { + val scheduler = HintScheduler(HintConfig(onMistakes = false)) + scheduler.arm(0, atAyahBoundary = false) + scheduler.onMistake(1_000, word) + + assertThat(scheduler.onTick(4_000)).containsExactly(Effect.GiveHint(1)) + // the hint gave the word: nothing is left to follow the user past + scheduler.onHintFinished(5_000) + assertThat(scheduler.onTick(8_999)).isEmpty() + assertThat(scheduler.onTick(9_000)).containsExactly(Effect.GiveHint(1)) + } + + @Test + fun `words per hint is configurable`() { + val scheduler = HintScheduler(HintConfig(wordsPerHint = 3)) + scheduler.arm(0, atAyahBoundary = false) + + assertThat(scheduler.onTick(4_000)).containsExactly(Effect.GiveHint(3)) + } + + @Test + fun `hinting gives up after too many hints in a row`() { + val scheduler = HintScheduler(HintConfig(maxConsecutiveHints = 2)) + scheduler.arm(0, atAyahBoundary = false) + + var now = 0L + repeat(2) { + now += 4_000 + assertThat(scheduler.onTick(now)).containsExactly(Effect.GiveHint(1)) + scheduler.onHintFinished(now) + } + now += 4_000 + assertThat(scheduler.onTick(now)).containsExactly(Effect.GiveUp) + assertThat(scheduler.isArmed).isFalse() + } + + @Test + fun `disarming clears a pending mistake and stops hints`() { + val scheduler = armed() + scheduler.onMistake(1_000, word) + + assertThat(scheduler.disarm()).containsExactly(Effect.ClearMistake(word)) + assertThat(scheduler.onTick(100_000)).isEmpty() + } + + @Test + fun `nothing happens before arming`() { + val scheduler = HintScheduler(HintConfig()) + + assertThat(scheduler.onMistake(0, word)).isEmpty() + assertThat(scheduler.onTick(100_000)).isEmpty() + } + + @Test + fun `a word gotten wrong twice is given at the next pause without waiting for the delay`() { + val scheduler = HintScheduler(HintConfig(delayMs = 10_000)) + scheduler.arm(0, atAyahBoundary = false) + scheduler.onSpeechActivity(500, active = true) + scheduler.onMistake(1_000, word) + // first attempt over; the user tries again and gets it wrong again + scheduler.onSpeechActivity(1_500, active = false) + scheduler.onSpeechActivity(2_500, active = true) + assertThat(scheduler.onTick(3_000)).isEmpty() + scheduler.onSpeechActivity(4_000, active = false) + + // given once the recognizer has had time to catch up, long before the 10 s delay + assertThat(scheduler.nextDeadlineMs()).isEqualTo(6_000) + assertThat(scheduler.onTick(6_000)).containsExactly(Effect.ClearMistake(word), Effect.GiveHint(1)) + } + + @Test + fun `a mistake recognized after the user stopped counts that attempt`() { + val scheduler = HintScheduler(HintConfig(delayMs = 10_000)) + scheduler.arm(0, atAyahBoundary = false) + scheduler.onSpeechActivity(500, active = true) + scheduler.onSpeechActivity(1_000, active = false) + scheduler.onMistake(1_400, word) + assertThat(scheduler.nextDeadlineMs()).isEqualTo(11_400) + + scheduler.onSpeechActivity(2_000, active = true) + scheduler.onSpeechActivity(3_000, active = false) + assertThat(scheduler.nextDeadlineMs()).isEqualTo(5_000) + } + + @Test + fun `a second attempt that turns out right gives no hint`() { + val scheduler = HintScheduler(HintConfig(delayMs = 10_000)) + scheduler.arm(0, atAyahBoundary = false) + scheduler.onSpeechActivity(500, active = true) + scheduler.onMistake(1_000, word) + scheduler.onSpeechActivity(1_500, active = false) + scheduler.onSpeechActivity(2_500, active = true) + scheduler.onSpeechActivity(4_000, active = false) + + // the word arrives from the recognizer before the pause is long enough + assertThat(scheduler.onWordRecited(5_000, atAyahBoundary = false)).containsExactly(Effect.ClearMistake(word)) + assertThat(scheduler.onTick(6_000)).isEmpty() + } + + @Test + fun `after three single word hints in a row the rest of the ayah or line is given`() { + val scheduler = armed() + var now = 0L + repeat(3) { + now += 4_000 + assertThat(scheduler.onTick(now)).containsExactly(Effect.GiveHint(1, HintScheduler.Extent.WORDS)) + scheduler.onHintFinished(now) + } + now += 4_000 + assertThat(scheduler.onTick(now)).containsExactly(Effect.GiveHint(1, HintScheduler.Extent.AYAH_OR_LINE)) + scheduler.onHintFinished(now) + + // reciting on their own starts over with single words + scheduler.onWordRecited(now + 1_000, atAyahBoundary = false) + assertThat(scheduler.onTick(now + 5_000)).containsExactly(Effect.GiveHint(1, HintScheduler.Extent.WORDS)) + } + + @Test + fun `a mistake can be only marked, with no hint after it`() { + val scheduler = HintScheduler(HintConfig(delayMs = 4_000, hintAfterMistake = false, onPauses = false)) + scheduler.arm(0, atAyahBoundary = false) + + assertThat(scheduler.onMistake(1_000, word)).containsExactly(Effect.MarkMistake(word)) + // no hint: after the delay the user may be followed on, and the mark stays + assertThat(scheduler.onTick(5_000)).containsExactly(Effect.FollowOn) + assertThat(scheduler.onTick(60_000)).isEmpty() + // the mark goes once the user recovers + assertThat(scheduler.onWordRecited(61_000, atAyahBoundary = false)).containsExactly(Effect.ClearMistake(word)) + } + + private fun armed(): HintScheduler { + val scheduler = HintScheduler(HintConfig(delayMs = 4_000)) + scheduler.arm(0, atAyahBoundary = false) + return scheduler + } +} diff --git a/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/salah/SalahFlowTest.kt b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/salah/SalahFlowTest.kt new file mode 100644 index 0000000000..f3a937d809 --- /dev/null +++ b/feature/memorize/tracker/src/test/kotlin/com/quran/mobile/feature/memorize/tracker/salah/SalahFlowTest.kt @@ -0,0 +1,149 @@ +package com.quran.mobile.feature.memorize.tracker.salah + +import com.google.common.truth.Truth.assertThat +import com.quran.mobile.feature.memorize.tracker.TimedPhoneme +import com.quran.mobile.feature.memorize.tracker.TrackerEvent +import org.junit.Test + +class SalahFlowTest { + + // Latin stand-ins for phonemes keep the scenario readable. + private val fatiha = listOf("alhamdu", "lillahi", "rabbi", "lalamin", "arrahmani", "rrahimi") + private val passage = listOf("qulhuwa", "llahu", "ahadun", "llahu", "ssamadu", "lamyalid", "walamyulad") + private val phrases = listOf( + "takbir" to "allahuakbar", "ameen" to "amin", "ruku" to "subhanarabbiyalazim", "tasmi" to "samiallahulimanhamidah", + ) + + private var time = 0L + + private fun SalahFlow.say(text: String): List = + feed(text.map { TimedPhoneme(it, (time++) * 80) }) + + private fun recitedIndexes(events: List) = + events.filterIsInstance().map { it.index } + + @Test + fun `prayer speech around the passage is never a mistake and the passage continues next rak'ah`() { + val flow = SalahFlow(passage, fatiha, phrases) + val all = mutableListOf() + + // rak'ah 1 + all += flow.say("allahuakbar") + all += flow.say("alhamdulillahirabbilalamin") + all += flow.say("arrahmanirrahimi") + all += flow.say("amin") + assertThat(flow.isReadingPassage).isFalse() + + val first = flow.say("qulhuwallahuahadun") + assertThat(recitedIndexes(first)).containsExactly(0, 1, 2).inOrder() + assertThat(flow.isReadingPassage).isTrue() + + all += flow.say("allahuakbar") + all += flow.onPause() // ruku: silence after the takbir + assertThat(flow.phase).isEqualTo(SalahFlow.Phase.BETWEEN_RAKAHS) + all += flow.say("subhanarabbiyalazim") + + // rak'ah 2: Al-Fatiha again, then the passage from where it stopped + all += flow.say("alhamdulillahirabbilalamin") + all += flow.say("arrahmanirrahimi") + val second = flow.say("llahussamadulamyalidwalamyulad") + + assertThat(all.filterIsInstance()).isEmpty() + assertThat(all.filterIsInstance()).isEmpty() + assertThat(recitedIndexes(second)).containsExactly(3, 4, 5, 6).inOrder() + assertThat(second.filterIsInstance()).isEmpty() + } + + @Test + fun `the passage is over once ruku is heard, even if the takbir wasn't recognized`() { + val flow = SalahFlow(passage, fatiha, phrases) + flow.say("qulhuwallahuahadun") + assertThat(flow.isReadingPassage).isTrue() + + // a takbir lost in the echo, then rising from ruku + flow.say("xx") + flow.say("samiallahulimanhamidah") + flow.onPause() + + assertThat(flow.phase).isEqualTo(SalahFlow.Phase.BETWEEN_RAKAHS) + assertThat(flow.isReadingPassage).isFalse() + } + + @Test + fun `a wrong word inside the passage is still a mistake`() { + val flow = SalahFlow(passage, fatiha, phrases) + flow.say("qulhuwallahu") + + val events = flow.say("xyzxyzxyzxyz") + + assertThat(events.filterIsInstance().map { it.index }).containsExactly(2) + } + + @Test + fun `the passage continues into the next sura in the following rak'ah`() { + val flow = SalahFlow(passage, fatiha, phrases + ("basmala" to "bismillahirrahmanirrahim")) + flow.say("qulhuwallahuahadun") + flow.say("llahussamadulamyalidwalamyulad") + assertThat(flow.passage.isDone).isTrue() + + // the session loads the next sura before the user gets there + flow.extendPassage(listOf("qulauzu", "birabbi", "lfalaqi")) + flow.say("allahuakbar") + flow.onPause() + flow.say("alhamdulillahirabbilalamin") + flow.say("arrahmanirrahimi") + val next = flow.say("bismillahirrahmanirrahimqulauzubirabbilfalaqi") + + assertThat(recitedIndexes(next)).containsExactly(7, 8, 9).inOrder() + assertThat(next.filterIsInstance()).isEmpty() + assertThat(flow.isReadingPassage).isTrue() + } + + @Test + fun `a passage recited after Al-Fatiha that isn't on screen is marked, prayer speech isn't`() { + val flow = SalahFlow(passage, fatiha, phrases, startWindow = passage.size) + val all = mutableListOf() + all += flow.say("allahuakbar") + all += flow.say("alhamdulillahirabbilalamin") + all += flow.say("arrahmanirrahimi") + all += flow.say("amin") + assertThat(all.filterIsInstance()).isEmpty() + + val elsewhere = flow.say("waddhuhawallayliidhasajamawaddaakarabbukawamaqala") + assertThat(elsewhere.filterIsInstance().map { it.kind }) + .containsExactly(TrackerEvent.Mistake.Kind.ELSEWHERE) + assertThat(flow.isReadingPassage).isFalse() + + // the passage on screen, started in its middle + val started = flow.say("llahussamadulamyalid") + assertThat(recitedIndexes(started)).containsExactly(3, 4, 5).inOrder() + assertThat(flow.isReadingPassage).isTrue() + } + + @Test + fun `the passage's start isn't looked for while Al-Fatiha is recited`() { + // a passage whose words also occur in Al-Fatiha + val passageLikeFatiha = listOf("rabbi", "lalamin", "qulhuwa", "llahu", "ahadun") + val flow = SalahFlow(passageLikeFatiha, fatiha, phrases, startWindow = passageLikeFatiha.size) + + flow.say("alhamdulillahi") + flow.say("rabbilalamin") + assertThat(flow.passage.anchored).isFalse() + + flow.say("arrahmanirrahimi") + flow.say("amin") + val passage = flow.say("qulhuwallahuahadun") + assertThat(recitedIndexes(passage)).containsExactly(2, 3, 4).inOrder() + } + + @Test + fun `the passage is found when listening starts after Al-Fatiha`() { + // e.g. the user pressed the mic once the imam had finished Al-Fatiha + val flow = SalahFlow(passage, fatiha, phrases, startWindow = passage.size) + + val events = flow.say("llahussamadulamyalid") + + assertThat(recitedIndexes(events)).containsExactly(3, 4, 5).inOrder() + assertThat(flow.isReadingPassage).isTrue() + } +} diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_garbled_loose.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_garbled_loose.tsv new file mode 100644 index 0000000000..c321a8cb12 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_garbled_loose.tsv @@ -0,0 +1,130 @@ +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَءِنَهُو +W لَلحَقُ +W مِ +W رَبِكَ +W وَمَ +W لَاهُ +W بِغَافِلِن +W عَمَا +W تَعمَلُون +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَحَيثُ +W مَا +W كُنتُم +W فَوَلُو +W وُجُوهَكُم +W شَطرَهُو +W لِءَلَا +W يَكُونَ +W لِنَاسِ +W عَلَيكُم +W حُجَتُن +W ءِلَ +W لَذِينَ +W ظَلَمُو +W مِنهُم +W فَلَا +W تَخشَوهُم +W وَخشَونِي +W وَلِءُتِمَ +W نِعمَتِي +W عَلَيكُم +W وَلَعَلَكُم +W تَهتَدُون +W كَمَا +W ءَرسَلنَا +W فِيكُم +W رَسُولَ +W مِنكُم +W يَتلُو +W عَلَيكُم +W ءَايَاتِنَا +W وَيُزَكِيكُم +W وَيُعَلِمُكُمُ +W لكِتَابَ +W وَلحِكمَتَ +W وَيُعَلِمُكُ +W مَا +W لَم +W تَكُونُو +W تَعلَمُون +W فَذكُرُونِي +W ءَذكُركُم +W وَشكُرُو +W لِي +W وَلَا +W تَكفُرُون +W يَاءَيُهَ +W لَذِينَ +W ءَامَنُ +W ستَعِينُو +W بِصَبرِ +W وَصَلَاتِ +W ءِنَ +W لَاهَ +W مَعَ +W صَابِرِين +A 2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2152,2152,2152,2152,2152,2152,2153,2153,2153,2153,2153,2153,2153,2153,2153,2153 +C max_missed_words=2;skip_ayat=0 +F و,0;َ,60;م,120;ِ,180;ن,240 +E 0 word 0 240 +F ح,420;َ,480;ي,540;ث,600;ُ,660 +E 1 word 1 660 +F خ,840;َ,900;ر,960;َ,1020;ج,1080;ت,1140;َ,1200 +E 2 word 2 1200 +F ف,1380;َ,1440;و,1500;َ,1560;ل,1620;ِ,1680 +E 3 word 3 1680 +F و,1860;َ,1920;ج,1980;ه,2040;َ,2100;ك,2160;َ,2220 +E 4 word 4 2220 +F ش,2400;َ,2460;ط,2520;ر,2580;َ,2640 +E 5 word 5 2640 +F ه,2820;ص,2880;َ,2940;ن,3000;ف,3060;ِ,3120;غ,3180;ِ,3240 +F ه,3420;ظ,3480;َ,3540;ط,3600;َ,3660;ا,3720;ص,3780;ِ,3840 +E 7 mistake 6 3840 SUBSTITUTION +F ر,4020;َ,4080;ء,4140;ِ,4200;ز,4260;َ,4320;خ,4380;ُ,4440;ر,4500 +F ه,4680;َ,4740;ه,4800;ظ,4860;َ,4920;ت,4980;ُ,5040 +F ص,5220;ِ,5280 +F ر,5460;َ,5520;ب,5580;ِ,5640;ك,5700;َ,5760 +F و,5940;َ,6000;م,6060;َ,6120 +F ل,6300;َ,6360;ا,6420;ه,6480;ُ,6540 +E 13 word 6 6540 ctx +E 13 word 7 6540 ctx +E 13 word 8 6540 ctx +E 13 word 9 6540 rec +E 13 word 10 6540 rec +E 13 word 11 6540 rec +E 13 word 12 6540 rec +E 13 word 13 6540 rec +F ب,6720;ِ,6780;غ,6840;َ,6900;ا,6960;ف,7020;ِ,7080;ل,7140;ِ,7200;ن,7260 +E 14 word 14 7260 +F ع,7440;َ,7500;م,7560;َ,7620;ا,7680 +E 15 word 15 7680 +F ت,7860;َ,7920;ع,7980;م,8040;َ,8100;ل,8160;ُ,8220;و,8280;ن,8340 +E 16 word 16 8340 +F و,8520;َ,8580;م,8640;ِ,8700;ن,8760 +E 17 word 17 8760 +F ح,8940;َ,9000;ي,9060;ث,9120;ُ,9180 +E 18 word 18 9180 +F خ,9360;َ,9420;ر,9480;َ,9540;ج,9600;ت,9660;َ,9720 +E 19 word 19 9720 +F ف,9900;َ,9960;و,10020;َ,10080;ل,10140;ِ,10200 +E 20 word 20 10200 +F و,10380;َ,10440;ج,10500;ه,10560;َ,10620;ك,10680;َ,10740 +E 21 word 21 10740 +F ش,10920;َ,10980;ط,11040;ر,11100;َ,11160 +E 22 word 22 11160 diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_garbled_strict.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_garbled_strict.tsv new file mode 100644 index 0000000000..51f0982dd9 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_garbled_strict.tsv @@ -0,0 +1,130 @@ +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَءِنَهُو +W لَلحَقُ +W مِ +W رَبِكَ +W وَمَ +W لَاهُ +W بِغَافِلِن +W عَمَا +W تَعمَلُون +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَحَيثُ +W مَا +W كُنتُم +W فَوَلُو +W وُجُوهَكُم +W شَطرَهُو +W لِءَلَا +W يَكُونَ +W لِنَاسِ +W عَلَيكُم +W حُجَتُن +W ءِلَ +W لَذِينَ +W ظَلَمُو +W مِنهُم +W فَلَا +W تَخشَوهُم +W وَخشَونِي +W وَلِءُتِمَ +W نِعمَتِي +W عَلَيكُم +W وَلَعَلَكُم +W تَهتَدُون +W كَمَا +W ءَرسَلنَا +W فِيكُم +W رَسُولَ +W مِنكُم +W يَتلُو +W عَلَيكُم +W ءَايَاتِنَا +W وَيُزَكِيكُم +W وَيُعَلِمُكُمُ +W لكِتَابَ +W وَلحِكمَتَ +W وَيُعَلِمُكُ +W مَا +W لَم +W تَكُونُو +W تَعلَمُون +W فَذكُرُونِي +W ءَذكُركُم +W وَشكُرُو +W لِي +W وَلَا +W تَكفُرُون +W يَاءَيُهَ +W لَذِينَ +W ءَامَنُ +W ستَعِينُو +W بِصَبرِ +W وَصَلَاتِ +W ءِنَ +W لَاهَ +W مَعَ +W صَابِرِين +A 2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2152,2152,2152,2152,2152,2152,2153,2153,2153,2153,2153,2153,2153,2153,2153,2153 +C max_missed_words=0;skip_ayat=0 +F و,0;َ,60;م,120;ِ,180;ن,240 +E 0 word 0 240 +F ح,420;َ,480;ي,540;ث,600;ُ,660 +E 1 word 1 660 +F خ,840;َ,900;ر,960;َ,1020;ج,1080;ت,1140;َ,1200 +E 2 word 2 1200 +F ف,1380;َ,1440;و,1500;َ,1560;ل,1620;ِ,1680 +E 3 word 3 1680 +F و,1860;َ,1920;ج,1980;ه,2040;َ,2100;ك,2160;َ,2220 +E 4 word 4 2220 +F ش,2400;َ,2460;ط,2520;ر,2580;َ,2640 +E 5 word 5 2640 +F ه,2820;ص,2880;َ,2940;ن,3000;ف,3060;ِ,3120;غ,3180;ِ,3240 +F ه,3420;ظ,3480;َ,3540;ط,3600;َ,3660;ا,3720;ص,3780;ِ,3840 +E 7 mistake 6 3840 SUBSTITUTION +F ر,4020;َ,4080;ء,4140;ِ,4200;ز,4260;َ,4320;خ,4380;ُ,4440;ر,4500 +F ه,4680;َ,4740;ه,4800;ظ,4860;َ,4920;ت,4980;ُ,5040 +F ص,5220;ِ,5280 +F ر,5460;َ,5520;ب,5580;ِ,5640;ك,5700;َ,5760 +F و,5940;َ,6000;م,6060;َ,6120 +F ل,6300;َ,6360;ا,6420;ه,6480;ُ,6540 +E 13 word 6 6540 ctx +E 13 word 7 6540 ctx +E 13 word 8 6540 ctx +E 13 word 9 6540 rec +E 13 word 10 6540 rec +E 13 word 11 6540 rec +E 13 word 12 6540 rec +E 13 word 13 6540 rec +F ب,6720;ِ,6780;غ,6840;َ,6900;ا,6960;ف,7020;ِ,7080;ل,7140;ِ,7200;ن,7260 +E 14 word 14 7260 +F ع,7440;َ,7500;م,7560;َ,7620;ا,7680 +E 15 word 15 7680 +F ت,7860;َ,7920;ع,7980;م,8040;َ,8100;ل,8160;ُ,8220;و,8280;ن,8340 +E 16 word 16 8340 +F و,8520;َ,8580;م,8640;ِ,8700;ن,8760 +E 17 word 17 8760 +F ح,8940;َ,9000;ي,9060;ث,9120;ُ,9180 +E 18 word 18 9180 +F خ,9360;َ,9420;ر,9480;َ,9540;ج,9600;ت,9660;َ,9720 +E 19 word 19 9720 +F ف,9900;َ,9960;و,10020;َ,10080;ل,10140;ِ,10200 +E 20 word 20 10200 +F و,10380;َ,10440;ج,10500;ه,10560;َ,10620;ك,10680;َ,10740 +E 21 word 21 10740 +F ش,10920;َ,10980;ط,11040;ر,11100;َ,11160 +E 22 word 22 11160 diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_left_out_followed.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_left_out_followed.tsv new file mode 100644 index 0000000000..c1429dac79 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_left_out_followed.tsv @@ -0,0 +1,185 @@ +W وَلِكُلِو +W وِجهَتُن +W هُوَ +W مُوَلِيهَا +W فَستَبِقُ +W لخَيرَاتِ +W ءَينَ +W مَا +W تَكُونُو +W يَءتِ +W بِكُمُ +W لَاهُ +W جَمِيعَن +W ءِنَ +W لَاهَ +W عَلَا +W كُلِ +W شَيءِن +W قَدِير +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَءِنَهُو +W لَلحَقُ +W مِ +W رَبِكَ +W وَمَ +W لَاهُ +W بِغَافِلِن +W عَمَا +W تَعمَلُون +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَحَيثُ +W مَا +W كُنتُم +W فَوَلُو +W وُجُوهَكُم +W شَطرَهُو +W لِءَلَا +W يَكُونَ +W لِنَاسِ +W عَلَيكُم +W حُجَتُن +W ءِلَ +W لَذِينَ +W ظَلَمُو +W مِنهُم +W فَلَا +W تَخشَوهُم +W وَخشَونِي +W وَلِءُتِمَ +W نِعمَتِي +W عَلَيكُم +W وَلَعَلَكُم +W تَهتَدُون +W كَمَا +W ءَرسَلنَا +W فِيكُم +W رَسُولَ +W مِنكُم +W يَتلُو +W عَلَيكُم +W ءَايَاتِنَا +W وَيُزَكِيكُم +W وَيُعَلِمُكُمُ +W لكِتَابَ +W وَلحِكمَتَ +W وَيُعَلِمُكُ +W مَا +W لَم +W تَكُونُو +W تَعلَمُون +W فَذكُرُونِي +W ءَذكُركُم +W وَشكُرُو +W لِي +W وَلَا +W تَكفُرُون +W يَاءَيُهَ +W لَذِينَ +W ءَامَنُ +W ستَعِينُو +W بِصَبرِ +W وَصَلَاتِ +W ءِنَ +W لَاهَ +W مَعَ +W صَابِرِين +A 2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2152,2152,2152,2152,2152,2152,2153,2153,2153,2153,2153,2153,2153,2153,2153,2153 +F و,0;َ,60;ل,120;ِ,180;ك,240;ُ,300;ل,360;ِ,420;و,480 +E 0 word 0 480 +F و,660;ِ,720;ج,780;ه,840;َ,900;ت,960;ُ,1020;ن,1080 +E 1 word 1 1080 +F ه,1260;ُ,1320;و,1380;َ,1440 +E 2 word 2 1440 +F م,1620;ُ,1680;و,1740;َ,1800;ل,1860;ِ,1920;ي,1980;ه,2040;َ,2100;ا,2160 +E 3 word 3 2160 +F ف,2340;َ,2400;س,2460;ت,2520;َ,2580;ب,2640;ِ,2700;ق,2760;ُ,2820 +E 4 word 4 2820 +F ل,3000;خ,3060;َ,3120;ي,3180;ر,3240;َ,3300;ا,3360;ت,3420;ِ,3480 +E 5 word 5 3480 +F ء,3660;َ,3720;ي,3780;ن,3840;َ,3900 +E 6 word 6 3900 +F م,4080;َ,4140;ا,4200 +E 7 word 7 4200 +F ت,4380;َ,4440;ك,4500;ُ,4560;و,4620;ن,4680;ُ,4740;و,4800 +E 8 word 8 4800 +F ي,4980;َ,5040;ء,5100;ت,5160;ِ,5220 +E 9 word 9 5220 +F ب,5400;ِ,5460;ك,5520;ُ,5580;م,5640;ُ,5700 +E 10 word 10 5700 +F ل,5880;َ,5940;ا,6000;ه,6060;ُ,6120 +E 11 word 11 6120 +F ج,6300;َ,6360;م,6420;ِ,6480;ي,6540;ع,6600;َ,6660;ن,6720 +E 12 word 12 6720 +F ء,6900;ِ,6960;ن,7020;َ,7080 +E 13 word 13 7080 +F ل,7260;َ,7320;ا,7380;ه,7440;َ,7500 +E 14 word 14 7500 +F ع,7680;َ,7740;ل,7800;َ,7860;ا,7920 +E 15 word 15 7920 +F ك,8100;ُ,8160;ل,8220;ِ,8280 +E 16 word 16 8280 +F ش,8460;َ,8520;ي,8580;ء,8640;ِ,8700;ن,8760 +E 17 word 17 8760 +F ق,8940;َ,9000;د,9060;ِ,9120;ي,9180;ر,9240 +E 18 word 18 9240 +F و,9420;َ,9480;م,9540;ِ,9600;ن,9660 +E 19 word 19 9660 +F ح,9840;َ,9900;ي,9960;ث,10020;ُ,10080 +E 20 word 20 10080 +F خ,10260;َ,10320;ر,10380;َ,10440;ج,10500;ت,10560;َ,10620 +E 21 word 21 10620 +F ف,10800;َ,10860;و,10920;َ,10980;ل,11040;ِ,11100 +E 22 word 22 11100 +F و,11280;َ,11340;ج,11400;ه,11460;َ,11520;ك,11580;َ,11640 +E 23 word 23 11640 +F ش,11820;َ,11880;ط,11940;ر,12000;َ,12060 +E 24 word 24 12060 +F ل,12240;م,12300;َ,12360;س,12420;ج,12480;ِ,12540;د,12600;ِ,12660 +E 25 word 25 12660 +F ل,12840;ح,12900;َ,12960;ر,13020;َ,13080;ا,13140;م,13200;ِ,13260 +E 26 word 26 13260 +F و,13440;َ,13500;ح,13560;َ,13620;ي,13680;ث,13740;ُ,13800 +F م,13980;َ,14040;ا,14100 +F ك,14280;ُ,14340;ن,14400;ت,14460;ُ,14520;م,14580 +E 29 mistake 27 14580 SUBSTITUTION +F ف,14760;َ,14820;و,14880;َ,14940;ل,15000;ُ,15060;و,15120 +E 30 missed 27 15120 +E 30 missed 28 15120 +E 30 missed 29 15120 +E 30 missed 30 15120 +E 30 missed 31 15120 +E 30 missed 32 15120 +E 30 missed 33 15120 +E 30 missed 34 15120 +E 30 missed 35 15120 +E 30 missed 36 15120 +E 30 missed 37 15120 +E 30 missed 38 15120 +E 30 missed 39 15120 +E 30 missed 40 15120 +E 30 missed 41 15120 +E 30 missed 42 15120 +E 30 missed 43 15120 +E 30 word 44 15120 rec +E 30 word 45 15120 rec +E 30 word 46 15120 rec +E 30 word 47 15120 rec +F و,15300;ُ,15360;ج,15420;ُ,15480;و,15540;ه,15600;َ,15660;ك,15720;ُ,15780;م,15840 +E 31 word 48 15840 +F ش,16020;َ,16080;ط,16140;ر,16200;َ,16260;ه,16320;ُ,16380;و,16440 +E 32 word 49 16440 diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_left_out_held.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_left_out_held.tsv new file mode 100644 index 0000000000..57ba2a89ba --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_left_out_held.tsv @@ -0,0 +1,163 @@ +W وَلِكُلِو +W وِجهَتُن +W هُوَ +W مُوَلِيهَا +W فَستَبِقُ +W لخَيرَاتِ +W ءَينَ +W مَا +W تَكُونُو +W يَءتِ +W بِكُمُ +W لَاهُ +W جَمِيعَن +W ءِنَ +W لَاهَ +W عَلَا +W كُلِ +W شَيءِن +W قَدِير +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَءِنَهُو +W لَلحَقُ +W مِ +W رَبِكَ +W وَمَ +W لَاهُ +W بِغَافِلِن +W عَمَا +W تَعمَلُون +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَحَيثُ +W مَا +W كُنتُم +W فَوَلُو +W وُجُوهَكُم +W شَطرَهُو +W لِءَلَا +W يَكُونَ +W لِنَاسِ +W عَلَيكُم +W حُجَتُن +W ءِلَ +W لَذِينَ +W ظَلَمُو +W مِنهُم +W فَلَا +W تَخشَوهُم +W وَخشَونِي +W وَلِءُتِمَ +W نِعمَتِي +W عَلَيكُم +W وَلَعَلَكُم +W تَهتَدُون +W كَمَا +W ءَرسَلنَا +W فِيكُم +W رَسُولَ +W مِنكُم +W يَتلُو +W عَلَيكُم +W ءَايَاتِنَا +W وَيُزَكِيكُم +W وَيُعَلِمُكُمُ +W لكِتَابَ +W وَلحِكمَتَ +W وَيُعَلِمُكُ +W مَا +W لَم +W تَكُونُو +W تَعلَمُون +W فَذكُرُونِي +W ءَذكُركُم +W وَشكُرُو +W لِي +W وَلَا +W تَكفُرُون +W يَاءَيُهَ +W لَذِينَ +W ءَامَنُ +W ستَعِينُو +W بِصَبرِ +W وَصَلَاتِ +W ءِنَ +W لَاهَ +W مَعَ +W صَابِرِين +A 2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2152,2152,2152,2152,2152,2152,2153,2153,2153,2153,2153,2153,2153,2153,2153,2153 +C max_missed_words=2;skip_ayat=0 +F و,0;َ,60;ل,120;ِ,180;ك,240;ُ,300;ل,360;ِ,420;و,480 +E 0 word 0 480 +F و,660;ِ,720;ج,780;ه,840;َ,900;ت,960;ُ,1020;ن,1080 +E 1 word 1 1080 +F ه,1260;ُ,1320;و,1380;َ,1440 +E 2 word 2 1440 +F م,1620;ُ,1680;و,1740;َ,1800;ل,1860;ِ,1920;ي,1980;ه,2040;َ,2100;ا,2160 +E 3 word 3 2160 +F ف,2340;َ,2400;س,2460;ت,2520;َ,2580;ب,2640;ِ,2700;ق,2760;ُ,2820 +E 4 word 4 2820 +F ل,3000;خ,3060;َ,3120;ي,3180;ر,3240;َ,3300;ا,3360;ت,3420;ِ,3480 +E 5 word 5 3480 +F ء,3660;َ,3720;ي,3780;ن,3840;َ,3900 +E 6 word 6 3900 +F م,4080;َ,4140;ا,4200 +E 7 word 7 4200 +F ت,4380;َ,4440;ك,4500;ُ,4560;و,4620;ن,4680;ُ,4740;و,4800 +E 8 word 8 4800 +F ي,4980;َ,5040;ء,5100;ت,5160;ِ,5220 +E 9 word 9 5220 +F ب,5400;ِ,5460;ك,5520;ُ,5580;م,5640;ُ,5700 +E 10 word 10 5700 +F ل,5880;َ,5940;ا,6000;ه,6060;ُ,6120 +E 11 word 11 6120 +F ج,6300;َ,6360;م,6420;ِ,6480;ي,6540;ع,6600;َ,6660;ن,6720 +E 12 word 12 6720 +F ء,6900;ِ,6960;ن,7020;َ,7080 +E 13 word 13 7080 +F ل,7260;َ,7320;ا,7380;ه,7440;َ,7500 +E 14 word 14 7500 +F ع,7680;َ,7740;ل,7800;َ,7860;ا,7920 +E 15 word 15 7920 +F ك,8100;ُ,8160;ل,8220;ِ,8280 +E 16 word 16 8280 +F ش,8460;َ,8520;ي,8580;ء,8640;ِ,8700;ن,8760 +E 17 word 17 8760 +F ق,8940;َ,9000;د,9060;ِ,9120;ي,9180;ر,9240 +E 18 word 18 9240 +F و,9420;َ,9480;م,9540;ِ,9600;ن,9660 +E 19 word 19 9660 +F ح,9840;َ,9900;ي,9960;ث,10020;ُ,10080 +E 20 word 20 10080 +F خ,10260;َ,10320;ر,10380;َ,10440;ج,10500;ت,10560;َ,10620 +E 21 word 21 10620 +F ف,10800;َ,10860;و,10920;َ,10980;ل,11040;ِ,11100 +E 22 word 22 11100 +F و,11280;َ,11340;ج,11400;ه,11460;َ,11520;ك,11580;َ,11640 +E 23 word 23 11640 +F ش,11820;َ,11880;ط,11940;ر,12000;َ,12060 +E 24 word 24 12060 +F ل,12240;م,12300;َ,12360;س,12420;ج,12480;ِ,12540;د,12600;ِ,12660 +E 25 word 25 12660 +F ل,12840;ح,12900;َ,12960;ر,13020;َ,13080;ا,13140;م,13200;ِ,13260 +E 26 word 26 13260 +F و,13440;َ,13500;ح,13560;َ,13620;ي,13680;ث,13740;ُ,13800 +F م,13980;َ,14040;ا,14100 +F ك,14280;ُ,14340;ن,14400;ت,14460;ُ,14520;م,14580 +E 29 mistake 27 14580 SUBSTITUTION +F ف,14760;َ,14820;و,14880;َ,14940;ل,15000;ُ,15060;و,15120 +F و,15300;ُ,15360;ج,15420;ُ,15480;و,15540;ه,15600;َ,15660;ك,15720;ُ,15780;م,15840 +F ش,16020;َ,16080;ط,16140;ر,16200;َ,16260;ه,16320;ُ,16380;و,16440 diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_phrase_again_held.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_phrase_again_held.tsv new file mode 100644 index 0000000000..67c975c2fe --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_phrase_again_held.tsv @@ -0,0 +1,219 @@ +W ءِنَا +W ءَنزَلنَ +W تَورَاتَ +W فِيهَا +W هُدَو +W وَنُورُي +W يَحكُمُ +W بِهَ +W نَبِيُونَ +W لَذِينَ +W ءَسلَمُو +W لِلَذِينَ +W هَادُو +W وَرَبَانِيُونَ +W وَلءَحبَارُ +W بِمَ +W ستُحفِظُو +W مِن +W كِتَابِ +W لَاهِ +W وَكَانُو +W عَلَيهِ +W شُهَدَاءَ +W فَلَا +W تَخشَوُ +W نَاسَ +W وَخشَونِ +W وَلَا +W تَشتَرُو +W بِءَايَاتِي +W ثَمَنَن +W قَلِيلَو +W وَمَ +W لَم +W يَحكُم +W بِمَا +W ءَنزَلَ +W لَاهُ +W فَءُلَاءِكَ +W هُمُ +W لكَافِرُون +W وَكَتَبنَا +W عَلَيهِم +W فِيهَا +W ءَنَ +W نَفسَ +W بِنَفسِ +W وَلعَينَ +W بِلعَينِ +W وَلءَنفَ +W بِلءَنفِ +W وَلءُذُنَ +W بِلءُذُنِ +W وَسِنَ +W بِسِنِ +W وَلجُرُوحَ +W قِصَاصُن +W فَمَن +W تَصَدَقَ +W بِهِي +W فَهُوَ +W كَفَارَتُ +W لَهُو +W وَمَ +W لَم +W يَحكُم +W بِمَا +W ءَنزَلَ +W لَاهُ +W فَءُلَاءِكَ +W هُمُ +W ظَالِمُون +W وَقَفَينَا +W عَلَا +W ءَاثَارِهِم +W بِعِيسَ +W بنِ +W مَريَمَ +W مُصَدِقَ +W لِمَا +W بَينَ +W يَدَيهِ +W مِنَ +W تَورَاتِ +W وَءَاتَينَاهُ +W لءِنجِيلَ +W فِيهِ +W هُدَو +W وَنُورُو +W وَمُصَدِقَ +W لِمَا +W بَينَ +W يَدَيهِ +W مِنَ +W تَورَاتِ +W وَهُدَو +W وَمَوعِظَتَ +W لِلمُتَقِين +A 5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046 +C max_missed_words=2;skip_ayat=0 +F ء,0;ِ,60;ن,120;َ,180;ا,240 +E 0 word 0 240 +F ء,420;َ,480;ن,540;ز,600;َ,660;ل,720;ن,780;َ,840 +E 1 word 1 840 +F ت,1020;َ,1080;و,1140;ر,1200;َ,1260;ا,1320;ت,1380;َ,1440 +E 2 word 2 1440 +F ف,1620;ِ,1680;ي,1740;ه,1800;َ,1860;ا,1920 +E 3 word 3 1920 +F ه,2100;ُ,2160;د,2220;َ,2280;و,2340 +E 4 word 4 2340 +F و,2520;َ,2580;ن,2640;ُ,2700;و,2760;ر,2820;ُ,2880;ي,2940 +E 5 word 5 2940 +F ي,3120;َ,3180;ح,3240;ك,3300;ُ,3360;م,3420;ُ,3480 +E 6 word 6 3480 +F ب,3660;ِ,3720;ه,3780;َ,3840 +E 7 word 7 3840 +F ن,4020;َ,4080;ب,4140;ِ,4200;ي,4260;ُ,4320;و,4380;ن,4440;َ,4500 +E 8 word 8 4500 +F ل,4680;َ,4740;ذ,4800;ِ,4860;ي,4920;ن,4980;َ,5040 +E 9 word 9 5040 +F ء,5220;َ,5280;س,5340;ل,5400;َ,5460;م,5520;ُ,5580;و,5640 +E 10 word 10 5640 +F ل,5820;ِ,5880;ل,5940;َ,6000;ذ,6060;ِ,6120;ي,6180;ن,6240;َ,6300 +E 11 word 11 6300 +F ه,6480;َ,6540;ا,6600;د,6660;ُ,6720;و,6780 +E 12 word 12 6780 +F و,6960;َ,7020;ر,7080;َ,7140;ب,7200;َ,7260;ا,7320;ن,7380;ِ,7440;ي,7500;ُ,7560;و,7620;ن,7680;َ,7740 +E 13 word 13 7740 +F و,7920;َ,7980;ل,8040;ء,8100;َ,8160;ح,8220;ب,8280;َ,8340;ا,8400;ر,8460;ُ,8520 +E 14 word 14 8520 +F ب,8700;ِ,8760;م,8820;َ,8880 +E 15 word 15 8880 +F س,9060;ت,9120;ُ,9180;ح,9240;ف,9300;ِ,9360;ظ,9420;ُ,9480;و,9540 +E 16 word 16 9540 +F م,9720;ِ,9780;ن,9840 +E 17 word 17 9840 +F ك,10020;ِ,10080;ت,10140;َ,10200;ا,10260;ب,10320;ِ,10380 +E 18 word 18 10380 +F ل,10560;َ,10620;ا,10680;ه,10740;ِ,10800 +E 19 word 19 10800 +F و,10980;َ,11040;ك,11100;َ,11160;ا,11220;ن,11280;ُ,11340;و,11400 +E 20 word 20 11400 +F ع,11580;َ,11640;ل,11700;َ,11760;ي,11820;ه,11880;ِ,11940 +E 21 word 21 11940 +F ش,12120;ُ,12180;ه,12240;َ,12300;د,12360;َ,12420;ا,12480;ء,12540;َ,12600 +E 22 word 22 12600 +F ف,12780;َ,12840;ل,12900;َ,12960;ا,13020 +E 23 word 23 13020 +F ت,13200;َ,13260;خ,13320;ش,13380;َ,13440;و,13500;ُ,13560 +E 24 word 24 13560 +F ن,13740;َ,13800;ا,13860;س,13920;َ,13980 +E 25 word 25 13980 +F و,14160;َ,14220;خ,14280;ش,14340;َ,14400;و,14460;ن,14520;ِ,14580 +E 26 word 26 14580 +F و,14760;َ,14820;ل,14880;َ,14940;ا,15000 +E 27 word 27 15000 +F ت,15180;َ,15240;ش,15300;ت,15360;َ,15420;ر,15480;ُ,15540;و,15600 +E 28 word 28 15600 +F ب,15780;ِ,15840;ء,15900;َ,15960;ا,16020;ي,16080;َ,16140;ا,16200;ت,16260;ِ,16320;ي,16380 +E 29 word 29 16380 +F ث,16560;َ,16620;م,16680;َ,16740;ن,16800;َ,16860;ن,16920 +E 30 word 30 16920 +F ق,17100;َ,17160;ل,17220;ِ,17280;ي,17340;ل,17400;َ,17460;و,17520 +E 31 word 31 17520 +F و,17700;َ,17760;م,17820;َ,17880 +E 32 word 32 17880 +F ل,18060;َ,18120;م,18180 +E 33 word 33 18180 +F ي,18360;َ,18420;ح,18480;ك,18540;ُ,18600;م,18660 +E 34 word 34 18660 +F ب,18840;ِ,18900;م,18960;َ,19020;ا,19080 +E 35 word 35 19080 +F ء,19260;َ,19320;ن,19380;ز,19440;َ,19500;ل,19560;َ,19620 +E 36 word 36 19620 +F ل,19800;َ,19860;ا,19920;ه,19980;ُ,20040 +E 37 word 37 20040 +F ف,20220;َ,20280;ء,20340;ُ,20400;ل,20460;َ,20520;ا,20580;ء,20640;ِ,20700;ك,20760;َ,20820 +E 38 word 38 20820 +F ه,21000;ُ,21060;م,21120;ُ,21180 +E 39 word 39 21180 +F ل,21360;ك,21420;َ,21480;ا,21540;ف,21600;ِ,21660;ر,21720;ُ,21780;و,21840;ن,21900 +E 40 word 40 21900 +F و,22080;َ,22140;ك,22200;َ,22260;ت,22320;َ,22380;ب,22440;ن,22500;َ,22560;ا,22620 +E 41 word 41 22620 +F ع,22800;َ,22860;ل,22920;َ,22980;ي,23040;ه,23100;ِ,23160;م,23220 +E 42 word 42 23220 +F ف,23400;ِ,23460;ي,23520;ه,23580;َ,23640;ا,23700 +E 43 word 43 23700 +F ء,23880;َ,23940;ن,24000;َ,24060 +E 44 word 44 24060 +F ن,24240;َ,24300;ف,24360;س,24420;َ,24480 +E 45 word 45 24480 +F ب,24660;ِ,24720;ن,24780;َ,24840;ف,24900;س,24960;ِ,25020 +E 46 word 46 25020 +F و,25200;َ,25260;ل,25320;ع,25380;َ,25440;ي,25500;ن,25560;َ,25620 +E 47 word 47 25620 +F ب,25800;ِ,25860;ل,25920;ع,25980;َ,26040;ي,26100;ن,26160;ِ,26220 +E 48 word 48 26220 +F و,26400;َ,26460;ل,26520;ء,26580;َ,26640;ن,26700;ف,26760;َ,26820 +E 49 word 49 26820 +F ب,27000;ِ,27060;ل,27120;ء,27180;َ,27240;ن,27300;ف,27360;ِ,27420 +E 50 word 50 27420 +F و,27600;َ,27660;ل,27720;ء,27780;ُ,27840;ذ,27900;ُ,27960;ن,28020;َ,28080 +E 51 word 51 28080 +F ب,28260;ِ,28320;ل,28380;ء,28440;ُ,28500;ذ,28560;ُ,28620;ن,28680;ِ,28740 +E 52 word 52 28740 +F و,28920;َ,28980;س,29040;ِ,29100;ن,29160;َ,29220 +E 53 word 53 29220 +F ب,29400;ِ,29460;س,29520;ِ,29580;ن,29640;ِ,29700 +E 54 word 54 29700 +F ل,29880;َ,29940;م,30000 +F ي,30180;َ,30240;ح,30300;ك,30360;ُ,30420;م,30480 +F ب,30660;ِ,30720;م,30780;َ,30840;ا,30900 +E 57 mistake 55 30900 SUBSTITUTION +F ء,31080;َ,31140;ن,31200;ز,31260;َ,31320;ل,31380;َ,31440 +F ل,31620;َ,31680;ا,31740;ه,31800;ُ,31860 +F ف,32040;َ,32100;ء,32160;ُ,32220;ل,32280;َ,32340;ا,32400;ء,32460;ِ,32520;ك,32580;َ,32640 +F ه,32820;ُ,32880;م,32940;ُ,33000 +F ظ,33180;َ,33240;ا,33300;ل,33360;ِ,33420;م,33480;ُ,33540;و,33600;ن,33660 diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_refrain_left_out.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_refrain_left_out.tsv new file mode 100644 index 0000000000..695f77778d --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_refrain_left_out.tsv @@ -0,0 +1,114 @@ +W فَبِءَيِ +W ءَالَاءِ +W رَبِكُمَا +W تُكَذِبَان +W خَلَقَ +W لءِنسَانَ +W مِن +W صَلصَالِن +W كَلفَخَار +W وَخَلَقَ +W لجَانَ +W مِ +W مَارِجِ +W مِ +W نَار +W فَبِءَيِ +W ءَالَاءِ +W رَبِكُمَا +W تُكَذِبَان +W رَبُ +W لمَشرِقَينِ +W وَرَبُ +W لمَغرِبَين +W فَبِءَيِ +W ءَالَاءِ +W رَبِكُمَا +W تُكَذِبَان +W مَرَجَ +W لبَحرَينِ +W يَلتَقِيَان +W بَينَهُمَا +W بَرزَخُ +W لَا +W يَبغِيَان +W فَبِءَيِ +W ءَالَاءِ +W رَبِكُمَا +W تُكَذِبَان +W يَخرُجُ +W مِنهُمَ +W لُءلُءُ +W وَلمَرجَان +W فَبِءَيِ +W ءَالَاءِ +W رَبِكُمَا +W تُكَذِبَان +W وَلَهُ +W لجَوَارِ +W لمُنشَءَاتُ +W فِ +W لبَحرِ +W كَلءَعلَام +W فَبِءَيِ +W ءَالَاءِ +W رَبِكُمَا +W تُكَذِبَان +W كُلُ +W مَن +W عَلَيهَا +W فَان +W وَيَبقَا +W وَجهُ +W رَبِكَ +W ذُ +W لجَلَالِ +W وَلءِكرَام +W فَبِءَيِ +W ءَالَاءِ +W رَبِكُمَا +W تُكَذِبَان +W يَسءَلُهُو +W مَن +W فِ +W سَمَاوَاتِ +W وَلءَرضِ +W كُلَ +W يَومِن +W هُوَ +W فِي +W شَءن +W فَبِءَيِ +W ءَالَاءِ +W رَبِكُمَا +W تُكَذِبَان +A 55013,55013,55013,55013,55014,55014,55014,55014,55014,55015,55015,55015,55015,55015,55015,55016,55016,55016,55016,55017,55017,55017,55017,55018,55018,55018,55018,55019,55019,55019,55020,55020,55020,55020,55021,55021,55021,55021,55022,55022,55022,55022,55023,55023,55023,55023,55024,55024,55024,55024,55024,55024,55025,55025,55025,55025,55026,55026,55026,55026,55027,55027,55027,55027,55027,55027,55028,55028,55028,55028,55029,55029,55029,55029,55029,55029,55029,55029,55029,55029,55030,55030,55030,55030 +C max_missed_words=2;skip_ayat=0 +F ف,0;َ,60;ب,120;ِ,180;ء,240;َ,300;ي,360;ِ,420 +E 0 word 0 420 +F ء,600;َ,660;ا,720;ل,780;َ,840;ا,900;ء,960;ِ,1020 +E 1 word 1 1020 +F ر,1200;َ,1260;ب,1320;ِ,1380;ك,1440;ُ,1500;م,1560;َ,1620;ا,1680 +E 2 word 2 1680 +F ت,1860;ُ,1920;ك,1980;َ,2040;ذ,2100;ِ,2160;ب,2220;َ,2280;ا,2340;ن,2400 +E 3 word 3 2400 +F خ,2580;َ,2640;ل,2700;َ,2760;ق,2820;َ,2880 +E 4 word 4 2880 +F ل,3060;ء,3120;ِ,3180;ن,3240;س,3300;َ,3360;ا,3420;ن,3480;َ,3540 +E 5 word 5 3540 +F م,3720;ِ,3780;ن,3840 +E 6 word 6 3840 +F ص,4020;َ,4080;ل,4140;ص,4200;َ,4260;ا,4320;ل,4380;ِ,4440;ن,4500 +E 7 word 7 4500 +F ك,4680;َ,4740;ل,4800;ف,4860;َ,4920;خ,4980;َ,5040;ا,5100;ر,5160 +E 8 word 8 5160 +F ف,5340;َ,5400;ب,5460;ِ,5520;ء,5580;َ,5640;ي,5700;ِ,5760 +F ء,5940;َ,6000;ا,6060;ل,6120;َ,6180;ا,6240;ء,6300;ِ,6360 +E 10 mistake 9 6360 SUBSTITUTION +F ر,6540;َ,6600;ب,6660;ِ,6720;ك,6780;ُ,6840;م,6900;َ,6960;ا,7020 +F ت,7200;ُ,7260;ك,7320;َ,7380;ذ,7440;ِ,7500;ب,7560;َ,7620;ا,7680;ن,7740 +E 12 repetition 3 7740 3 +F ر,7920;َ,7980;ب,8040;ُ,8100 +F ل,8280;م,8340;َ,8400;ش,8460;ر,8520;ِ,8580;ق,8640;َ,8700;ي,8760;ن,8820;ِ,8880 +F و,9060;َ,9120;ر,9180;َ,9240;ب,9300;ُ,9360 +F ل,9540;م,9600;َ,9660;غ,9720;ر,9780;ِ,9840;ب,9900;َ,9960;ي,10020;ن,10080 diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_restart.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_restart.tsv new file mode 100644 index 0000000000..5c8b079138 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_restart.tsv @@ -0,0 +1,203 @@ +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَءِنَهُو +W لَلحَقُ +W مِ +W رَبِكَ +W وَمَ +W لَاهُ +W بِغَافِلِن +W عَمَا +W تَعمَلُون +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَحَيثُ +W مَا +W كُنتُم +W فَوَلُو +W وُجُوهَكُم +W شَطرَهُو +W لِءَلَا +W يَكُونَ +W لِنَاسِ +W عَلَيكُم +W حُجَتُن +W ءِلَ +W لَذِينَ +W ظَلَمُو +W مِنهُم +W فَلَا +W تَخشَوهُم +W وَخشَونِي +W وَلِءُتِمَ +W نِعمَتِي +W عَلَيكُم +W وَلَعَلَكُم +W تَهتَدُون +W كَمَا +W ءَرسَلنَا +W فِيكُم +W رَسُولَ +W مِنكُم +W يَتلُو +W عَلَيكُم +W ءَايَاتِنَا +W وَيُزَكِيكُم +W وَيُعَلِمُكُمُ +W لكِتَابَ +W وَلحِكمَتَ +W وَيُعَلِمُكُ +W مَا +W لَم +W تَكُونُو +W تَعلَمُون +W فَذكُرُونِي +W ءَذكُركُم +W وَشكُرُو +W لِي +W وَلَا +W تَكفُرُون +W يَاءَيُهَ +W لَذِينَ +W ءَامَنُ +W ستَعِينُو +W بِصَبرِ +W وَصَلَاتِ +W ءِنَ +W لَاهَ +W مَعَ +W صَابِرِين +A 2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2152,2152,2152,2152,2152,2152,2153,2153,2153,2153,2153,2153,2153,2153,2153,2153 +C max_missed_words=0;skip_ayat=0 +F و,0;َ,60;م,120;ِ,180;ن,240 +E 0 word 0 240 +F ح,420;َ,480;ي,540;ث,600;ُ,660 +E 1 word 1 660 +F خ,840;َ,900;ر,960;َ,1020;ج,1080;ت,1140;َ,1200 +E 2 word 2 1200 +F ف,1380;َ,1440;و,1500;َ,1560;ل,1620;ِ,1680 +E 3 word 3 1680 +F و,1860;َ,1920;ج,1980;ه,2040;َ,2100;ك,2160;َ,2220 +E 4 word 4 2220 +F ش,2400;َ,2460;ط,2520;ر,2580;َ,2640 +E 5 word 5 2640 +F ل,2820;م,2880;َ,2940;س,3000;ج,3060;ِ,3120;د,3180;ِ,3240 +E 6 word 6 3240 +F ل,3420;ح,3480;َ,3540;ر,3600;َ,3660;ا,3720;م,3780;ِ,3840 +E 7 word 7 3840 +F و,4020;َ,4080;ء,4140;ِ,4200;ن,4260;َ,4320;ه,4380;ُ,4440;و,4500 +E 8 word 8 4500 +F ل,4680;َ,4740;ل,4800;ح,4860;َ,4920;ق,4980;ُ,5040 +E 9 word 9 5040 +F م,5220;ِ,5280 +E 10 word 10 5280 +F ر,5460;َ,5520;ب,5580;ِ,5640;ك,5700;َ,5760 +E 11 word 11 5760 +F و,5940;َ,6000;م,6060;ِ,6120;ن,6180 +E 12 repetition 0 6180 0 +F ح,6360;َ,6420;ي,6480;ث,6540;ُ,6600 +E 13 repetition 1 6600 1 +F خ,6780;َ,6840;ر,6900;َ,6960;ج,7020;ت,7080;َ,7140 +E 14 repetition 2 7140 2 +F ف,7320;َ,7380;و,7440;َ,7500;ل,7560;ِ,7620 +E 15 repetition 3 7620 3 +F و,7800;َ,7860;ج,7920;ه,7980;َ,8040;ك,8100;َ,8160 +E 16 repetition 4 8160 4 +F ش,8340;َ,8400;ط,8460;ر,8520;َ,8580 +E 17 repetition 5 8580 5 +F ل,8760;م,8820;َ,8880;س,8940;ج,9000;ِ,9060;د,9120;ِ,9180 +E 18 repetition 6 9180 6 +F ل,9360;ح,9420;َ,9480;ر,9540;َ,9600;ا,9660;م,9720;ِ,9780 +E 19 repetition 7 9780 7 +F و,9960;َ,10020;ء,10080;ِ,10140;ن,10200;َ,10260;ه,10320;ُ,10380;و,10440 +E 20 repetition 8 10440 8 +F ل,10620;َ,10680;ل,10740;ح,10800;َ,10860;ق,10920;ُ,10980 +E 21 repetition 9 10980 9 +F م,11160;ِ,11220 +E 22 repetition 10 11220 10 +F ر,11400;َ,11460;ب,11520;ِ,11580;ك,11640;َ,11700 +E 23 repetition 11 11700 11 +F و,11880;َ,11940;م,12000;َ,12060 +E 24 word 12 12060 +F ل,12240;َ,12300;ا,12360;ه,12420;ُ,12480 +E 25 word 13 12480 +F ب,12660;ِ,12720;غ,12780;َ,12840;ا,12900;ف,12960;ِ,13020;ل,13080;ِ,13140;ن,13200 +E 26 word 14 13200 +F ع,13380;َ,13440;م,13500;َ,13560;ا,13620 +E 27 word 15 13620 +F ت,13800;َ,13860;ع,13920;م,13980;َ,14040;ل,14100;ُ,14160;و,14220;ن,14280 +E 28 word 16 14280 +F و,14460;َ,14520;م,14580;ِ,14640;ن,14700 +E 29 word 17 14700 +F ح,14880;َ,14940;ي,15000;ث,15060;ُ,15120 +E 30 word 18 15120 +F خ,15300;َ,15360;ر,15420;َ,15480;ج,15540;ت,15600;َ,15660 +E 31 word 19 15660 +F ف,15840;َ,15900;و,15960;َ,16020;ل,16080;ِ,16140 +E 32 word 20 16140 +F و,16320;َ,16380;ج,16440;ه,16500;َ,16560;ك,16620;َ,16680 +E 33 word 21 16680 +F ش,16860;َ,16920;ط,16980;ر,17040;َ,17100 +E 34 word 22 17100 +F ل,17280;م,17340;َ,17400;س,17460;ج,17520;ِ,17580;د,17640;ِ,17700 +E 35 word 23 17700 +F ل,17880;ح,17940;َ,18000;ر,18060;َ,18120;ا,18180;م,18240;ِ,18300 +E 36 word 24 18300 +F و,18480;َ,18540;ح,18600;َ,18660;ي,18720;ث,18780;ُ,18840 +E 37 word 25 18840 +F م,19020;َ,19080;ا,19140 +E 38 word 26 19140 +F ك,19320;ُ,19380;ن,19440;ت,19500;ُ,19560;م,19620 +E 39 word 27 19620 +F ف,19800;َ,19860;و,19920;َ,19980;ل,20040;ُ,20100;و,20160 +E 40 word 28 20160 +F و,20340;ُ,20400;ج,20460;ُ,20520;و,20580;ه,20640;َ,20700;ك,20760;ُ,20820;م,20880 +E 41 word 29 20880 +F ش,21060;َ,21120;ط,21180;ر,21240;َ,21300;ه,21360;ُ,21420;و,21480 +E 42 word 30 21480 +F ل,21660;ِ,21720;ء,21780;َ,21840;ل,21900;َ,21960;ا,22020 +E 43 word 31 22020 +F ي,22200;َ,22260;ك,22320;ُ,22380;و,22440;ن,22500;َ,22560 +E 44 word 32 22560 +F ل,22740;ِ,22800;ن,22860;َ,22920;ا,22980;س,23040;ِ,23100 +E 45 word 33 23100 +F ع,23280;َ,23340;ل,23400;َ,23460;ي,23520;ك,23580;ُ,23640;م,23700 +E 46 word 34 23700 +F ح,23880;ُ,23940;ج,24000;َ,24060;ت,24120;ُ,24180;ن,24240 +E 47 word 35 24240 +F ء,24420;ِ,24480;ل,24540;َ,24600 +E 48 word 36 24600 +F ل,24780;َ,24840;ذ,24900;ِ,24960;ي,25020;ن,25080;َ,25140 +E 49 word 37 25140 +F ظ,25320;َ,25380;ل,25440;َ,25500;م,25560;ُ,25620;و,25680 +E 50 word 38 25680 +F م,25860;ِ,25920;ن,25980;ه,26040;ُ,26100;م,26160 +E 51 word 39 26160 +F ف,26340;َ,26400;ل,26460;َ,26520;ا,26580 +E 52 word 40 26580 +F ت,26760;َ,26820;خ,26880;ش,26940;َ,27000;و,27060;ه,27120;ُ,27180;م,27240 +E 53 word 41 27240 +F و,27420;َ,27480;خ,27540;ش,27600;َ,27660;و,27720;ن,27780;ِ,27840;ي,27900 +E 54 word 42 27900 +F و,28080;َ,28140;ل,28200;ِ,28260;ء,28320;ُ,28380;ت,28440;ِ,28500;م,28560;َ,28620 +E 55 word 43 28620 +F ن,28800;ِ,28860;ع,28920;م,28980;َ,29040;ت,29100;ِ,29160;ي,29220 +E 56 word 44 29220 +F ع,29400;َ,29460;ل,29520;َ,29580;ي,29640;ك,29700;ُ,29760;م,29820 +E 57 word 45 29820 +F و,30000;َ,30060;ل,30120;َ,30180;ع,30240;َ,30300;ل,30360;َ,30420;ك,30480;ُ,30540;م,30600 +E 58 word 46 30600 +F ت,30780;َ,30840;ه,30900;ت,30960;َ,31020;د,31080;ُ,31140;و,31200;ن,31260 +E 59 word 47 31260 diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_restart_after_stumble.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_restart_after_stumble.tsv new file mode 100644 index 0000000000..3154fffdbc --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_restart_after_stumble.tsv @@ -0,0 +1,141 @@ +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَءِنَهُو +W لَلحَقُ +W مِ +W رَبِكَ +W وَمَ +W لَاهُ +W بِغَافِلِن +W عَمَا +W تَعمَلُون +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَحَيثُ +W مَا +W كُنتُم +W فَوَلُو +W وُجُوهَكُم +W شَطرَهُو +W لِءَلَا +W يَكُونَ +W لِنَاسِ +W عَلَيكُم +W حُجَتُن +W ءِلَ +W لَذِينَ +W ظَلَمُو +W مِنهُم +W فَلَا +W تَخشَوهُم +W وَخشَونِي +W وَلِءُتِمَ +W نِعمَتِي +W عَلَيكُم +W وَلَعَلَكُم +W تَهتَدُون +W كَمَا +W ءَرسَلنَا +W فِيكُم +W رَسُولَ +W مِنكُم +W يَتلُو +W عَلَيكُم +W ءَايَاتِنَا +W وَيُزَكِيكُم +W وَيُعَلِمُكُمُ +W لكِتَابَ +W وَلحِكمَتَ +W وَيُعَلِمُكُ +W مَا +W لَم +W تَكُونُو +W تَعلَمُون +W فَذكُرُونِي +W ءَذكُركُم +W وَشكُرُو +W لِي +W وَلَا +W تَكفُرُون +W يَاءَيُهَ +W لَذِينَ +W ءَامَنُ +W ستَعِينُو +W بِصَبرِ +W وَصَلَاتِ +W ءِنَ +W لَاهَ +W مَعَ +W صَابِرِين +A 2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2152,2152,2152,2152,2152,2152,2153,2153,2153,2153,2153,2153,2153,2153,2153,2153 +C max_missed_words=2;skip_ayat=0 +F و,0;َ,60;م,120;ِ,180;ن,240 +E 0 word 0 240 +F ح,420;َ,480;ي,540;ث,600;ُ,660 +E 1 word 1 660 +F خ,840;َ,900;ر,960;َ,1020;ج,1080;ت,1140;َ,1200 +E 2 word 2 1200 +F ف,1380;َ,1440;و,1500;َ,1560;ل,1620;ِ,1680 +E 3 word 3 1680 +F و,1860;َ,1920;ج,1980;ه,2040;َ,2100;ك,2160;َ,2220 +E 4 word 4 2220 +F ش,2400;َ,2460;ط,2520;ر,2580;َ,2640 +E 5 word 5 2640 +F ل,2820;م,2880;َ,2940;س,3000;ج,3060;ِ,3120;د,3180;ِ,3240 +E 6 word 6 3240 +F ل,3420;ح,3480;َ,3540;ر,3600;َ,3660;ا,3720;م,3780;ِ,3840 +E 7 word 7 3840 +F و,4020;َ,4080;ء,4140;ِ,4200;ن,4260;َ,4320;ه,4380;ُ,4440;و,4500 +E 8 word 8 4500 +F ل,4680;َ,4740;ل,4800;ح,4860;َ,4920;ق,4980;ُ,5040 +E 9 word 9 5040 +F م,5220;ِ,5280 +E 10 word 10 5280 +F ر,5460;َ,5520;ب,5580;ِ,5640;ك,5700;َ,5760 +E 11 word 11 5760 +F خ,5940;ب,6000;ز,6060;ق,6120;ط,6180;ف,6240 +F و,6420;َ,6480;م,6540;ِ,6600;ن,6660 +E 13 mistake 12 6660 SUBSTITUTION +F ح,6840;َ,6900;ي,6960;ث,7020;ُ,7080 +F خ,7260;َ,7320;ر,7380;َ,7440;ج,7500;ت,7560;َ,7620 +E 15 repetition 0 7620 2 +F ف,7800;َ,7860;و,7920;َ,7980;ل,8040;ِ,8100 +E 16 repetition 3 8100 3 +F و,8280;َ,8340;ج,8400;ه,8460;َ,8520;ك,8580;َ,8640 +E 17 repetition 4 8640 4 +F ش,8820;َ,8880;ط,8940;ر,9000;َ,9060 +E 18 repetition 5 9060 5 +F ل,9240;م,9300;َ,9360;س,9420;ج,9480;ِ,9540;د,9600;ِ,9660 +E 19 repetition 6 9660 6 +F ل,9840;ح,9900;َ,9960;ر,10020;َ,10080;ا,10140;م,10200;ِ,10260 +E 20 repetition 7 10260 7 +F و,10440;َ,10500;ء,10560;ِ,10620;ن,10680;َ,10740;ه,10800;ُ,10860;و,10920 +E 21 repetition 8 10920 8 +F ل,11100;َ,11160;ل,11220;ح,11280;َ,11340;ق,11400;ُ,11460 +E 22 repetition 9 11460 9 +F م,11640;ِ,11700 +E 23 repetition 10 11700 10 +F ر,11880;َ,11940;ب,12000;ِ,12060;ك,12120;َ,12180 +E 24 repetition 11 12180 11 +F و,12360;َ,12420;م,12480;َ,12540 +E 25 word 12 12540 +F ل,12720;َ,12780;ا,12840;ه,12900;ُ,12960 +E 26 word 13 12960 +F ب,13140;ِ,13200;غ,13260;َ,13320;ا,13380;ف,13440;ِ,13500;ل,13560;ِ,13620;ن,13680 +E 27 word 14 13680 +F ع,13860;َ,13920;م,13980;َ,14040;ا,14100 +E 28 word 15 14100 +F ت,14280;َ,14340;ع,14400;م,14460;َ,14520;ل,14580;ُ,14640;و,14700;ن,14760 +E 29 word 16 14760 diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_restart_after_stumble_salah.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_restart_after_stumble_salah.tsv new file mode 100644 index 0000000000..38bcc83f63 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_restart_after_stumble_salah.tsv @@ -0,0 +1,140 @@ +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَءِنَهُو +W لَلحَقُ +W مِ +W رَبِكَ +W وَمَ +W لَاهُ +W بِغَافِلِن +W عَمَا +W تَعمَلُون +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَحَيثُ +W مَا +W كُنتُم +W فَوَلُو +W وُجُوهَكُم +W شَطرَهُو +W لِءَلَا +W يَكُونَ +W لِنَاسِ +W عَلَيكُم +W حُجَتُن +W ءِلَ +W لَذِينَ +W ظَلَمُو +W مِنهُم +W فَلَا +W تَخشَوهُم +W وَخشَونِي +W وَلِءُتِمَ +W نِعمَتِي +W عَلَيكُم +W وَلَعَلَكُم +W تَهتَدُون +W كَمَا +W ءَرسَلنَا +W فِيكُم +W رَسُولَ +W مِنكُم +W يَتلُو +W عَلَيكُم +W ءَايَاتِنَا +W وَيُزَكِيكُم +W وَيُعَلِمُكُمُ +W لكِتَابَ +W وَلحِكمَتَ +W وَيُعَلِمُكُ +W مَا +W لَم +W تَكُونُو +W تَعلَمُون +W فَذكُرُونِي +W ءَذكُركُم +W وَشكُرُو +W لِي +W وَلَا +W تَكفُرُون +W يَاءَيُهَ +W لَذِينَ +W ءَامَنُ +W ستَعِينُو +W بِصَبرِ +W وَصَلَاتِ +W ءِنَ +W لَاهَ +W مَعَ +W صَابِرِين +A 2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2152,2152,2152,2152,2152,2152,2153,2153,2153,2153,2153,2153,2153,2153,2153,2153 +F و,0;َ,60;م,120;ِ,180;ن,240 +E 0 word 0 240 +F ح,420;َ,480;ي,540;ث,600;ُ,660 +E 1 word 1 660 +F خ,840;َ,900;ر,960;َ,1020;ج,1080;ت,1140;َ,1200 +E 2 word 2 1200 +F ف,1380;َ,1440;و,1500;َ,1560;ل,1620;ِ,1680 +E 3 word 3 1680 +F و,1860;َ,1920;ج,1980;ه,2040;َ,2100;ك,2160;َ,2220 +E 4 word 4 2220 +F ش,2400;َ,2460;ط,2520;ر,2580;َ,2640 +E 5 word 5 2640 +F ل,2820;م,2880;َ,2940;س,3000;ج,3060;ِ,3120;د,3180;ِ,3240 +E 6 word 6 3240 +F ل,3420;ح,3480;َ,3540;ر,3600;َ,3660;ا,3720;م,3780;ِ,3840 +E 7 word 7 3840 +F و,4020;َ,4080;ء,4140;ِ,4200;ن,4260;َ,4320;ه,4380;ُ,4440;و,4500 +E 8 word 8 4500 +F ل,4680;َ,4740;ل,4800;ح,4860;َ,4920;ق,4980;ُ,5040 +E 9 word 9 5040 +F م,5220;ِ,5280 +E 10 word 10 5280 +F ر,5460;َ,5520;ب,5580;ِ,5640;ك,5700;َ,5760 +E 11 word 11 5760 +F خ,5940;ب,6000;ز,6060;ق,6120;ط,6180;ف,6240 +F و,6420;َ,6480;م,6540;ِ,6600;ن,6660 +E 13 mistake 12 6660 SUBSTITUTION +F ح,6840;َ,6900;ي,6960;ث,7020;ُ,7080 +F خ,7260;َ,7320;ر,7380;َ,7440;ج,7500;ت,7560;َ,7620 +E 15 repetition 0 7620 2 +F ف,7800;َ,7860;و,7920;َ,7980;ل,8040;ِ,8100 +E 16 repetition 3 8100 3 +F و,8280;َ,8340;ج,8400;ه,8460;َ,8520;ك,8580;َ,8640 +E 17 repetition 4 8640 4 +F ش,8820;َ,8880;ط,8940;ر,9000;َ,9060 +E 18 repetition 5 9060 5 +F ل,9240;م,9300;َ,9360;س,9420;ج,9480;ِ,9540;د,9600;ِ,9660 +E 19 repetition 6 9660 6 +F ل,9840;ح,9900;َ,9960;ر,10020;َ,10080;ا,10140;م,10200;ِ,10260 +E 20 repetition 7 10260 7 +F و,10440;َ,10500;ء,10560;ِ,10620;ن,10680;َ,10740;ه,10800;ُ,10860;و,10920 +E 21 repetition 8 10920 8 +F ل,11100;َ,11160;ل,11220;ح,11280;َ,11340;ق,11400;ُ,11460 +E 22 repetition 9 11460 9 +F م,11640;ِ,11700 +E 23 repetition 10 11700 10 +F ر,11880;َ,11940;ب,12000;ِ,12060;ك,12120;َ,12180 +E 24 repetition 11 12180 11 +F و,12360;َ,12420;م,12480;َ,12540 +E 25 word 12 12540 +F ل,12720;َ,12780;ا,12840;ه,12900;ُ,12960 +E 26 word 13 12960 +F ب,13140;ِ,13200;غ,13260;َ,13320;ا,13380;ف,13440;ِ,13500;ل,13560;ِ,13620;ن,13680 +E 27 word 14 13680 +F ع,13860;َ,13920;م,13980;َ,14040;ا,14100 +E 28 word 15 14100 +F ت,14280;َ,14340;ع,14400;م,14460;َ,14520;ل,14580;ُ,14640;و,14700;ن,14760 +E 29 word 16 14760 diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_unheard_last_word_loose.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_unheard_last_word_loose.tsv new file mode 100644 index 0000000000..d286311087 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_unheard_last_word_loose.tsv @@ -0,0 +1,174 @@ +W وَلِكُلِو +W وِجهَتُن +W هُوَ +W مُوَلِيهَا +W فَستَبِقُ +W لخَيرَاتِ +W ءَينَ +W مَا +W تَكُونُو +W يَءتِ +W بِكُمُ +W لَاهُ +W جَمِيعَن +W ءِنَ +W لَاهَ +W عَلَا +W كُلِ +W شَيءِن +W قَدِير +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَءِنَهُو +W لَلحَقُ +W مِ +W رَبِكَ +W وَمَ +W لَاهُ +W بِغَافِلِن +W عَمَا +W تَعمَلُون +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَحَيثُ +W مَا +W كُنتُم +W فَوَلُو +W وُجُوهَكُم +W شَطرَهُو +W لِءَلَا +W يَكُونَ +W لِنَاسِ +W عَلَيكُم +W حُجَتُن +W ءِلَ +W لَذِينَ +W ظَلَمُو +W مِنهُم +W فَلَا +W تَخشَوهُم +W وَخشَونِي +W وَلِءُتِمَ +W نِعمَتِي +W عَلَيكُم +W وَلَعَلَكُم +W تَهتَدُون +W كَمَا +W ءَرسَلنَا +W فِيكُم +W رَسُولَ +W مِنكُم +W يَتلُو +W عَلَيكُم +W ءَايَاتِنَا +W وَيُزَكِيكُم +W وَيُعَلِمُكُمُ +W لكِتَابَ +W وَلحِكمَتَ +W وَيُعَلِمُكُ +W مَا +W لَم +W تَكُونُو +W تَعلَمُون +W فَذكُرُونِي +W ءَذكُركُم +W وَشكُرُو +W لِي +W وَلَا +W تَكفُرُون +W يَاءَيُهَ +W لَذِينَ +W ءَامَنُ +W ستَعِينُو +W بِصَبرِ +W وَصَلَاتِ +W ءِنَ +W لَاهَ +W مَعَ +W صَابِرِين +A 2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2152,2152,2152,2152,2152,2152,2153,2153,2153,2153,2153,2153,2153,2153,2153,2153 +C max_missed_words=2;skip_ayat=0 +F و,0;َ,60;ل,120;ِ,180;ك,240;ُ,300;ل,360;ِ,420;و,480 +E 0 word 0 480 +F و,660;ِ,720;ج,780;ه,840;َ,900;ت,960;ُ,1020;ن,1080 +E 1 word 1 1080 +F ه,1260;ُ,1320;و,1380;َ,1440 +E 2 word 2 1440 +F م,1620;ُ,1680;و,1740;َ,1800;ل,1860;ِ,1920;ي,1980;ه,2040;َ,2100;ا,2160 +E 3 word 3 2160 +F ف,2340;َ,2400;س,2460;ت,2520;َ,2580;ب,2640;ِ,2700;ق,2760;ُ,2820 +E 4 word 4 2820 +F ل,3000;خ,3060;َ,3120;ي,3180;ر,3240;َ,3300;ا,3360;ت,3420;ِ,3480 +E 5 word 5 3480 +F ء,3660;َ,3720;ي,3780;ن,3840;َ,3900 +E 6 word 6 3900 +F م,4080;َ,4140;ا,4200 +E 7 word 7 4200 +F ت,4380;َ,4440;ك,4500;ُ,4560;و,4620;ن,4680;ُ,4740;و,4800 +E 8 word 8 4800 +F ي,4980;َ,5040;ء,5100;ت,5160;ِ,5220 +E 9 word 9 5220 +F ب,5400;ِ,5460;ك,5520;ُ,5580;م,5640;ُ,5700 +E 10 word 10 5700 +F ل,5880;َ,5940;ا,6000;ه,6060;ُ,6120 +E 11 word 11 6120 +F ج,6300;َ,6360;م,6420;ِ,6480;ي,6540;ع,6600;َ,6660;ن,6720 +E 12 word 12 6720 +F ء,6900;ِ,6960;ن,7020;َ,7080 +E 13 word 13 7080 +F ل,7260;َ,7320;ا,7380;ه,7440;َ,7500 +E 14 word 14 7500 +F ع,7680;َ,7740;ل,7800;َ,7860;ا,7920 +E 15 word 15 7920 +F ك,8100;ُ,8160;ل,8220;ِ,8280 +E 16 word 16 8280 +F ش,8460;َ,8520;ي,8580;ء,8640;ِ,8700;ن,8760 +E 17 word 17 8760 +F و,8940;َ,9000;م,9060;ِ,9120;ن,9180 +F ح,9360;َ,9420;ي,9480;ث,9540;ُ,9600 +E 19 mistake 18 9600 SUBSTITUTION +F خ,9780;َ,9840;ر,9900;َ,9960;ج,10020;ت,10080;َ,10140 +E 20 missed 18 10140 +E 20 word 19 9180 +E 20 word 20 9600 +E 20 word 21 10140 +F ف,10320;َ,10380;و,10440;َ,10500;ل,10560;ِ,10620 +E 21 word 22 10620 +F و,10800;َ,10860;ج,10920;ه,10980;َ,11040;ك,11100;َ,11160 +E 22 word 23 11160 +F ش,11340;َ,11400;ط,11460;ر,11520;َ,11580 +E 23 word 24 11580 +F ل,11760;م,11820;َ,11880;س,11940;ج,12000;ِ,12060;د,12120;ِ,12180 +E 24 word 25 12180 +F ل,12360;ح,12420;َ,12480;ر,12540;َ,12600;ا,12660;م,12720;ِ,12780 +E 25 word 26 12780 +F و,12960;َ,13020;ء,13080;ِ,13140;ن,13200;َ,13260;ه,13320;ُ,13380;و,13440 +E 26 word 27 13440 +F ل,13620;َ,13680;ل,13740;ح,13800;َ,13860;ق,13920;ُ,13980 +E 27 word 28 13980 +F م,14160;ِ,14220 +E 28 word 29 14220 +F ر,14400;َ,14460;ب,14520;ِ,14580;ك,14640;َ,14700 +E 29 word 30 14700 +F و,14880;َ,14940;م,15000;َ,15060 +E 30 word 31 15060 +F ل,15240;َ,15300;ا,15360;ه,15420;ُ,15480 +E 31 word 32 15480 +F ب,15660;ِ,15720;غ,15780;َ,15840;ا,15900;ف,15960;ِ,16020;ل,16080;ِ,16140;ن,16200 +E 32 word 33 16200 +F ع,16380;َ,16440;م,16500;َ,16560;ا,16620 +E 33 word 34 16620 +F ت,16800;َ,16860;ع,16920;م,16980;َ,17040;ل,17100;ُ,17160;و,17220;ن,17280 +E 34 word 35 17280 diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_unheard_last_word_strict.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_unheard_last_word_strict.tsv new file mode 100644 index 0000000000..a3715fb8f5 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_unheard_last_word_strict.tsv @@ -0,0 +1,157 @@ +W وَلِكُلِو +W وِجهَتُن +W هُوَ +W مُوَلِيهَا +W فَستَبِقُ +W لخَيرَاتِ +W ءَينَ +W مَا +W تَكُونُو +W يَءتِ +W بِكُمُ +W لَاهُ +W جَمِيعَن +W ءِنَ +W لَاهَ +W عَلَا +W كُلِ +W شَيءِن +W قَدِير +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَءِنَهُو +W لَلحَقُ +W مِ +W رَبِكَ +W وَمَ +W لَاهُ +W بِغَافِلِن +W عَمَا +W تَعمَلُون +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَحَيثُ +W مَا +W كُنتُم +W فَوَلُو +W وُجُوهَكُم +W شَطرَهُو +W لِءَلَا +W يَكُونَ +W لِنَاسِ +W عَلَيكُم +W حُجَتُن +W ءِلَ +W لَذِينَ +W ظَلَمُو +W مِنهُم +W فَلَا +W تَخشَوهُم +W وَخشَونِي +W وَلِءُتِمَ +W نِعمَتِي +W عَلَيكُم +W وَلَعَلَكُم +W تَهتَدُون +W كَمَا +W ءَرسَلنَا +W فِيكُم +W رَسُولَ +W مِنكُم +W يَتلُو +W عَلَيكُم +W ءَايَاتِنَا +W وَيُزَكِيكُم +W وَيُعَلِمُكُمُ +W لكِتَابَ +W وَلحِكمَتَ +W وَيُعَلِمُكُ +W مَا +W لَم +W تَكُونُو +W تَعلَمُون +W فَذكُرُونِي +W ءَذكُركُم +W وَشكُرُو +W لِي +W وَلَا +W تَكفُرُون +W يَاءَيُهَ +W لَذِينَ +W ءَامَنُ +W ستَعِينُو +W بِصَبرِ +W وَصَلَاتِ +W ءِنَ +W لَاهَ +W مَعَ +W صَابِرِين +A 2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2152,2152,2152,2152,2152,2152,2153,2153,2153,2153,2153,2153,2153,2153,2153,2153 +C max_missed_words=0;skip_ayat=0 +F و,0;َ,60;ل,120;ِ,180;ك,240;ُ,300;ل,360;ِ,420;و,480 +E 0 word 0 480 +F و,660;ِ,720;ج,780;ه,840;َ,900;ت,960;ُ,1020;ن,1080 +E 1 word 1 1080 +F ه,1260;ُ,1320;و,1380;َ,1440 +E 2 word 2 1440 +F م,1620;ُ,1680;و,1740;َ,1800;ل,1860;ِ,1920;ي,1980;ه,2040;َ,2100;ا,2160 +E 3 word 3 2160 +F ف,2340;َ,2400;س,2460;ت,2520;َ,2580;ب,2640;ِ,2700;ق,2760;ُ,2820 +E 4 word 4 2820 +F ل,3000;خ,3060;َ,3120;ي,3180;ر,3240;َ,3300;ا,3360;ت,3420;ِ,3480 +E 5 word 5 3480 +F ء,3660;َ,3720;ي,3780;ن,3840;َ,3900 +E 6 word 6 3900 +F م,4080;َ,4140;ا,4200 +E 7 word 7 4200 +F ت,4380;َ,4440;ك,4500;ُ,4560;و,4620;ن,4680;ُ,4740;و,4800 +E 8 word 8 4800 +F ي,4980;َ,5040;ء,5100;ت,5160;ِ,5220 +E 9 word 9 5220 +F ب,5400;ِ,5460;ك,5520;ُ,5580;م,5640;ُ,5700 +E 10 word 10 5700 +F ل,5880;َ,5940;ا,6000;ه,6060;ُ,6120 +E 11 word 11 6120 +F ج,6300;َ,6360;م,6420;ِ,6480;ي,6540;ع,6600;َ,6660;ن,6720 +E 12 word 12 6720 +F ء,6900;ِ,6960;ن,7020;َ,7080 +E 13 word 13 7080 +F ل,7260;َ,7320;ا,7380;ه,7440;َ,7500 +E 14 word 14 7500 +F ع,7680;َ,7740;ل,7800;َ,7860;ا,7920 +E 15 word 15 7920 +F ك,8100;ُ,8160;ل,8220;ِ,8280 +E 16 word 16 8280 +F ش,8460;َ,8520;ي,8580;ء,8640;ِ,8700;ن,8760 +E 17 word 17 8760 +F و,8940;َ,9000;م,9060;ِ,9120;ن,9180 +F ح,9360;َ,9420;ي,9480;ث,9540;ُ,9600 +E 19 mistake 18 9600 SUBSTITUTION +F خ,9780;َ,9840;ر,9900;َ,9960;ج,10020;ت,10080;َ,10140 +F ف,10320;َ,10380;و,10440;َ,10500;ل,10560;ِ,10620 +F و,10800;َ,10860;ج,10920;ه,10980;َ,11040;ك,11100;َ,11160 +F ش,11340;َ,11400;ط,11460;ر,11520;َ,11580 +F ل,11760;م,11820;َ,11880;س,11940;ج,12000;ِ,12060;د,12120;ِ,12180 +F ل,12360;ح,12420;َ,12480;ر,12540;َ,12600;ا,12660;م,12720;ِ,12780 +F و,12960;َ,13020;ء,13080;ِ,13140;ن,13200;َ,13260;ه,13320;ُ,13380;و,13440 +F ل,13620;َ,13680;ل,13740;ح,13800;َ,13860;ق,13920;ُ,13980 +F م,14160;ِ,14220 +F ر,14400;َ,14460;ب,14520;ِ,14580;ك,14640;َ,14700 +F و,14880;َ,14940;م,15000;َ,15060 +F ل,15240;َ,15300;ا,15360;ه,15420;ُ,15480 +F ب,15660;ِ,15720;غ,15780;َ,15840;ا,15900;ف,15960;ِ,16020;ل,16080;ِ,16140;ن,16200 +F ع,16380;َ,16440;م,16500;َ,16560;ا,16620 +E 33 repetition 15 16620 15 +F ت,16800;َ,16860;ع,16920;م,16980;َ,17040;ل,17100;ُ,17160;و,17220;ن,17280 diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_unrecognizable_loose.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_unrecognizable_loose.tsv new file mode 100644 index 0000000000..38895535c8 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_unrecognizable_loose.tsv @@ -0,0 +1,130 @@ +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَءِنَهُو +W لَلحَقُ +W مِ +W رَبِكَ +W وَمَ +W لَاهُ +W بِغَافِلِن +W عَمَا +W تَعمَلُون +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَحَيثُ +W مَا +W كُنتُم +W فَوَلُو +W وُجُوهَكُم +W شَطرَهُو +W لِءَلَا +W يَكُونَ +W لِنَاسِ +W عَلَيكُم +W حُجَتُن +W ءِلَ +W لَذِينَ +W ظَلَمُو +W مِنهُم +W فَلَا +W تَخشَوهُم +W وَخشَونِي +W وَلِءُتِمَ +W نِعمَتِي +W عَلَيكُم +W وَلَعَلَكُم +W تَهتَدُون +W كَمَا +W ءَرسَلنَا +W فِيكُم +W رَسُولَ +W مِنكُم +W يَتلُو +W عَلَيكُم +W ءَايَاتِنَا +W وَيُزَكِيكُم +W وَيُعَلِمُكُمُ +W لكِتَابَ +W وَلحِكمَتَ +W وَيُعَلِمُكُ +W مَا +W لَم +W تَكُونُو +W تَعلَمُون +W فَذكُرُونِي +W ءَذكُركُم +W وَشكُرُو +W لِي +W وَلَا +W تَكفُرُون +W يَاءَيُهَ +W لَذِينَ +W ءَامَنُ +W ستَعِينُو +W بِصَبرِ +W وَصَلَاتِ +W ءِنَ +W لَاهَ +W مَعَ +W صَابِرِين +A 2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2152,2152,2152,2152,2152,2152,2153,2153,2153,2153,2153,2153,2153,2153,2153,2153 +C max_missed_words=2;skip_ayat=0 +F و,0;َ,60;م,120;ِ,180;ن,240 +E 0 word 0 240 +F ح,420;َ,480;ي,540;ث,600;ُ,660 +E 1 word 1 660 +F خ,840;َ,900;ر,960;َ,1020;ج,1080;ت,1140;َ,1200 +E 2 word 2 1200 +F ف,1380;َ,1440;و,1500;َ,1560;ل,1620;ِ,1680 +E 3 word 3 1680 +F و,1860;َ,1920;ج,1980;ه,2040;َ,2100;ك,2160;َ,2220 +E 4 word 4 2220 +F ش,2400;َ,2460;ط,2520;ر,2580;َ,2640 +E 5 word 5 2640 +F ه,2820;ص,2880;ُ,2940;ن,3000;ف,3060;َ,3120;غ,3180;َ,3240 +F ه,3420;ظ,3480;ُ,3540;ط,3600;ُ,3660;ا,3720;ص,3780;َ,3840 +E 7 mistake 6 3840 SUBSTITUTION +F ر,4020;ُ,4080;ء,4140;َ,4200;ز,4260;ُ,4320;خ,4380;ِ,4440;ر,4500 +F ه,4680;ُ,4740;ه,4800;ظ,4860;ُ,4920;ت,4980;ِ,5040 +F ص,5220;َ,5280 +F ر,5460;َ,5520;ب,5580;ِ,5640;ك,5700;َ,5760 +F و,5940;َ,6000;م,6060;َ,6120 +F ل,6300;َ,6360;ا,6420;ه,6480;ُ,6540 +E 13 missed 6 6540 +E 13 word 7 6540 ctx +E 13 word 8 6540 ctx +E 13 word 9 6540 rec +E 13 word 10 6540 rec +E 13 word 11 6540 rec +E 13 word 12 6540 rec +E 13 word 13 6540 rec +F ب,6720;ِ,6780;غ,6840;َ,6900;ا,6960;ف,7020;ِ,7080;ل,7140;ِ,7200;ن,7260 +E 14 word 14 7260 +F ع,7440;َ,7500;م,7560;َ,7620;ا,7680 +E 15 word 15 7680 +F ت,7860;َ,7920;ع,7980;م,8040;َ,8100;ل,8160;ُ,8220;و,8280;ن,8340 +E 16 word 16 8340 +F و,8520;َ,8580;م,8640;ِ,8700;ن,8760 +E 17 word 17 8760 +F ح,8940;َ,9000;ي,9060;ث,9120;ُ,9180 +E 18 word 18 9180 +F خ,9360;َ,9420;ر,9480;َ,9540;ج,9600;ت,9660;َ,9720 +E 19 word 19 9720 +F ف,9900;َ,9960;و,10020;َ,10080;ل,10140;ِ,10200 +E 20 word 20 10200 +F و,10380;َ,10440;ج,10500;ه,10560;َ,10620;ك,10680;َ,10740 +E 21 word 21 10740 +F ش,10920;َ,10980;ط,11040;ر,11100;َ,11160 +E 22 word 22 11160 diff --git a/feature/memorize/tracker/src/test/resources/golden/ayat_unrecognizable_strict.tsv b/feature/memorize/tracker/src/test/resources/golden/ayat_unrecognizable_strict.tsv new file mode 100644 index 0000000000..e9762ee9b1 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/ayat_unrecognizable_strict.tsv @@ -0,0 +1,118 @@ +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَءِنَهُو +W لَلحَقُ +W مِ +W رَبِكَ +W وَمَ +W لَاهُ +W بِغَافِلِن +W عَمَا +W تَعمَلُون +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَحَيثُ +W مَا +W كُنتُم +W فَوَلُو +W وُجُوهَكُم +W شَطرَهُو +W لِءَلَا +W يَكُونَ +W لِنَاسِ +W عَلَيكُم +W حُجَتُن +W ءِلَ +W لَذِينَ +W ظَلَمُو +W مِنهُم +W فَلَا +W تَخشَوهُم +W وَخشَونِي +W وَلِءُتِمَ +W نِعمَتِي +W عَلَيكُم +W وَلَعَلَكُم +W تَهتَدُون +W كَمَا +W ءَرسَلنَا +W فِيكُم +W رَسُولَ +W مِنكُم +W يَتلُو +W عَلَيكُم +W ءَايَاتِنَا +W وَيُزَكِيكُم +W وَيُعَلِمُكُمُ +W لكِتَابَ +W وَلحِكمَتَ +W وَيُعَلِمُكُ +W مَا +W لَم +W تَكُونُو +W تَعلَمُون +W فَذكُرُونِي +W ءَذكُركُم +W وَشكُرُو +W لِي +W وَلَا +W تَكفُرُون +W يَاءَيُهَ +W لَذِينَ +W ءَامَنُ +W ستَعِينُو +W بِصَبرِ +W وَصَلَاتِ +W ءِنَ +W لَاهَ +W مَعَ +W صَابِرِين +A 2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2152,2152,2152,2152,2152,2152,2153,2153,2153,2153,2153,2153,2153,2153,2153,2153 +C max_missed_words=0;skip_ayat=0 +F و,0;َ,60;م,120;ِ,180;ن,240 +E 0 word 0 240 +F ح,420;َ,480;ي,540;ث,600;ُ,660 +E 1 word 1 660 +F خ,840;َ,900;ر,960;َ,1020;ج,1080;ت,1140;َ,1200 +E 2 word 2 1200 +F ف,1380;َ,1440;و,1500;َ,1560;ل,1620;ِ,1680 +E 3 word 3 1680 +F و,1860;َ,1920;ج,1980;ه,2040;َ,2100;ك,2160;َ,2220 +E 4 word 4 2220 +F ش,2400;َ,2460;ط,2520;ر,2580;َ,2640 +E 5 word 5 2640 +F ه,2820;ص,2880;ُ,2940;ن,3000;ف,3060;َ,3120;غ,3180;َ,3240 +F ه,3420;ظ,3480;ُ,3540;ط,3600;ُ,3660;ا,3720;ص,3780;َ,3840 +E 7 mistake 6 3840 SUBSTITUTION +F ر,4020;ُ,4080;ء,4140;َ,4200;ز,4260;ُ,4320;خ,4380;ِ,4440;ر,4500 +F ه,4680;ُ,4740;ه,4800;ظ,4860;ُ,4920;ت,4980;ِ,5040 +F ص,5220;َ,5280 +F ر,5460;َ,5520;ب,5580;ِ,5640;ك,5700;َ,5760 +F و,5940;َ,6000;م,6060;َ,6120 +F ل,6300;َ,6360;ا,6420;ه,6480;ُ,6540 +F ب,6720;ِ,6780;غ,6840;َ,6900;ا,6960;ف,7020;ِ,7080;ل,7140;ِ,7200;ن,7260 +F ع,7440;َ,7500;م,7560;َ,7620;ا,7680 +F ت,7860;َ,7920;ع,7980;م,8040;َ,8100;ل,8160;ُ,8220;و,8280;ن,8340 +F و,8520;َ,8580;م,8640;ِ,8700;ن,8760 +F ح,8940;َ,9000;ي,9060;ث,9120;ُ,9180 +E 18 repetition 1 9180 1 +F خ,9360;َ,9420;ر,9480;َ,9540;ج,9600;ت,9660;َ,9720 +E 19 repetition 2 9720 2 +F ف,9900;َ,9960;و,10020;َ,10080;ل,10140;ِ,10200 +E 20 repetition 3 10200 3 +F و,10380;َ,10440;ج,10500;ه,10560;َ,10620;ك,10680;َ,10740 +E 21 repetition 4 10740 4 +F ش,10920;َ,10980;ط,11040;ر,11100;َ,11160 +E 22 repetition 5 11160 5 diff --git a/feature/memorize/tracker/src/test/resources/golden/live_mi11_27_30_basmala.tsv b/feature/memorize/tracker/src/test/resources/golden/live_mi11_27_30_basmala.tsv new file mode 100644 index 0000000000..bd8c962725 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/live_mi11_27_30_basmala.tsv @@ -0,0 +1,117 @@ +W ءنهو +W من +W سليمان +W وءنهو +W بسم +W لاه +W رحمان +W رحيم +W ءلا +W تعلو +W علي +W وءتوني +W مسلمين +W قالت +W ياءيه +W لملء +W ءفتوني +W في +W ءمري +W ما +W كنت +W قاطعتن +W ءمرن +W حتا +W تشهدون +W قالو +W نحن +W ءلو +W قوتو +W وءلو +W بءسن +W شديدو +W ولءمر +W ءليك +W فنظري +W ماذا +W تءمرين +W قالت +W ءن +W لملوك +W ءذا +W دخلو +W قريتن +W ءفسدوها +W وجعلو +W ءعزت +W ءهلها +W ءذلتو +W وكذالك +W يفعلون +P isti'adha ءعوذبلاهمنشيطانرجيم +P basmala بسملاهرحمانرحيم +A 27030,27030,27030,27030,27030,27030,27030,27030,27031,27031,27031,27031,27031,27032,27032,27032,27032,27032,27032,27032,27032,27032,27032,27032,27032,27033,27033,27033,27033,27033,27033,27033,27033,27033,27033,27033,27033,27034,27034,27034,27034,27034,27034,27034,27034,27034,27034,27034,27034,27034 +C max_missed_words=2;skip_ayat=0 +F ء,71700 +F ن,72700 +F ه,73200 +S +F و,73600 +E 4 word 0 73600 +F م,74100 +F ن,75100;س,75100 +E 6 word 1 75100 +F ل,75600 +F ي,76000;م,76000 +F ا,77000;ن,77000 +E 9 word 2 77000 +F و,77500 +S +F ء,78000 +F ن,78900 +S +F ه,79400 +F و,79900;ب,79900 +E 16 word 3 79900 +F س,80400 +F م,80800 +E 18 word 4 80800 +F ل,81300 +F ا,81800 +F ه,82300 +E 21 word 5 82300 +S +F ر,83200;ح,83200 +F م,83700 +F ا,84200 +F ن,84700 +E 26 word 6 84700 +F ر,85200 +F ح,85600 +S +S +F ء,90900 +F ل,91400 +E 32 word 7 85600 +F ا,92400;ت,92400 +E 33 word 8 92400 +F ع,92800 +S +F ل,93300 +F و,93800 +E 37 word 9 93800 +F ع,94300;ل,94300 +F ي,95200 +E 39 word 10 95200 +F و,95700 +S +F ء,96200;ت,96200 +F و,97200;ن,97200 +S +F ف,101000 +S +F ق,107200;ا,107200 +F ل,107700 +E 48 mistake 11 107700 SUBSTITUTION +F ت,108200 +F ي,108700 diff --git a/feature/memorize/tracker/src/test/resources/golden/real_husary_2_149_left_out.tsv b/feature/memorize/tracker/src/test/resources/golden/real_husary_2_149_left_out.tsv new file mode 100644 index 0000000000..0473636049 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/real_husary_2_149_left_out.tsv @@ -0,0 +1,248 @@ +W وَلِكُلِو +W وِجهَتُن +W هُوَ +W مُوَلِيهَا +W فَستَبِقُ +W لخَيرَاتِ +W ءَينَ +W مَا +W تَكُونُو +W يَءتِ +W بِكُمُ +W لَاهُ +W جَمِيعَن +W ءِنَ +W لَاهَ +W عَلَا +W كُلِ +W شَيءِن +W قَدِير +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَءِنَهُو +W لَلحَقُ +W مِ +W رَبِكَ +W وَمَ +W لَاهُ +W بِغَافِلِن +W عَمَا +W تَعمَلُون +W وَمِن +W حَيثُ +W خَرَجتَ +W فَوَلِ +W وَجهَكَ +W شَطرَ +W لمَسجِدِ +W لحَرَامِ +W وَحَيثُ +W مَا +W كُنتُم +W فَوَلُو +W وُجُوهَكُم +W شَطرَهُو +W لِءَلَا +W يَكُونَ +W لِنَاسِ +W عَلَيكُم +W حُجَتُن +W ءِلَ +W لَذِينَ +W ظَلَمُو +W مِنهُم +W فَلَا +W تَخشَوهُم +W وَخشَونِي +W وَلِءُتِمَ +W نِعمَتِي +W عَلَيكُم +W وَلَعَلَكُم +W تَهتَدُون +W كَمَا +W ءَرسَلنَا +W فِيكُم +W رَسُولَ +W مِنكُم +W يَتلُو +W عَلَيكُم +W ءَايَاتِنَا +W وَيُزَكِيكُم +W وَيُعَلِمُكُمُ +W لكِتَابَ +W وَلحِكمَتَ +W وَيُعَلِمُكُ +W مَا +W لَم +W تَكُونُو +W تَعلَمُون +A 2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2148,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2149,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2150,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151,2151 +C max_missed_words=2;skip_ayat=0 +F و,240;َ,240 +F ل,520;ِ,520;ك,800;ُ,800 +F ل,1240;ِ,1240 +F و,2080;ِ,2080;ج,2240 +E 3 word 0 1240 +F ه,2440;َ,2440;ت,2760;ُ,2760 +F ن,3080 +E 5 word 1 3080 +F ه,3360;ُ,3360;و,3520;َ,3520 +E 6 word 2 3520 +F م,3840;ُ,3840;و,4040;َ,4040 +F ل,4640;ِ,4640 +F ي,4960 +F ه,5280;َ,5280;ا,5480 +E 10 word 3 5480 +F ف,7200;َ,7200;س,7520 +F ت,7680;َ,7680;ب,7920;ِ,7920 +F ق,8200;ُ,8200;ل,8520 +E 13 word 4 8200 +F خ,8800;َ,8800;ي,9040 +F ر,9360;َ,9360 +F ا,10480 +F ت,10680;ِ,10680 +E 17 word 5 10680 +F ء,12240;َ,12240 +F ي,12480;ن,12600;َ,12600 +E 19 word 6 12600 +F م,12960;َ,12960;ا,13200 +E 20 word 7 13200 +F ت,13440;َ,13440;ك,13800;ُ,13800 +F و,14000;ن,14240;ُ,14240 +F و,14600;ي,14800;َ,14800 +E 23 word 8 14600 +F ء,15040;ت,15240;ِ,15240 +E 24 word 9 15240 +F ب,15480;ِ,15480 +F ك,15840;ُ,15840;م,16000;ُ,16000 +E 26 word 10 16000 +F ل,16520;َ,16520 +F ا,16800;ه,16960;ُ,16960 +E 28 word 11 16960 +F ج,17280;َ,17280;م,17520;ِ,17520 +F ي,17840;ع,18120;َ,18120 +F ا,19480 +F ء,20720;ِ,20720 +E 32 word 12 19480 +F ن,21720;َ,21720 +E 33 word 13 21720 +F ل,22280;َ,22280 +F ا,22560;ه,22680;َ,22680 +E 35 word 14 22680 +F ع,23040;َ,23040;ل,23320;َ,23320 +F ا,23560;ك,23840;ُ,23840 +E 37 word 15 23560 +F ل,24200;ِ,24200 +E 38 word 16 24200 +F ش,24560;َ,24560;ي,24760 +F ء,24960;ِ,24960 +F ن,25920;ق,26160;َ,26160 +E 41 word 17 25920 +F د,26440;ِ,26440 +F ي,27760 +F ر,27840 +E 44 word 18 27840 +F و,28760;َ,28760 +F م,28960;ِ,28960;ن,29200 +E 46 word 19 29200 +F ح,29440;َ,29440;ي,29600 +F ث,29880;ُ,29880;خ,30160;َ,30160 +E 48 word 20 29880 +F ر,30440;َ,30440;ج,30680 +F ت,30880;َ,30880 +E 50 word 21 30880 +F ف,31200;َ,31200;و,31440;َ,31440 +F ل,31880;ِ,31880 +E 52 word 22 31880 +F و,32160;َ,32160;ج,32400;ه,32560;َ,32560 +F ك,32880;َ,32880 +E 54 word 23 32880 +F ش,33160;َ,33160;ط,33440 +F ر,33640;َ,33640;ل,34000 +E 56 word 24 33640 +F م,34160;َ,34160;س,34520 +F ج,34680;ِ,34680;د,34960;ِ,34960 +E 58 word 25 34960 +F ل,35280 +F ح,35520;َ,35520;ر,35800;َ,35800 +F ا,37200;م,37280;ِ,37280 +E 61 word 26 37280 +F و,39040;َ,39040 +F ح,39360;َ,39360;ي,39600 +F ث,39880;ُ,39880;م,40160;َ,40160 +F ا,40520 +F ك,40840;ُ,40840 +E 66 mistake 27 40840 SUBSTITUTION +F ن,41560 +F ت,41800;ُ,41800;م,42120 +F ف,42400;َ,42400 +F و,42720;َ,42720 +F ل,43240;ُ,43240 +F و,43760;و,43880;ُ,43880 +F ج,44200;ُ,44200;و,44480 +F ه,44680;َ,44680;ك,45040;ُ,45040 +F م,45280 +F ش,45600;َ,45600;ط,45840 +F ر,46120;َ,46120 +F ه,46560;ُ,46560;و,46720;ل,46960;ِ,46960 +F ء,47200;َ,47200 +F ل,47720;َ,47720 +F ا,48040;ي,48280;َ,48280 +F ك,48680;ُ,48680 +F و,48960;ن,49120;َ,49120 +F ل,49440;ِ,49440 +F ن,50400;َ,50400;ا,50680 +F س,50880;ِ,50880;ع,51200;َ,51200 +F ل,51480;َ,51480;ي,51720 +F ك,52000;ُ,52000 +F م,52320;ح,52600;ُ,52600 +F ج,53040;َ,53040 +F ت,53400;ُ,53400 +F ن,53800;ء,54000;ِ,54000 +F ل,54480;َ,54480 +F ل,55040;َ,55040 +F ذ,55360;ِ,55360;ي,55640 +F ن,55800;َ,55800 +F ظ,56160;َ,56160;ل,56320;َ,56320 +F م,56640;ُ,56640;و,56960 +F ل,62400;َ,62400;ذ,62720;ِ,62720 +F ي,62920;ن,63120;َ,63120 +F ظ,63480;َ,63480;ل,63680;َ,63680 +F م,64000;ُ,64000 +F و,64360;م,64600;ِ,64600 +F ن,64960 +E 104 repetition 19 64960 19 +F ه,65280;ُ,65280;م,65480 +F ف,65800;َ,65800;ل,66120;َ,66120 +F ا,66440 +F ت,66720;َ,66720;خ,66960 +F ش,67240;َ,67240 +F و,67680;ه,67920;ُ,67920 +F م,68200;و,68480;َ,68480 +F خ,68880 +F ش,69160;َ,69160;و,69440 +F ن,69720;ِ,69720;ي,70000 +F و,70200;َ,70200 +F ل,70560;ِ,70560;ء,70760;ُ,70760 +F ت,71080;ِ,71080 +F م,71920;َ,71920 +F ن,72200;ِ,72200 +F ع,72480;م,72640;َ,72640 +F ت,73120;ِ,73120 +F ي,73440;ع,73680;َ,73680 +F ل,73920;َ,73920;ي,74200 +F ك,74520;ُ,74520 +F م,74880;و,75040;َ,75040 +F ل,75360;َ,75360;ع,75600;َ,75600 +F ل,76080;َ,76080 +F ك,76480;ُ,76480;م,76720 +F ت,77000;َ,77000 +F ه,77280;ت,77520;َ,77520 +F د,77840;ُ,77840 +F و,79320;ن,79400 diff --git a/feature/memorize/tracker/src/test/resources/golden/real_husary_5_46_repeated_phrase.tsv b/feature/memorize/tracker/src/test/resources/golden/real_husary_5_46_repeated_phrase.tsv new file mode 100644 index 0000000000..e76c219d14 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/real_husary_5_46_repeated_phrase.tsv @@ -0,0 +1,868 @@ +W ءنا +W ءنزلن +W تورات +W فيها +W هدو +W ونوري +W يحكم +W به +W نبيون +W لذين +W ءسلمو +W لذين +W هادو +W وربانيون +W ولءحبار +W بم +W ستحفظو +W من +W كتاب +W لاه +W وكانو +W عليه +W شهداء +W فلا +W تخشو +W ناس +W وخشون +W ولا +W تشترو +W بءاياتي +W ثمن +W قليلو +W وم +W لم +W يحكم +W بما +W ءنزل +W لاه +W فءلاءك +W هم +W لكافرون +W وكتبنا +W عليهم +W فيها +W ءن +W نفس +W بنفس +W ولعين +W بلعين +W ولءنف +W بلءنف +W ولءذن +W بلءذن +W وسن +W بسن +W ولجروح +W قصاصن +W فمن +W تصدق +W بهي +W فهو +W كفارت +W لهو +W وم +W لم +W يحكم +W بما +W ءنزل +W لاه +W فءلاءك +W هم +W ظالمون +W وقفينا +W علا +W ءاثارهم +W بعيس +W بن +W مريم +W مصدق +W لما +W بين +W يديه +W من +W تورات +W وءاتيناه +W لءنجيل +W فيه +W هدو +W ونورو +W ومصدق +W لما +W بين +W يديه +W من +W تورات +W وهدو +W وموعظت +W لمتقين +W وليحكم +W ءهل +W لءنجيل +W بما +W ءنزل +W لاه +W فيه +W وم +W لم +W يحكم +W بما +W ءنزل +W لاه +W فءلاءك +W هم +W لفاسقون +W وءنزلنا +W ءليك +W لكتاب +W بلحق +W مصدق +W لما +W بين +W يديه +W من +W لكتاب +W ومهيمن +W عليه +W فحكم +W بينهم +W بما +W ءنزل +W لاه +W ولا +W تبع +W ءهواءهم +W عما +W جاءك +W من +W لحق +W لكلن +W جعلنا +W منكم +W شرعتو +W ومنهاجو +W ولو +W شاء +W لاه +W لجعلكم +W ءمتو +W واحدتو +W ولاك +W ليبلوكم +W في +W ما +W ءاتاكم +W فستبق +W لخيرات +W ءل +W لاه +W مرجعكم +W جميعن +W فينبءكم +W بما +W كنتم +W فيه +W تختلفون +W وءن +W حكم +W بينهم +W بما +W ءنزل +W لاه +W ولا +W تبع +W ءهواءهم +W وحذرهم +W ءي +W يفتنوك +W عم +W بعض +W ما +W ءنزل +W لاه +W ءليك +W فءن +W تولو +W فعلم +W ءنما +W يريد +W لاه +W ءي +W يصيبهم +W بعض +W ذنوبهم +W وءن +W كثير +W من +W ناس +W لفاسقون +A 5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5044,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5045,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5046,5047,5047,5047,5047,5047,5047,5047,5047,5047,5047,5047,5047,5047,5047,5047,5047,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5048,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049,5049 +C max_missed_words=2;skip_ayat=0 +F ء,240 +F ن,1680 +F ا,3680 +E 2 word 0 3680 +F ء,3880 +F ن,4640 +F ز,4880;ل,5200 +F ن,5400 +E 6 word 1 5400 +F ت,6040 +F و,6360;ر,6640 +F ا,7000 +F ت,7240 +E 10 word 2 7240 +F ف,7680;ي,7960 +F ه,8240 +F ا,8720;ه,9000 +E 13 word 3 8720 +F د,9280 +F و,10440 +E 15 word 4 10440 +F ن,10760 +F و,12280;ر,12400 +F ي,15460 +E 18 word 5 15460 +F ح,15700;ك,15900 +F م,16140;ب,16460 +E 20 word 6 16140 +F ه,16700 +E 21 word 7 16700 +F ن,17900 +F ب,18180 +F ي,18700 +F و,19140;ن,19300 +E 25 word 8 19300 +F ل,19980;ذ,20260 +F ي,20500;ن,20700 +E 27 word 9 20700 +F ء,21060 +F س,21420;ل,21580 +F م,21900;و,22220 +E 30 word 10 22220 +F ل,22460 +F ل,22940 +F ذ,23340;ي,23500;ن,23700 +E 33 repetition 10 22460 10 +E 33 word 11 23700 +F ه,24100 +F ا,24420;د,24700 +F و,25060 +E 36 word 12 25060 +F و,25260 +F ر,25860 +F ب,26500 +F ا,26860;ن,27100 +F ي,27660;و,27940 +F ن,28180;و,28460 +E 42 word 13 28180 +F ل,28860 +F ء,29100;ح,29340 +F ب,29580;ا,29980 +F ر,30180;ب,30500 +E 46 word 14 30180 +F م,30740 +E 47 word 15 30740 +F س,31060;ت,31260 +F ح,31620;ف,31900 +F ر,32220 +F و,32540;م,32780 +E 51 word 16 32540 +F ن,33580;ك,33820 +E 52 word 17 33580 +F ت,34140 +F ا,34540;ب,34740 +E 54 word 18 34740 +F ل,35420 +F ا,36380;ه,36500 +E 56 word 19 36500 +F ب,39580 +F م,39820 +E 58 repetition 15 39820 15 +F س,40140;ت,40340 +F ح,40620;ف,40860 +F ظ,41220 +F و,41580;م,41820 +F ن,42500 +E 63 repetition 16 42500 17 +F ك,42700 +F ت,43020;ا,43420 +F ب,43660 +E 66 repetition 18 43660 18 +F ل,44260 +F ا,44620;ه,44780 +E 68 repetition 19 44780 19 +F و,45100 +F ك,45540 +F ا,45900;ن,46100 +F و,46460;ع,46740 +E 72 word 20 46460 +F ل,47020 +F ي,47420;ه,47660 +E 74 word 21 47660 +F ش,48060 +F ه,48300;د,48700 +F ا,50340;ء,50460 +E 77 word 22 50460 +F ف,52820 +F ل,53100;ا,53500 +E 79 word 23 53500 +F ت,53740 +F خ,54100;ش,54420 +F و,54860 +E 82 word 24 54860 +F ن,55820 +F ا,56220 +F س,56500;و,56820 +E 85 word 25 56500 +F خ,57180 +F ش,57460;و,57820 +F ن,58020 +E 88 word 26 58020 +F و,58380;ل,58700 +F ا,59060 +E 90 word 27 59060 +F ت,59340;ش,59660 +F ت,59900 +F ر,60300;و,60620 +E 93 word 28 60620 +F ب,60820 +F ء,61260;ا,61580 +F ي,61780 +F ا,62220;ت,62540 +F ي,62940 +E 98 word 29 62940 +F ث,63220;م,63500 +F ن,63780 +E 100 word 30 63780 +F ن,64780;ق,64980 +F ل,65260 +F ي,65700;ل,66020 +F و,68800 +E 104 repetition 30 64780 30 +E 104 word 31 68800 +F م,69120 +E 105 word 32 69120 +F ل,69720 +F م,70040;ي,70320 +E 107 word 33 70040 +F ح,70720 +F ك,71040 +F م,71920;ب,72120 +E 110 word 34 71920 +F م,72520 +F ا,74280;ء,74480 +E 112 word 35 74280 +F ن,75320;ز,75560 +F ل,75840 +E 114 word 36 75840 +F ل,76640;ا,77040 +F ه,77280 +E 116 word 37 77280 +F ف,77640;ء,77960 +F ل,78240 +F ا,79720;ء,79840 +F ك,80080 +E 120 word 38 80080 +F ه,80480;م,80720 +E 121 word 39 80720 +F ل,81120 +F ك,81440;ا,81760 +F ف,82000 +F ر,82400 +F و,83920;ن,84000 +E 126 word 40 84000 +F و,84800;ك,85080 +F ت,85360;ب,85640 +F ن,85920 +F ا,86360;ع,86640 +E 130 word 41 86360 +F ل,86920 +F ي,87280;ه,87560 +F م,87960 +E 133 word 42 87960 +F ف,88320 +F ي,88760;ه,89080 +F ا,90800;ء,91000 +E 136 word 43 90800 +F ن,92200 +E 137 word 44 92200 +F ن,93320 +F ف,93640 +F س,93960;ب,94320 +E 140 word 45 93960 +F ن,95280 +F ف,95600 +F س,95880;و,96160 +E 143 word 46 95880 +F ل,96520 +F ع,96800;ي,97080 +F ن,97280;ب,97600 +E 146 word 47 97280 +F ل,97960 +F ع,98240;ي,98480 +F ن,98720;و,99000 +E 149 word 48 98720 +F ل,99440 +F ء,99720 +F ن,100480 +F ف,100720;ب,101040 +E 153 word 49 100720 +F ل,101400 +F ء,101680 +F ن,102400 +F ف,102600;و,102880 +E 157 word 50 102600 +F ل,103280 +F ء,103520;ذ,103760 +F ن,104040;ب,104320 +E 160 word 51 104040 +F ل,104720 +F ء,104960;ذ,105200 +F ن,105440;و,105760 +E 163 word 52 105440 +F ء,106440 +F ن,107400;ب,107720 +F س,108440 +F ن,109520 +E 167 mistake 53 109520 SUBSTITUTION +F و,109800;ل,110160 +F ج,110400 +F ر,110760;و,111120 +F ح,111360 +E 171 word 53 107400 ctx +E 171 word 54 109520 +E 171 word 55 111360 +F ت,111720 +F ص,112160 +F ا,113640;ص,113760 +F ف,116960;م,117280 +F ن,118080;ت,118360 +E 176 mistake 56 118360 SUBSTITUTION +F ص,118720 +F د,119240 +F ق,119600 +E 179 word 56 113760 ctx +E 179 word 57 118080 +E 179 word 58 119600 +F ب,119880 +F ه,120320;ي,120560 +E 181 word 59 120560 +F ف,120840;ه,121200 +F و,121440 +E 183 word 60 121440 +F ك,121800 +F ف,122400 +F ا,122880 +F ر,123200;ت,123560 +E 187 word 61 123560 +F ل,124240;ه,124520 +F و,127460;م,127700 +E 189 word 62 124520 +E 189 word 63 127700 +F ل,128300 +F م,128620 +E 191 word 64 128620 +F ي,128900;ح,129260 +F ك,129580 +F م,130420;ب,130620 +E 194 word 65 130420 +F م,130980 +F ا,132740;ء,132860 +E 196 word 66 132740 +F ن,133540 +F ز,133740;ل,134020 +E 198 word 67 134020 +F ل,134780 +F ا,135140;ه,135340 +E 200 word 68 135340 +F ف,135700 +F ء,136100;ل,136340 +F ا,138020;ء,138140;ك,138380 +E 203 word 69 138380 +F ه,138740 +F م,139020 +E 205 word 70 139020 +F ظ,139780 +F ا,140140;ل,140380 +F م,140700 +F و,142220 +F ن,142340 +E 210 word 71 142340 +F و,143220 +F ق,143540 +F ف,144060 +F ي,144380;ن,144620 +F ا,145060 +E 215 word 72 145060 +F ع,145380 +F ل,145700 +F ا,147420 +E 218 word 73 147420 +F ء,147660;ا,147980 +F ث,148300 +F ا,148660;ر,148900 +F ه,149260 +F م,150060;ب,150260 +E 223 word 74 150060 +F ع,150660;ي,150940 +F س,151180 +E 225 word 75 151180 +F ب,151460;ن,151700 +E 226 word 76 151700 +F م,152020;ر,152340 +F ي,152540 +F م,152900;م,153220 +E 229 word 77 152900 +F ص,153540 +F د,154140 +F ق,154500 +E 232 word 78 154500 +F ل,155060 +F م,155420 +F ا,155820;ب,156060 +E 235 word 79 155820 +F ي,156380;ن,156580 +E 236 word 80 156580 +F ي,156900 +F د,157220 +F ي,157700;ه,157860 +E 239 word 81 157860 +F م,158220;ن,158500 +E 240 word 82 158500 +F ت,159180 +F و,159620;ر,159900 +F ا,161420 +F ت,161540 +E 244 word 83 161540 +F و,163940;ء,164260 +F ا,164620 +F ت,164900;ي,165260 +F ن,165500 +F ا,165980 +F ه,166340;ل,166740 +E 250 word 84 166340 +F ء,167020 +F ن,167780;ج,168060 +F ي,168460;ل,168660 +E 253 word 85 168660 +F ف,169180 +F ي,169420 +F ه,169700;ه,170020 +E 256 word 86 169700 +F د,170340 +F و,171380 +E 258 word 87 171380 +F ن,171740 +F و,172140;ر,172460 +F و,173340 +E 261 word 88 173340 +F م,173660 +F ص,174020 +F د,174540;ق,174940 +E 264 word 89 174940 +F ل,175500;م,175860 +F ا,176220 +E 266 word 90 176220 +F ب,176460;ي,176780 +F ن,176980;ي,177300 +E 268 word 91 176980 +F د,177620 +F ي,177980;ه,178260 +E 270 word 92 178260 +F م,178580 +F ن,178860 +E 272 word 93 178860 +F ت,179540 +F و,179900;ر,180140 +F ا,180580 +F ت,180820 +E 276 word 94 180820 +F و,181220;ه,181540 +F د,181860 +F و,182940 +E 279 word 95 182940 +F م,183300 +F و,183660;ع,183900 +F ظ,184220 +F ت,184620 +E 283 word 96 184620 +F ل,185220 +F ل,185700;م,185940 +F ت,186500;ق,186940 +F ي,188700;ن,188780 +E 287 repetition 96 185220 96 +E 287 word 97 188780 +F و,189660 +F ل,190100 +F ي,190340;ح,190660 +F ك,190980 +F م,191300;ء,191620 +E 292 word 98 191300 +F ه,191980 +F ل,192260 +E 294 word 99 192260 +F ل,192740;ء,192980 +F ن,193700;ج,193980 +F ي,194380;ل,194540 +E 297 word 100 194540 +F ب,194860 +F م,195220 +F ا,196900 +E 300 word 101 196900 +F ء,197100 +F ن,197740;ز,197980 +F ل,198260 +E 303 word 102 198260 +F ل,199020 +F ا,199660 +F ه,199940 +E 306 word 103 199940 +F ف,200420 +F ي,201700 +F ه,201860 +E 309 word 104 201860 +F و,203660 +F م,203940 +E 311 word 105 203940 +F ل,204580 +F م,204980 +E 313 word 106 204980 +F ي,205220;ح,205620 +F ك,205900 +F م,206820;ب,207020 +E 316 word 107 206820 +F م,207380 +F ا,209220;ء,209420 +E 318 word 108 209220 +F ن,210100;ز,210340 +F ل,210660 +E 320 word 109 210660 +F ل,211380 +F ا,211740 +F ه,211980;ف,212340 +E 323 word 110 211980 +F ء,212660 +F ل,212980 +F ا,214500;ء,214620 +F ك,214900 +E 327 word 111 214900 +F ه,215340;م,215620 +E 328 word 112 215620 +F ل,216060 +F ف,216420 +F ا,216740;س,217020 +F ق,217460 +F و,218980;ن,219100 +E 333 word 113 219100 +F و,219940 +F ء,220260 +F ن,221140;ز,221380 +F ل,221820 +F ن,222100 +F ا,223700;ء,223860 +E 339 word 114 223700 +F ل,224100 +F ي,224420;ك,224700 +E 341 word 115 224700 +F ل,225020;ك,225260 +F ت,225620 +F ا,225980;ب,226180 +E 344 word 116 226180 +F ب,226540 +F ل,226860;ح,227060 +F ق,227580 +E 347 word 117 227580 +F م,227940 +F ص,228260 +F د,228740;ق,229100 +E 350 word 118 229100 +F ل,229660 +F م,229980 +F ا,230380;ب,230620 +E 353 word 119 230380 +F ي,230900;ن,231100 +E 354 word 120 231100 +F ي,231460 +F د,231780 +F ي,232140;ه,232380 +E 357 word 121 232380 +F م,232740;ن,232980 +E 358 word 122 232980 +F ل,233340 +F ك,233580;ت,233940 +F ا,234340 +F ب,234540;و,234860 +E 362 word 123 234540 +F م,235220 +F ه,235540;ي,235860 +F م,236100 +F ن,236420;ن,236780 +E 366 word 124 236780 +F ع,237100 +F ل,237420 +F ي,238540;ه,238700 +E 369 word 125 238700 +F ف,240780;ح,241060 +F ك,241380 +F م,242420 +E 372 word 126 242420 +F ب,242660;ي,242940 +F ن,243140 +F ه,243620 +F م,244340 +E 376 word 127 244340 +F ب,244580;م,244900 +F ا,246780 +E 378 word 128 246780 +F ء,246980 +F ن,247620;ز,247860 +F ل,248140 +E 381 word 129 248140 +F ل,248940 +F ا,250500;ه,250660 +E 383 word 130 250660 +F و,252540 +F ل,252860 +F ا,253260;ت,253620 +E 386 word 131 253260 +F ت,254300;ب,254580 +F ع,254940 +E 388 repetition 131 253620 131 +E 388 word 132 254940 +F ء,255260;ه,255580 +F و,255900 +F ا,257820;ء,257940 +F ه,258300 +F م,258620 +E 393 word 133 258620 +F ع,258980 +F م,260140 +F ا,260700 +E 396 word 134 260700 +F ج,261060 +F ا,262860;ء,262980 +F ك,263300;م,263620 +E 399 word 135 263300 +F ن,263900 +E 400 word 136 263900 +F ل,264380;ح,264620 +F ق,265020 +E 402 word 137 265020 +F ل,267220 +F ك,267620 +F ل,268100 +F ن,268860 +E 406 word 138 268860 +F ج,269140;ع,269420 +F ل,269820 +F ن,270060 +F ا,270500;م,270780 +E 410 word 139 270500 +F ن,271620 +F ك,271940;م,272180 +E 412 word 140 272180 +F ف,272540 +F ر,272900;ع,273140 +F ت,273580 +F و,274580 +E 416 word 141 274580 +F م,274940 +F ن,275300;ه,275540 +F ا,275980 +F ج,276300 +F ا,276740 +F و,279880 +E 422 word 142 279880 +F ل,280200 +F و,280640;ش,280920 +E 424 word 143 280640 +F ا,282440 +F ء,282600 +E 426 word 144 282600 +F ل,283240 +F ا,283600;ه,283840 +E 428 word 145 283840 +F ل,284160 +F ج,284480;ع,284800 +F ل,285080 +F ك,285520;م,285880 +E 432 word 146 285880 +F ء,286160 +F م,287080 +F ت,287520 +F و,288640 +E 436 word 147 288640 +F ا,289000 +F ح,289280;د,289560 +F ت,290040 +F و,291000 +E 440 word 148 291000 +F ل,291320 +F ا,291680;ك,291960 +E 442 word 149 291960 +F ل,292480 +F ي,292840 +F ب,293120;ل,293400 +F و,293760 +F ك,294240 +F م,294560;ف,294880 +E 448 word 150 294560 +F ي,295240 +E 449 word 151 295240 +F م,295560 +F ا,297200 +E 451 word 152 297200 +F ء,297440;ا,297800 +F ت,298160 +F ا,298560 +F ك,298880;م,299120 +E 455 word 153 299120 +F ف,301520 +F س,301880;ت,302080 +F ب,302400 +F ق,302760 +E 459 word 154 302760 +F ل,303200;خ,303520 +F ي,303880 +F ر,304200 +F ا,305760;ت,305960 +E 463 word 155 305960 +F ء,307760 +F ل,308000 +E 465 word 156 308000 +F ل,308680 +F ا,309040;ه,309280 +E 467 word 157 309280 +F م,309600 +F ر,309960;ج,310240 +F ع,310560 +F ك,310960;م,311200 +E 471 word 158 311200 +F ج,311480 +F م,311840;ي,312280 +F ع,312520 +F ن,313360;ف,313600 +E 475 word 159 313360 +F ي,313920 +F ن,314240 +F ب,314880 +F ء,315200;ك,315640 +F م,316400 +E 480 word 160 316400 +F ب,316640;م,317000 +F ا,317440 +E 482 word 161 317440 +F ك,317800 +F ن,318680;ت,318960 +F م,319360 +E 485 word 162 319360 +F ف,319720 +F ي,320160;ه,320400 +E 487 word 163 320400 +F ت,320720 +F خ,321120;ت,321360 +F ل,321720 +F ف,322080 +F و,323600;ن,323680 +E 492 word 164 323680 diff --git a/feature/memorize/tracker/src/test/resources/golden/real_husary_baqarah_1_5.tsv b/feature/memorize/tracker/src/test/resources/golden/real_husary_baqarah_1_5.tsv new file mode 100644 index 0000000000..d3bd9b9524 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/real_husary_baqarah_1_5.tsv @@ -0,0 +1,154 @@ +W ءَلِفلَامِيم +W ذَالِكَ +W لكِتَابُ +W لَا +W رَيبَ +W فِيهِ +W هُدَ +W لِلمُتَقِين +W ءَلَذِينَ +W يُءمِنُونَ +W بِلغَيبِ +W وَيُقِيمُونَ +W صَلَاتَ +W وَمِمَا +W رَزَقنَاهُم +W يُنفِقُون +W وَلَذِينَ +W يُءمِنُونَ +W بِمَا +W ءُنزِلَ +W ءِلَيكَ +W وَمَا +W ءُنزِلَ +W مِن +W قَبلِكَ +W وَبِلءَاخِرَتِ +W هُم +W يُوقِنُون +W ءُلَاءِكَ +W عَلَا +W هُدَ +W مِ +W رَبِهِم +W وَءُلَاءِكَ +W هُمُ +W لمُفلِحُون +P isti'adha ءَعُوذُبِلَاهِمِنَشَيطَانِرَجِيم +P basmala بِسمِلَاهِرَحمَانِرَحِيم +F ب,560;ِ,560;س,760 +F م,960;ِ,960 +F ل,1440;َ,1440;ا,1600;ه,1760;ِ,1760 +F ر,2200;َ,2200 +F ح,2400;م,2600;َ,2600 +F ا,2880;ن,3040;ِ,3040 +F ر,3520;َ,3520;ح,3800;ِ,3800 +F ي,5440;م,5560 +F ء,7480;َ,7480 +E 8 nontarget 0 5560 basmala +F ل,7680;ِ,7680;ف,7960 +F ل,8240;َ,8240 +F ا,11080 +F م,12480;ِ,12480 +F ي,15120 +F م,15360 +E 14 word 0 15360 +F ذ,17680;َ,17680 +F ا,17840;ل,18000;ِ,18000;ك,18200;َ,18200 +E 16 word 1 18200 +F ل,18400;ك,18560;ِ,18560 +F ت,18840;َ,18840 +F ا,19200;ب,19320;ُ,19320 +E 19 word 2 19320 +F ل,19680;َ,19680;ا,19920 +E 20 word 3 19920 +F ر,20160;َ,20160 +F ي,21640;ب,21720;َ,21720 +E 22 word 4 21720 +F ف,23560;ِ,23560;ي,23800 +F ه,24000;ِ,24000;ه,24240;ُ,24240 +E 24 word 5 24000 +F د,24480;َ,24480;ل,24920;ِ,24920 +E 25 word 6 24480 +F ل,25160;م,25360;ُ,25360 +F ت,25840;َ,25840 +F ق,26160;ِ,26160 +F ي,27960;ن,28040 +E 29 word 7 28040 +F ء,30560;َ,30560 +F ل,30920;َ,30920 +F ذ,31200;ِ,31200;ي,31360;ن,31520;َ,31520 +E 32 word 8 31520 +F ي,31760;ُ,31760;ء,32000 +F م,32160;ِ,32160;ن,32440;ُ,32440 +F و,32680;ن,32840;َ,32840 +E 35 word 9 32840 +F ب,33120;ِ,33120;ل,33320;غ,33520;َ,33520 +F ي,33720;ب,33920;ِ,33920 +E 37 word 10 33920 +F و,34200;َ,34200 +F ي,34560;ُ,34560;ق,34840;ِ,34840 +F ي,35120;م,35320;ُ,35320 +F و,35600;ن,35760;َ,35760 +E 41 word 11 35760 +F ص,36280;َ,36280 +F ل,36480;َ,36480;ا,36760 +F ت,37000;َ,37000;و,37280;َ,37280 +E 44 word 12 37000 +F م,37560;ِ,37560 +F م,38640;َ,38640 +F ا,38960;ر,39200;َ,39200 +E 47 word 13 38960 +F ز,39480;َ,39480;ق,39720 +F ن,39960;َ,39960 +F ا,40320;ه,40640;ُ,40640 +F م,40880;ي,41200;ُ,41200 +E 51 word 14 40880 +F ن,42080 +F ف,42280;ِ,42280;ق,42640;ُ,42640 +F و,44000;ن,44080 +E 54 word 15 44080 +F و,46080;َ,46080 +F ل,46560;َ,46560;ذ,46800;ِ,46800 +F ي,47040;ن,47200;َ,47200 +E 57 word 16 47200 +F ي,47520;ُ,47520;ء,47760;م,47960;ِ,47960 +F ن,48240;ُ,48240 +F و,48520;ن,48680;َ,48680 +E 60 word 17 48680 +F ب,48960;ِ,48960;م,49320;َ,49320 +F ا,51040;ء,51240;ُ,51240 +E 62 word 18 51040 +F ن,52080 +F ز,52320;ِ,52320;ل,52560;َ,52560 +E 64 word 19 52560 +F ء,52840;ِ,52840;ل,53080;َ,53080 +F ي,53320;ك,53560;َ,53560 +E 66 word 20 53560 +F و,53920;َ,53920 +F م,54280;َ,54280 +F ا,55880;ء,56080;ُ,56080 +E 69 word 21 55880 +F ن,56880 +F ز,57120;ِ,57120;ل,57360;َ,57360 +E 71 word 22 57360 +F م,57720;ِ,57720 +F ن,58560;ق,58720;َ,58720;ب,58960 +E 73 word 23 58560 +F ل,59200;ِ,59200 +F ك,59520;َ,59520;و,59760;َ,59760 +E 75 word 24 59520 +F ب,60000;ِ,60000;ل,60320 +F ء,60600;َ,60600;ا,60800 +F خ,61000;ِ,61000;ر,61280;َ,61280 +F ت,61600;ِ,61600 +E 79 word 25 61600 +F ه,61960;ُ,61960;م,62200 +E 80 word 26 62200 +F ي,62520;ُ,62520 +F و,62880;ق,63120;ِ,63120 +F ن,63360;ُ,63360 +F و,65040;ن,65120 +E 84 word 27 65120 +F ء,68320;ُ,68320 +F ل,68640;َ,68640 diff --git a/feature/memorize/tracker/src/test/resources/golden/real_husary_fatiha.tsv b/feature/memorize/tracker/src/test/resources/golden/real_husary_fatiha.tsv new file mode 100644 index 0000000000..01dbf4520f --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/real_husary_fatiha.tsv @@ -0,0 +1,132 @@ +W بِسمِ +W لَاهِ +W رَحمَانِ +W رَحِيم +W ءَلحَمدُ +W لِلَاهِ +W رَبِ +W لعَالَمِين +W ءَرَحمَانِ +W رَحِيم +W مَالِكِ +W يَومِ +W دِين +W ءِيَاكَ +W نَعبُدُ +W وَءِيَاكَ +W نَستَعِين +W ءِهدِنَ +W صِرَاطَ +W لمُستَقِيم +W صِرَاطَ +W لَذِينَ +W ءَنعَمتَ +W عَلَيهِم +W غَيرِ +W لمَغضُوبِ +W عَلَيهِم +W وَلَ +W ضَالِين +P isti'adha ءَعُوذُبِلَاهِمِنَشَيطَانِرَجِيم +F ء,960;َ,960;ع,1040;ُ,1040;و,1160;ذ,1320;ُ,1320 +F ب,1440;ِ,1440;ل,1720;َ,1720;ا,1840 +F ه,2000;ِ,2000;م,2200;ِ,2200 +F ن,2400;َ,2400;ش,2680;َ,2680;ي,2840 +F ط,3000;َ,3000;ا,3160;ن,3320;ِ,3320 +F ر,3640;َ,3640 +F ج,3840;ِ,3840 +F ي,5320;م,5400 +F ب,6680;ِ,6680 +E 8 nontarget 0 5400 isti'adha +F س,6840;م,6960;ِ,6960 +E 9 word 0 6960 +F ل,7360;َ,7360;ا,7520 +F ه,7680;ِ,7680;ر,8120;َ,8120 +E 11 word 1 7680 +F ح,8280;م,8440;َ,8440 +F ا,8680;ن,8840;ِ,8840 +E 13 word 2 8840 +F ر,9240;َ,9240;ح,9440;ِ,9440 +F ي,11000 +F م,11120 +E 16 word 3 11120 +F ء,12600;َ,12600;ل,12760 +F ح,12960;َ,12960;م,13040;د,13200;ُ,13200 +E 18 word 4 13200 +F ل,13440;ِ,13440;ل,13760;َ,13760 +F ا,13920;ه,14080;ِ,14080 +E 20 word 5 14080 +F ر,14400;َ,14400;ب,14680;ِ,14680 +E 21 word 6 14680 +F ل,14880;ع,15120;َ,15120;ا,15280 +F ل,15520;َ,15520;م,15720;ِ,15720 +F ي,17360;ن,17440 +E 24 word 7 17440 +F ء,18400;َ,18400 +F ر,18800;َ,18800;ح,19000 +F م,19200;َ,19200;ا,19400;ن,19560;ِ,19560 +E 27 word 8 19560 +F ر,19920;َ,19920 +F ح,20160;ِ,20160 +F ي,21720;م,21840 +E 30 word 9 21840 +F م,23040;َ,23040;ا,23200;ل,23360;ِ,23360 +F ك,23640;ِ,23640;ي,23840;َ,23840 +E 32 word 10 23640 +F و,24080;م,24240;ِ,24240 +E 33 word 11 24240 +F د,24640;ِ,24640 +F ي,26320;ن,26360 +E 35 word 12 26360 +F ء,27840;ِ,27840;ي,28120;َ,28120 +F ا,28320;ك,28480;َ,28480;ن,28720;َ,28720 +E 37 word 13 28480 +F ع,28920;ب,29080;ُ,29080 +F د,29360;ُ,29360;و,29600;َ,29600 +E 39 word 14 29360 +F ء,29920;ِ,29920 +F ي,30240;َ,30240;ا,30480;ك,30680;َ,30680 +E 41 word 15 30680 +F ن,30880;َ,30880;س,31080 +F ت,31240;َ,31240;ع,31440;ِ,31440 +F ي,33240;ن,33320 +E 44 word 16 33320 +F ء,34560;ِ,34560;ه,34600;د,34760;ِ,34760;ن,34960;َ,34960 +E 45 word 17 34960 +F ص,35360;ِ,35360 +F ر,35520;َ,35520;ا,35800;ط,35960;َ,35960 +E 47 word 18 35960 +F ل,36200;م,36400;ُ,36400 +F س,36600;ت,36760;َ,36760 +F ق,37040;ِ,37040 +F ي,38680;م,38760 +E 51 word 19 38760 +F ص,40040;ِ,40040;ر,40280;َ,40280 +F ا,40480;ط,40640;َ,40640 +E 53 word 20 40640 +F ل,41000;َ,41000 +F ذ,41280;ِ,41280;ي,41400;ن,41520;َ,41520 +E 55 word 21 41520 +F ء,41760;َ,41760;ن,41920;ع,42080;َ,42080 +F م,42280;ت,42480;َ,42480 +E 57 word 22 42480 +F ع,42760;َ,42760;ل,42960;َ,42960 +F ي,43200;ه,43400;ِ,43400 +F م,43680;غ,43880;َ,43880 +E 60 word 23 43680 +F ي,44160;ر,44320;ِ,44320;ل,44560 +E 61 word 24 44320 +F م,44720;َ,44720;غ,44960 +F ض,45200;ُ,45200;و,45480 +F ب,45640;ِ,45640;ع,45920;َ,45920 +E 64 word 25 45640 +F ل,46120;َ,46120;ي,46320;ه,46520;ِ,46520 +F م,46760;و,46960;َ,46960 +E 66 word 26 46760 +F ل,47160;َ,47160 +E 67 word 27 47160 +F ض,47840;َ,47840 +F ا,50560 +F ل,51280;ِ,51280 +F ي,53360;ن,53520 +E 71 word 28 53520 diff --git a/feature/memorize/tracker/src/test/resources/golden/synthetic_hinted.tsv b/feature/memorize/tracker/src/test/resources/golden/synthetic_hinted.tsv new file mode 100644 index 0000000000..15c56ec1b2 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/synthetic_hinted.tsv @@ -0,0 +1,12 @@ +W bismi +W allahi +W arrahmani +W arrahimi +F b,0;i,80;s,160;m,240;i,320 +E 0 word 0 320 +F q,400;u,480;l,560;h,640;u,720;w,800;a,880 +H 1 +F a,0;r,80;r,160;a,240;h,320;m,400;a,480;n,560;i,640 +E 3 word 2 640 +F a,720;r,800;r,880;a,960;h,1040;i,1120;m,1200;i,1280 +E 4 word 3 1280 diff --git a/feature/memorize/tracker/src/test/resources/golden/synthetic_perfect.tsv b/feature/memorize/tracker/src/test/resources/golden/synthetic_perfect.tsv new file mode 100644 index 0000000000..b013813308 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/synthetic_perfect.tsv @@ -0,0 +1,13 @@ +W bismi +W allahi +W arrahmani +W arrahimi +F b,0;i,80;s,160 +F m,240;i,320;a,400;l,480;l,560 +E 1 word 0 320 +F a,640;h,720;i,800;a,880;r,960;r,1040;a,1120 +E 2 word 1 800 +F h,1200;m,1280;a,1360;n,1440;i,1520;a,1600;r,1680;r,1760 +E 3 word 2 1520 +F a,1840;h,1920;i,2000;m,2080;i,2160 +E 4 word 3 2160 diff --git a/feature/memorize/tracker/src/test/resources/golden/synthetic_repetition.tsv b/feature/memorize/tracker/src/test/resources/golden/synthetic_repetition.tsv new file mode 100644 index 0000000000..0ef0bb2285 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/synthetic_repetition.tsv @@ -0,0 +1,14 @@ +W bismi +W allahi +W arrahmani +W arrahimi +F b,0;i,80;s,160;m,240;i,320 +E 0 word 0 320 +F a,400;l,480;l,560;a,640;h,720;i,800 +E 1 word 1 800 +F b,880;i,960;s,1040;m,1120;i,1200 +E 2 repetition 0 1200 0 +F a,1280;l,1360;l,1440;a,1520;h,1600;i,1680 +E 3 repetition 1 1680 1 +F a,1760;r,1840;r,1920;a,2000;h,2080;m,2160;a,2240;n,2320;i,2400 +E 4 word 2 2400 diff --git a/feature/memorize/tracker/src/test/resources/golden/synthetic_self_correction.tsv b/feature/memorize/tracker/src/test/resources/golden/synthetic_self_correction.tsv new file mode 100644 index 0000000000..4e3122d691 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/synthetic_self_correction.tsv @@ -0,0 +1,12 @@ +W bismi +W allahi +W arrahmani +W arrahimi +F b,0;i,80;s,160;m,240;i,320 +E 0 word 0 320 +F q,400;u,480;l,560;h,640;u,720 +F a,800;l,880;l,960;a,1040;h,1120;i,1200 +E 2 repetition 0 720 0 +E 2 word 1 1200 +F a,1280;r,1360;r,1440;a,1520;h,1600;m,1680;a,1760;n,1840;i,1920 +E 3 word 2 1920 diff --git a/feature/memorize/tracker/src/test/resources/golden/synthetic_skip.tsv b/feature/memorize/tracker/src/test/resources/golden/synthetic_skip.tsv new file mode 100644 index 0000000000..4cab0ce1f7 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/synthetic_skip.tsv @@ -0,0 +1,12 @@ +W bismi +W allahi +W arrahmani +W arrahimi +F b,0;i,80;s,160;m,240;i,320 +E 0 word 0 320 +F a,400;r,480;r,560;a,640;h,720;m,800;a,880;n,960;i,1040 +E 1 mistake 1 1040 SUBSTITUTION +F a,1120;r,1200;r,1280;a,1360;h,1440;i,1520;m,1600;i,1680 +E 2 missed 1 1680 +E 2 word 2 1040 +E 2 word 3 1680 diff --git a/feature/memorize/tracker/src/test/resources/golden/synthetic_substitution.tsv b/feature/memorize/tracker/src/test/resources/golden/synthetic_substitution.tsv new file mode 100644 index 0000000000..2dabc01284 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/synthetic_substitution.tsv @@ -0,0 +1,10 @@ +W bismi +W allahi +W arrahmani +W arrahimi +F b,0;i,80;s,160;m,240;i,320 +E 0 word 0 320 +F a,400;l,480;l,560;a,640;x,720;i,800 +E 1 word 1 800 +F a,880;r,960;r,1040;a,1120;h,1200;m,1280;a,1360;n,1440;i,1520 +E 2 word 2 1520 diff --git a/feature/memorize/tracker/src/test/resources/golden/synthetic_takbir.tsv b/feature/memorize/tracker/src/test/resources/golden/synthetic_takbir.tsv new file mode 100644 index 0000000000..c8152f8752 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/synthetic_takbir.tsv @@ -0,0 +1,20 @@ +W qulhuwa +W llahu +W ahadun +W llahu +W ssamadu +P takbir allahuakbar +P ruku subhanarabbiyalazim +F q,0;u,80;l,160;h,240;u,320;w,400;a,480 +E 0 word 0 480 +F l,560;l,640;a,720;h,800;u,880;a,960;h,1040;a,1120;d,1200;u,1280;n,1360 +E 1 word 1 880 +E 1 word 2 1360 +F a,1440;l,1520;l,1600;a,1680 +F h,1760;u,1840;a,1920;k,2000;b,2080;a,2160;r,2240 +F s,2320;u,2400;b,2480;h,2560;a,2640;n,2720;a,2800;r,2880;a,2960;b,3040;b,3120;i,3200;y,3280;a,3360;l,3440;a,3520;z,3600;i,3680;m,3760 +E 4 nontarget 3 2240 takbir +F l,3840;l,3920;a,4000;h,4080;u,4160;s,4240;s,4320;a,4400;m,4480;a,4560;d,4640;u,4720 +E 5 repetition 2 3760 2 +E 5 word 3 4160 +E 5 word 4 4720 diff --git a/feature/memorize/tracker/src/test/resources/golden/synthetic_takbir_leftover.tsv b/feature/memorize/tracker/src/test/resources/golden/synthetic_takbir_leftover.tsv new file mode 100644 index 0000000000..a14a542b73 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/synthetic_takbir_leftover.tsv @@ -0,0 +1,20 @@ +W qulhuwa +W llahu +W ahadun +W llahu +W ssamadu +P takbir allahuakbar +P ruku subhanarabbiyalazim +F q,0;u,80;l,160;h,240;u,320;w,400;a,480 +E 0 word 0 480 +F l,560;l,640;a,720;h,800;u,880;a,960;h,1040;a,1120;d,1200;u,1280;n,1360 +E 1 word 1 880 +E 1 word 2 1360 +F d,1440;u,1520;n,1600;w,1680;a,1760;l,1840;l,1920;a,2000 +E 2 mistake 3 2000 SUBSTITUTION +F a,2080;l,2160;l,2240;a,2320;h,2400;u,2480;a,2560;k,2640;b,2720;a,2800;r,2880 +S +E 4 nontarget 3 2880 takbir +F l,0;l,80;a,160;h,240;u,320;s,400;s,480;a,560;m,640;a,720;d,800;u,880 +E 5 word 3 320 +E 5 word 4 880 diff --git a/feature/memorize/tracker/src/test/resources/golden/synthetic_takbir_pause.tsv b/feature/memorize/tracker/src/test/resources/golden/synthetic_takbir_pause.tsv new file mode 100644 index 0000000000..75ba621881 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/synthetic_takbir_pause.tsv @@ -0,0 +1,18 @@ +W qulhuwa +W llahu +W ahadun +W llahu +W ssamadu +P takbir allahuakbar +P ruku subhanarabbiyalazim +F q,0;u,80;l,160;h,240;u,320;w,400;a,480 +E 0 word 0 480 +F l,560;l,640;a,720;h,800;u,880;a,960;h,1040;a,1120;d,1200;u,1280;n,1360 +E 1 word 1 880 +E 1 word 2 1360 +F a,1440;l,1520;l,1600;a,1680;h,1760;u,1840;a,1920;k,2000;b,2080;a,2160;r,2240 +S +E 3 nontarget 3 2240 takbir +F l,0;l,80;a,160;h,240;u,320;s,400;s,480;a,560;m,640;a,720;d,800;u,880 +E 4 word 3 320 +E 4 word 4 880 diff --git a/feature/memorize/tracker/src/test/resources/golden/synthetic_wrong_word.tsv b/feature/memorize/tracker/src/test/resources/golden/synthetic_wrong_word.tsv new file mode 100644 index 0000000000..bba2e1d84f --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/golden/synthetic_wrong_word.tsv @@ -0,0 +1,9 @@ +W bismi +W allahi +W arrahmani +W arrahimi +F b,0;i,80;s,160;m,240;i,320 +E 0 word 0 320 +F q,400;u,480;l,560;h,640;u,720;w,800;a,880 +F a,960;h,1040;a,1120;d,1200;u,1280;n,1360 +E 2 mistake 1 1360 SUBSTITUTION diff --git a/feature/memorize/tracker/src/test/resources/live_start/live_mi11_102_dropped_start.tsv b/feature/memorize/tracker/src/test/resources/live_start/live_mi11_102_dropped_start.tsv new file mode 100644 index 0000000000..a02445eab6 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/live_start/live_mi11_102_dropped_start.tsv @@ -0,0 +1,673 @@ +W وتين +W وزيتون +W وطور +W سينين +W وهاذ +W لبلد +W لءمين +W لقد +W خلقن +W لءنسان +W في +W ءحسن +W تقويم +W ثم +W ردناه +W ءسفل +W سافلين +W ءل +W لذين +W ءامنو +W وعمل +W صالحات +W فلهم +W ءجرن +W غير +W منون +W فما +W يكذبك +W بعد +W بدين +W ءليس +W لاه +W بءحكم +W لحاكمين +W ءقرء +W بسم +W ربك +W لذي +W خلق +W خلق +W لءنسان +W من +W علق +W ءقرء +W وربك +W لءكرم +W ءلذي +W علم +W بلقلم +W علم +W لءنسان +W ما +W لم +W يعلم +W كلا +W ءن +W لءنسان +W ليطغا +W ء +W رءاه +W ستغنا +W ءن +W ءلا +W ربك +W رجعا +W ءرءيت +W لذي +W ينها +W عبدن +W ءذا +W صلا +W ءرءيت +W ءن +W كان +W عل +W لهدا +W ءو +W ءمر +W بتقوا +W ءرءيت +W ءن +W كذب +W وتولا +W ءلم +W يعلم +W بءن +W لاه +W يرا +W كلا +W لء +W لم +W ينته +W لنسفعم +W بناصيه +W ناصيتن +W كاذبتن +W خاطءه +W فليدع +W ناديه +W سندع +W زبانيه +W كلا +W لا +W تطعه +W وسجد +W وقترب +W ءنا +W ءنزلناه +W في +W ليلت +W لقدر +W وما +W ءدراك +W ما +W ليلت +W لقدر +W ليلت +W لقدر +W خير +W من +W ءلف +W شهر +W تنزل +W لملاءكت +W وروح +W فيها +W بءذن +W ربه +W من +W كل +W ءمر +W سلامن +W هي +W حتا +W مطلع +W لفجر +W لم +W يكن +W لذين +W كفرو +W من +W ءهل +W لكتاب +W ولمشركين +W منفكين +W حتا +W تءتيهم +W لبينه +W رسول +W من +W لاه +W يتلو +W صحف +W مطهره +W فيها +W كتبن +W قيمه +W وما +W تفرق +W لذين +W ءوت +W لكتاب +W ءلا +W م +W بعد +W ما +W جاءتهم +W لبينه +W وما +W ءمرو +W ءلا +W ليعبد +W لاه +W مخلصين +W له +W دين +W حنفاء +W ويقيم +W صلات +W ويءت +W زكات +W وذالك +W دين +W لقيمه +W ءن +W لذين +W كفرو +W من +W ءهل +W لكتاب +W ولمشركين +W في +W نار +W جهنم +W خالدين +W فيها +W ءلاءك +W هم +W شر +W لبريه +W ءن +W لذين +W ءامنو +W وعمل +W صالحات +W ءلاءك +W هم +W خير +W لبريه +W جزاءهم +W عند +W ربهم +W جنات +W عدن +W تجري +W من +W تحته +W لءنهار +W خالدين +W فيها +W ءبد +W رضي +W لاه +W عنهم +W ورضو +W عنه +W ذالك +W لمن +W خشي +W ربه +W ءذا +W زلزلت +W لءرض +W زلزالها +W وءخرجت +W لءرض +W ءثقالها +W وقال +W لءنسان +W ما +W لها +W يومءذن +W تحدث +W ءخبارها +W بءن +W ربك +W ءوحا +W لها +W يومءذي +W يصدر +W ناس +W ءشتات +W ليرو +W ءعمالهم +W فمي +W يعمل +W مثقال +W ذرتن +W خيري +W يره +W ومي +W يعمل +W مثقال +W ذرتن +W شري +W يره +W ولعاديات +W ضبحا +W فلموريات +W قدحا +W فلمغيرات +W صبحا +W فءثرن +W بهي +W نقعا +W فوسطن +W بهي +W جمعا +W ءن +W لءنسان +W لربهي +W لكنود +W وءنهو +W علا +W ذالك +W لشهيد +W وءنهو +W لحب +W لخير +W لشديد +W ءفلا +W يعلم +W ءذا +W بعثر +W ما +W ف +W لقبور +W وحصل +W ما +W ف +W صدور +W ءن +W ربهم +W بهم +W يومءذ +W لخبير +W ءلقارعه +W م +W لقارعه +W وما +W ءدراك +W م +W لقارعه +W يوم +W يكون +W ناس +W كلفراش +W لمبثوث +W وتكون +W لجبال +W كلعهن +W لمنفوش +W فءما +W من +W ثقلت +W موازينه +W فهو +W في +W عيشت +W راضيه +W وءما +W من +W خفت +W موازينه +W فءمهو +W هاويه +W وما +W ءدراك +W ما +W هيه +W نارن +W حاميه +W ءلهاكم +W تكاثر +W حتا +W زرتم +W لمقابر +W كلا +W سوف +W تعلمون +W ثم +W كلا +W سوف +W تعلمون +W كلا +W لو +W تعلمون +W علم +W ليقين +W لترون +W لجحيم +W ثم +W لترونها +W عين +W ليقين +W ثم +W لتسءلن +W يومءذن +W عن +W نعيم +W ولعصر +W ءن +W لءنسان +W لفي +W خسر +W ءل +W لذين +W ءامنو +W وعمل +W صالحات +W وتواصو +W بلحق +W وتواصو +W بصبر +W ويل +W لكل +W همزت +W لمزه +W ءلذي +W جمع +W مالو +W وعده +W يحسب +W ءن +W مالهو +W ءخلده +W كلا +W ليمبذن +W ف +W لحطمه +W وما +W ءدراك +W م +W لحطمه +W نار +W لاه +W لموقده +W ءلتي +W تطلع +W عل +W لءفءده +W ءنها +W عليه +W مءصده +W في +W عمد +W مده +W ءلم +W تر +W كيف +W فعل +W ربك +W بءصحاب +W لفيل +W ءلم +W يجعل +W كيدهم +W في +W تضليل +W وءرسل +W عليهم +W طيرن +W ءبابيل +W ترميهم +W بحجارت +W من +W سجيل +W فجعلهم +W كعصف +W مءكول +W لءيلاف +W قريش +W ءيلافهم +W رحلت +W شتاء +W وصيف +W فليعبدو +W رب +W هاذ +W لبيت +W ءلذي +W ءطعمه +W من +W جوعو +W وءامنه +W من +W خوف +W ءرءيت +W لذي +W يكذب +W بدين +W فذالك +W لذي +W يدع +W ليتيم +W ولا +W يحض +W علا +W طعام +W لمسكين +W فويل +W لمصلين +W ءلذين +W هم +W عن +W صلاتهم +W ساهون +W ءلذين +W هم +W يراءون +W ويمنعون +W لماعون +W ءنا +W ءعطيناك +W لكوثر +W فصل +W لربك +W ونحر +W ءن +W شانءك +W هو +W لءبتر +W قل +W ياءيه +W لكافرون +W لا +W ءعبد +W ما +W تعبدون +W ولا +W ءنتم +W عابدون +W ما +W ءعبد +W ولا +W ءن +W عابد +W ما +W عبتم +W ولا +W ءنتم +W عابدون +W ما +W ءعبد +W لكم +W دينكم +W ولي +W دين +W ءذا +W جاء +W نصر +W لاه +W ولفتح +W ورءيت +W ناس +W يدخلون +W في +W دين +W لاه +W ءفواجا +W فسبح +W بحمد +W ربك +W وستغفره +W ءنهو +W كان +W توابا +W تبت +W يدا +W ءبي +W لهبو +W وتب +W ما +W ءغنا +W عنه +W مالهو +W وما +W كسب +W سيصلا +W نارن +W ذات +W لهب +W ومرءتهو +W حمالت +W لحطب +W في +W جيدها +W حبل +W م +W مسد +W قل +W هو +W لاه +W ءحد +W ءلاه +W صمد +W لم +W يلد +W ولم +W يولد +W ولم +W يك +W لهو +W كفون +W ءحد +W قل +W ءعوذ +W برب +W لفلق +W من +W شر +W ما +W خلق +W ومن +W شر +W غاسقن +W ءذا +W وقب +W ومن +W شر +W نفاثات +W ف +W لعقد +W ومن +W شر +W حاسدن +W ءذا +W حسد +W قل +W ءعوذ +W برب +W ناس +W ملك +W ناس +W ءلاه +W ناس +W من +W شر +W لوسواس +W لخناس +W ءلذي +W يوسوس +W في +W صدور +W ناس +W من +W لجنت +W وناس +P isti'adha ءعوذبلاهمنشيطانرجيم +P basmala بسملاهرحمانرحيم +A 95001,95001,95002,95002,95003,95003,95003,95004,95004,95004,95004,95004,95004,95005,95005,95005,95005,95006,95006,95006,95006,95006,95006,95006,95006,95006,95007,95007,95007,95007,95008,95008,95008,95008,96001,96001,96001,96001,96001,96002,96002,96002,96002,96003,96003,96003,96004,96004,96004,96005,96005,96005,96005,96005,96006,96006,96006,96006,96007,96007,96007,96008,96008,96008,96008,96009,96009,96009,96010,96010,96010,96011,96011,96011,96011,96011,96012,96012,96012,96013,96013,96013,96013,96014,96014,96014,96014,96014,96015,96015,96015,96015,96015,96015,96016,96016,96016,96017,96017,96018,96018,96019,96019,96019,96019,96019,97001,97001,97001,97001,97001,97002,97002,97002,97002,97002,97003,97003,97003,97003,97003,97003,97004,97004,97004,97004,97004,97004,97004,97004,97004,97005,97005,97005,97005,97005,98001,98001,98001,98001,98001,98001,98001,98001,98001,98001,98001,98001,98002,98002,98002,98002,98002,98002,98003,98003,98003,98004,98004,98004,98004,98004,98004,98004,98004,98004,98004,98004,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98007,98007,98007,98007,98007,98007,98007,98007,98007,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,99001,99001,99001,99001,99002,99002,99002,99003,99003,99003,99003,99004,99004,99004,99005,99005,99005,99005,99006,99006,99006,99006,99006,99006,99007,99007,99007,99007,99007,99007,99008,99008,99008,99008,99008,99008,100001,100001,100002,100002,100003,100003,100004,100004,100004,100005,100005,100005,100006,100006,100006,100006,100007,100007,100007,100007,100008,100008,100008,100008,100009,100009,100009,100009,100009,100009,100009,100010,100010,100010,100010,100011,100011,100011,100011,100011,101001,101002,101002,101003,101003,101003,101003,101004,101004,101004,101004,101004,101005,101005,101005,101005,101006,101006,101006,101006,101007,101007,101007,101007,101008,101008,101008,101008,101009,101009,101010,101010,101010,101010,101011,101011,102001,102001,102002,102002,102002,102003,102003,102003,102004,102004,102004,102004,102005,102005,102005,102005,102005,102006,102006,102007,102007,102007,102007,102008,102008,102008,102008,102008,103001,103002,103002,103002,103002,103003,103003,103003,103003,103003,103003,103003,103003,103003,104001,104001,104001,104001,104002,104002,104002,104002,104003,104003,104003,104003,104004,104004,104004,104004,104005,104005,104005,104005,104006,104006,104006,104007,104007,104007,104007,104008,104008,104008,104009,104009,104009,105001,105001,105001,105001,105001,105001,105001,105002,105002,105002,105002,105002,105003,105003,105003,105003,105004,105004,105004,105004,105005,105005,105005,106001,106001,106002,106002,106002,106002,106003,106003,106003,106003,106004,106004,106004,106004,106004,106004,106004,107001,107001,107001,107001,107002,107002,107002,107002,107003,107003,107003,107003,107003,107004,107004,107005,107005,107005,107005,107005,107006,107006,107006,107007,107007,108001,108001,108001,108002,108002,108002,108003,108003,108003,108003,109001,109001,109001,109002,109002,109002,109002,109003,109003,109003,109003,109003,109004,109004,109004,109004,109004,109005,109005,109005,109005,109005,109006,109006,109006,109006,110001,110001,110001,110001,110001,110002,110002,110002,110002,110002,110002,110002,110003,110003,110003,110003,110003,110003,110003,111001,111001,111001,111001,111001,111002,111002,111002,111002,111002,111002,111003,111003,111003,111003,111004,111004,111004,111005,111005,111005,111005,111005,112001,112001,112001,112001,112002,112002,112003,112003,112003,112003,112004,112004,112004,112004,112004,113001,113001,113001,113001,113002,113002,113002,113002,113003,113003,113003,113003,113003,113004,113004,113004,113004,113004,113005,113005,113005,113005,113005,114001,114001,114001,114001,114002,114002,114003,114003,114004,114004,114004,114004,114005,114005,114005,114005,114005,114006,114006,114006 +C max_missed_words=2;skip_ayat=0 +I start=297;window=560 +S +F ء,8400 +F ل,8800 +F ه,9300;ا,9300 +F ك,9800 +S +F م,10300 +F ت,10800 +F ك,11200 +F ا,11700;ث,11700 +F ر,12200 +F ح,13200 +F ت,13600 +F ا,14100 +F ن,14600 +F ل,15100;ع,15100 +F ب,15600 +F م,16000 +F ق,16500 +F ا,17000 +F ب,17500;ر,17500 +S +F ب,18400 +F ل,18900;ء,18900 +F ا,19400 +F ث,19900 +F و,20400;ف,20400 +F ت,20800 +F ع,21300 +F ل,21800 +S +F م,22300 +F و,23200 +F ن,23700 +F ء,24700 +F ل,25200 +F ا,25600;ل,25600 +F و,26100 +F ت,26600 +F ع,27100;ل,27100 +F م,27600 +F و,28000;ن,28000 +F ع,28500 +F ل,29000 +F م,29500 +F ل,30000;ي,30000 +F ق,30400 +S +F ي,31900 +F ن,32400 diff --git a/feature/memorize/tracker/src/test/resources/live_start/live_mi11_102_dropped_start_correct.tsv b/feature/memorize/tracker/src/test/resources/live_start/live_mi11_102_dropped_start_correct.tsv new file mode 100644 index 0000000000..b938839e63 --- /dev/null +++ b/feature/memorize/tracker/src/test/resources/live_start/live_mi11_102_dropped_start_correct.tsv @@ -0,0 +1,686 @@ +W وتين +W وزيتون +W وطور +W سينين +W وهاذ +W لبلد +W لءمين +W لقد +W خلقن +W لءنسان +W في +W ءحسن +W تقويم +W ثم +W ردناه +W ءسفل +W سافلين +W ءل +W لذين +W ءامنو +W وعمل +W صالحات +W فلهم +W ءجرن +W غير +W منون +W فما +W يكذبك +W بعد +W بدين +W ءليس +W لاه +W بءحكم +W لحاكمين +W ءقرء +W بسم +W ربك +W لذي +W خلق +W خلق +W لءنسان +W من +W علق +W ءقرء +W وربك +W لءكرم +W ءلذي +W علم +W بلقلم +W علم +W لءنسان +W ما +W لم +W يعلم +W كلا +W ءن +W لءنسان +W ليطغا +W ء +W رءاه +W ستغنا +W ءن +W ءلا +W ربك +W رجعا +W ءرءيت +W لذي +W ينها +W عبدن +W ءذا +W صلا +W ءرءيت +W ءن +W كان +W عل +W لهدا +W ءو +W ءمر +W بتقوا +W ءرءيت +W ءن +W كذب +W وتولا +W ءلم +W يعلم +W بءن +W لاه +W يرا +W كلا +W لء +W لم +W ينته +W لنسفعم +W بناصيه +W ناصيتن +W كاذبتن +W خاطءه +W فليدع +W ناديه +W سندع +W زبانيه +W كلا +W لا +W تطعه +W وسجد +W وقترب +W ءنا +W ءنزلناه +W في +W ليلت +W لقدر +W وما +W ءدراك +W ما +W ليلت +W لقدر +W ليلت +W لقدر +W خير +W من +W ءلف +W شهر +W تنزل +W لملاءكت +W وروح +W فيها +W بءذن +W ربه +W من +W كل +W ءمر +W سلامن +W هي +W حتا +W مطلع +W لفجر +W لم +W يكن +W لذين +W كفرو +W من +W ءهل +W لكتاب +W ولمشركين +W منفكين +W حتا +W تءتيهم +W لبينه +W رسول +W من +W لاه +W يتلو +W صحف +W مطهره +W فيها +W كتبن +W قيمه +W وما +W تفرق +W لذين +W ءوت +W لكتاب +W ءلا +W م +W بعد +W ما +W جاءتهم +W لبينه +W وما +W ءمرو +W ءلا +W ليعبد +W لاه +W مخلصين +W له +W دين +W حنفاء +W ويقيم +W صلات +W ويءت +W زكات +W وذالك +W دين +W لقيمه +W ءن +W لذين +W كفرو +W من +W ءهل +W لكتاب +W ولمشركين +W في +W نار +W جهنم +W خالدين +W فيها +W ءلاءك +W هم +W شر +W لبريه +W ءن +W لذين +W ءامنو +W وعمل +W صالحات +W ءلاءك +W هم +W خير +W لبريه +W جزاءهم +W عند +W ربهم +W جنات +W عدن +W تجري +W من +W تحته +W لءنهار +W خالدين +W فيها +W ءبد +W رضي +W لاه +W عنهم +W ورضو +W عنه +W ذالك +W لمن +W خشي +W ربه +W ءذا +W زلزلت +W لءرض +W زلزالها +W وءخرجت +W لءرض +W ءثقالها +W وقال +W لءنسان +W ما +W لها +W يومءذن +W تحدث +W ءخبارها +W بءن +W ربك +W ءوحا +W لها +W يومءذي +W يصدر +W ناس +W ءشتات +W ليرو +W ءعمالهم +W فمي +W يعمل +W مثقال +W ذرتن +W خيري +W يره +W ومي +W يعمل +W مثقال +W ذرتن +W شري +W يره +W ولعاديات +W ضبحا +W فلموريات +W قدحا +W فلمغيرات +W صبحا +W فءثرن +W بهي +W نقعا +W فوسطن +W بهي +W جمعا +W ءن +W لءنسان +W لربهي +W لكنود +W وءنهو +W علا +W ذالك +W لشهيد +W وءنهو +W لحب +W لخير +W لشديد +W ءفلا +W يعلم +W ءذا +W بعثر +W ما +W ف +W لقبور +W وحصل +W ما +W ف +W صدور +W ءن +W ربهم +W بهم +W يومءذ +W لخبير +W ءلقارعه +W م +W لقارعه +W وما +W ءدراك +W م +W لقارعه +W يوم +W يكون +W ناس +W كلفراش +W لمبثوث +W وتكون +W لجبال +W كلعهن +W لمنفوش +W فءما +W من +W ثقلت +W موازينه +W فهو +W في +W عيشت +W راضيه +W وءما +W من +W خفت +W موازينه +W فءمهو +W هاويه +W وما +W ءدراك +W ما +W هيه +W نارن +W حاميه +W ءلهاكم +W تكاثر +W حتا +W زرتم +W لمقابر +W كلا +W سوف +W تعلمون +W ثم +W كلا +W سوف +W تعلمون +W كلا +W لو +W تعلمون +W علم +W ليقين +W لترون +W لجحيم +W ثم +W لترونها +W عين +W ليقين +W ثم +W لتسءلن +W يومءذن +W عن +W نعيم +W ولعصر +W ءن +W لءنسان +W لفي +W خسر +W ءل +W لذين +W ءامنو +W وعمل +W صالحات +W وتواصو +W بلحق +W وتواصو +W بصبر +W ويل +W لكل +W همزت +W لمزه +W ءلذي +W جمع +W مالو +W وعده +W يحسب +W ءن +W مالهو +W ءخلده +W كلا +W ليمبذن +W ف +W لحطمه +W وما +W ءدراك +W م +W لحطمه +W نار +W لاه +W لموقده +W ءلتي +W تطلع +W عل +W لءفءده +W ءنها +W عليه +W مءصده +W في +W عمد +W مده +W ءلم +W تر +W كيف +W فعل +W ربك +W بءصحاب +W لفيل +W ءلم +W يجعل +W كيدهم +W في +W تضليل +W وءرسل +W عليهم +W طيرن +W ءبابيل +W ترميهم +W بحجارت +W من +W سجيل +W فجعلهم +W كعصف +W مءكول +W لءيلاف +W قريش +W ءيلافهم +W رحلت +W شتاء +W وصيف +W فليعبدو +W رب +W هاذ +W لبيت +W ءلذي +W ءطعمه +W من +W جوعو +W وءامنه +W من +W خوف +W ءرءيت +W لذي +W يكذب +W بدين +W فذالك +W لذي +W يدع +W ليتيم +W ولا +W يحض +W علا +W طعام +W لمسكين +W فويل +W لمصلين +W ءلذين +W هم +W عن +W صلاتهم +W ساهون +W ءلذين +W هم +W يراءون +W ويمنعون +W لماعون +W ءنا +W ءعطيناك +W لكوثر +W فصل +W لربك +W ونحر +W ءن +W شانءك +W هو +W لءبتر +W قل +W ياءيه +W لكافرون +W لا +W ءعبد +W ما +W تعبدون +W ولا +W ءنتم +W عابدون +W ما +W ءعبد +W ولا +W ءن +W عابد +W ما +W عبتم +W ولا +W ءنتم +W عابدون +W ما +W ءعبد +W لكم +W دينكم +W ولي +W دين +W ءذا +W جاء +W نصر +W لاه +W ولفتح +W ورءيت +W ناس +W يدخلون +W في +W دين +W لاه +W ءفواجا +W فسبح +W بحمد +W ربك +W وستغفره +W ءنهو +W كان +W توابا +W تبت +W يدا +W ءبي +W لهبو +W وتب +W ما +W ءغنا +W عنه +W مالهو +W وما +W كسب +W سيصلا +W نارن +W ذات +W لهب +W ومرءتهو +W حمالت +W لحطب +W في +W جيدها +W حبل +W م +W مسد +W قل +W هو +W لاه +W ءحد +W ءلاه +W صمد +W لم +W يلد +W ولم +W يولد +W ولم +W يك +W لهو +W كفون +W ءحد +W قل +W ءعوذ +W برب +W لفلق +W من +W شر +W ما +W خلق +W ومن +W شر +W غاسقن +W ءذا +W وقب +W ومن +W شر +W نفاثات +W ف +W لعقد +W ومن +W شر +W حاسدن +W ءذا +W حسد +W قل +W ءعوذ +W برب +W ناس +W ملك +W ناس +W ءلاه +W ناس +W من +W شر +W لوسواس +W لخناس +W ءلذي +W يوسوس +W في +W صدور +W ناس +W من +W لجنت +W وناس +P isti'adha ءعوذبلاهمنشيطانرجيم +P basmala بسملاهرحمانرحيم +A 95001,95001,95002,95002,95003,95003,95003,95004,95004,95004,95004,95004,95004,95005,95005,95005,95005,95006,95006,95006,95006,95006,95006,95006,95006,95006,95007,95007,95007,95007,95008,95008,95008,95008,96001,96001,96001,96001,96001,96002,96002,96002,96002,96003,96003,96003,96004,96004,96004,96005,96005,96005,96005,96005,96006,96006,96006,96006,96007,96007,96007,96008,96008,96008,96008,96009,96009,96009,96010,96010,96010,96011,96011,96011,96011,96011,96012,96012,96012,96013,96013,96013,96013,96014,96014,96014,96014,96014,96015,96015,96015,96015,96015,96015,96016,96016,96016,96017,96017,96018,96018,96019,96019,96019,96019,96019,97001,97001,97001,97001,97001,97002,97002,97002,97002,97002,97003,97003,97003,97003,97003,97003,97004,97004,97004,97004,97004,97004,97004,97004,97004,97005,97005,97005,97005,97005,98001,98001,98001,98001,98001,98001,98001,98001,98001,98001,98001,98001,98002,98002,98002,98002,98002,98002,98003,98003,98003,98004,98004,98004,98004,98004,98004,98004,98004,98004,98004,98004,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98005,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98006,98007,98007,98007,98007,98007,98007,98007,98007,98007,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,98008,99001,99001,99001,99001,99002,99002,99002,99003,99003,99003,99003,99004,99004,99004,99005,99005,99005,99005,99006,99006,99006,99006,99006,99006,99007,99007,99007,99007,99007,99007,99008,99008,99008,99008,99008,99008,100001,100001,100002,100002,100003,100003,100004,100004,100004,100005,100005,100005,100006,100006,100006,100006,100007,100007,100007,100007,100008,100008,100008,100008,100009,100009,100009,100009,100009,100009,100009,100010,100010,100010,100010,100011,100011,100011,100011,100011,101001,101002,101002,101003,101003,101003,101003,101004,101004,101004,101004,101004,101005,101005,101005,101005,101006,101006,101006,101006,101007,101007,101007,101007,101008,101008,101008,101008,101009,101009,101010,101010,101010,101010,101011,101011,102001,102001,102002,102002,102002,102003,102003,102003,102004,102004,102004,102004,102005,102005,102005,102005,102005,102006,102006,102007,102007,102007,102007,102008,102008,102008,102008,102008,103001,103002,103002,103002,103002,103003,103003,103003,103003,103003,103003,103003,103003,103003,104001,104001,104001,104001,104002,104002,104002,104002,104003,104003,104003,104003,104004,104004,104004,104004,104005,104005,104005,104005,104006,104006,104006,104007,104007,104007,104007,104008,104008,104008,104009,104009,104009,105001,105001,105001,105001,105001,105001,105001,105002,105002,105002,105002,105002,105003,105003,105003,105003,105004,105004,105004,105004,105005,105005,105005,106001,106001,106002,106002,106002,106002,106003,106003,106003,106003,106004,106004,106004,106004,106004,106004,106004,107001,107001,107001,107001,107002,107002,107002,107002,107003,107003,107003,107003,107003,107004,107004,107005,107005,107005,107005,107005,107006,107006,107006,107007,107007,108001,108001,108001,108002,108002,108002,108003,108003,108003,108003,109001,109001,109001,109002,109002,109002,109002,109003,109003,109003,109003,109003,109004,109004,109004,109004,109004,109005,109005,109005,109005,109005,109006,109006,109006,109006,110001,110001,110001,110001,110001,110002,110002,110002,110002,110002,110002,110002,110003,110003,110003,110003,110003,110003,110003,111001,111001,111001,111001,111001,111002,111002,111002,111002,111002,111002,111003,111003,111003,111003,111004,111004,111004,111005,111005,111005,111005,111005,112001,112001,112001,112001,112002,112002,112003,112003,112003,112003,112004,112004,112004,112004,112004,113001,113001,113001,113001,113002,113002,113002,113002,113003,113003,113003,113003,113003,113004,113004,113004,113004,113004,113005,113005,113005,113005,113005,114001,114001,114001,114001,114002,114002,114003,114003,114004,114004,114004,114004,114005,114005,114005,114005,114005,114006,114006,114006 +C max_missed_words=2;skip_ayat=0 +I start=297;window=560 +S +F ء,8400 +F ل,8800 +F ه,9300;ا,9300 +F ك,9800 +S +F م,10300 +F ت,10800 +F ك,11200;ا,11200 +F ث,11700 +S +F ر,12200 +F ح,13200 +F ت,13600 +F ا,14100 +F ت,14600;ر,14600 +S +F ج,15100 +F م,15600 +F ل,16000;م,16000 +F ق,16500 +F ا,17000;ب,17000 +F ر,17500 +S +F ف,18400 +F ل,18900 +F ا,19400 +F ت,19900 +F و,20400;ف,20400 +F ت,20800 +F ع,21300 +F ل,21800 +S +F م,22300 +F و,23200;ن,23200 +S +F ث,29500 +F م,30400 +F ك,30900 +F ل,31400 +F ا,31900 +F س,32400;و,32400 +F ف,32800 +F ت,33300 +F ع,33800;ل,33800 +F م,34300 +S +F و,35700;ن,35700 +F ء,36700 +F ل,37600;ا,37600 +F ل,38100 +F و,38600;ت,38600 +F ع,39100 +F ل,39600 +F م,40000 +F و,40500;ن,40500 +F ع,41000 +F ل,41500;م,41500 +F ل,42000 +F ي,42400 +F ق,42900 +S +F ي,43900;ن,43900 diff --git a/feature/progress/build.gradle.kts b/feature/progress/build.gradle.kts new file mode 100644 index 0000000000..3513f99904 --- /dev/null +++ b/feature/progress/build.gradle.kts @@ -0,0 +1,61 @@ +plugins { + id("quran.android.library.compose") + alias(libs.plugins.metro) +} + +android { + namespace = "com.quran.mobile.feature.progress" + defaultConfig { + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + testOptions.unitTests.isIncludeAndroidResources = true + // library modules only build release; the screenshot test runs against it + testBuildType = "release" + // the sample data both the renders and the device screenshots draw + sourceSets["test"].kotlin.srcDir("src/sharedTest/kotlin") + sourceSets["androidTest"].kotlin.srcDir("src/sharedTest/kotlin") +} + +// -Pprogress.render: ProgressScreenRenderTest draws the Progress screens to +// build/outputs/progress-renders (phones upright and on their side, a small phone, tablets, the +// MatePad 12 X landscape and portrait; English and Arabic; day and night) to look at them. The +// tablet-sized bitmaps need more than the default heap. +tasks.withType().configureEach { + if (providers.gradleProperty("progress.render").isPresent) { + systemProperty("progress.render", "true") + maxHeapSize = "2g" + } +} + +dependencies { + implementation(project(":common:data")) + implementation(project(":common:di")) + implementation(project(":common:pages")) + implementation(project(":common:progress")) + implementation(project(":common:ui:core")) + + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.appcompat) + implementation(libs.androidx.annotation) + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.preference.ktx) + implementation(libs.androidx.work.runtime.ktx) + implementation(libs.compose.animation) + implementation(libs.compose.foundation) + implementation(libs.compose.material3) + implementation(libs.compose.ui) + implementation(libs.kotlinx.coroutines.android) + implementation(libs.kotlinx.coroutines.core) + implementation(libs.kotlinx.collections.immutable) + + testImplementation(project(":pages:data:madani")) + testImplementation(libs.junit) + testImplementation(libs.truth) + testImplementation(libs.robolectric) + testImplementation(libs.androidx.junit) + testImplementation(libs.kotlinx.coroutines.test) + + androidTestImplementation(project(":pages:data:madani")) + androidTestImplementation(libs.androidx.test.runner) + androidTestImplementation(libs.androidx.junit) +} diff --git a/feature/progress/src/androidTest/AndroidManifest.xml b/feature/progress/src/androidTest/AndroidManifest.xml new file mode 100644 index 0000000000..6d650e8778 --- /dev/null +++ b/feature/progress/src/androidTest/AndroidManifest.xml @@ -0,0 +1,10 @@ + + + + + + + diff --git a/feature/progress/src/androidTest/kotlin/com/quran/mobile/feature/progress/ui/ProgressScreenshotsTest.kt b/feature/progress/src/androidTest/kotlin/com/quran/mobile/feature/progress/ui/ProgressScreenshotsTest.kt new file mode 100644 index 0000000000..f2441c9dae --- /dev/null +++ b/feature/progress/src/androidTest/kotlin/com/quran/mobile/feature/progress/ui/ProgressScreenshotsTest.kt @@ -0,0 +1,94 @@ +package com.quran.mobile.feature.progress.ui + +import android.content.res.Configuration +import android.graphics.Bitmap +import android.util.Log +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.unit.LayoutDirection +import androidx.test.core.app.ActivityScenario +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.quran.labs.androidquran.common.ui.core.QuranTheme +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import java.util.Locale +import java.util.TimeZone + +/** + * Draws Progress on the device it runs on (e.g. Test Lab's virtual tablet and phone) and keeps a + * screenshot of each screen in English and Arabic, by day and night, in /sdcard/progress-shots (Test + * Lab pulls that folder). The data is [SampleStates]'. + */ +@RunWith(AndroidJUnit4::class) +class ProgressScreenshotsTest { + + @Test + fun progressScreens() { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val own = File(instrumentation.targetContext.getExternalFilesDir(null), "progress-shots").apply { mkdirs() } + TimeZone.setDefault(TimeZone.getTimeZone("UTC")) + val device = with(instrumentation.targetContext.resources.configuration) { "w${screenWidthDp}dp-h${screenHeightDp}dp" } + var taken = 0 + ActivityScenario.launch(ComponentActivity::class.java).use { scenario -> + for (arabic in listOf(false, true)) { + val locale = if (arabic) Locale.forLanguageTag("ar-EG") else Locale.US + Locale.setDefault(locale) + val state = SampleStates.state(arabic) + for (dark in listOf(false, true)) { + for ((name, selection) in SampleStates.screens) { + scenario.onActivity { activity -> + val config = Configuration(activity.resources.configuration).apply { + setLocale(locale) + setLayoutDirection(locale) + uiMode = (uiMode and Configuration.UI_MODE_NIGHT_MASK.inv()) or + if (dark) Configuration.UI_MODE_NIGHT_YES else Configuration.UI_MODE_NIGHT_NO + } + val context = activity.createConfigurationContext(config) + activity.setContent { + CompositionLocalProvider( + LocalContext provides context, + LocalConfiguration provides config, + LocalLayoutDirection provides if (arabic) LayoutDirection.Rtl else LayoutDirection.Ltr, + ) { + QuranTheme(useDarkTheme = dark) { + Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surface)) { + ProgressScreen(state, selection, ProgressActions(), dark) + } + } + } + } + } + instrumentation.waitForIdleSync() + Thread.sleep(SETTLE_MS) + val shot: Bitmap = instrumentation.uiAutomation.takeScreenshot() ?: continue + val file = File(own, "${name}_${if (arabic) "ar" else "en"}_${if (dark) "dark" else "light"}.png") + file.outputStream().use { shot.compress(Bitmap.CompressFormat.PNG, 100, it) } + taken++ + } + } + } + } + // where Test Lab (and adb, as the shell) can pull them from + instrumentation.uiAutomation.executeShellCommand("mkdir -p $SHARED").close() + instrumentation.uiAutomation.executeShellCommand("cp -r ${own.absolutePath}/. $SHARED/").close() + Log.i(TAG, "took $taken screenshots on $device into $SHARED") + } + + private companion object { + const val TAG = "ProgressScreenshots" + const val SHARED = "/sdcard/progress-shots" + // on an emulator the first switch between screens can take longer than a frame or two + const val SETTLE_MS = 1_500L + } +} diff --git a/feature/progress/src/main/AndroidManifest.xml b/feature/progress/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..cbaa00a983 --- /dev/null +++ b/feature/progress/src/main/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ProgressActivity.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ProgressActivity.kt new file mode 100644 index 0000000000..1b588f8fff --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ProgressActivity.kt @@ -0,0 +1,201 @@ +package com.quran.mobile.feature.progress + +import android.Manifest +import android.app.TimePickerDialog +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.Bundle +import android.provider.Settings +import android.text.format.DateFormat +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AppCompatActivity +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.listSaver +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.runtime.CompositionLocalProvider +import androidx.lifecycle.lifecycleScope +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.labs.androidquran.common.ui.core.QuranTheme +import com.quran.labs.androidquran.common.ui.core.ReadingBookmarkSlots +import com.quran.mobile.di.QuranApplicationComponentProvider +import com.quran.mobile.feature.progress.bookmarks.BookmarkEditor +import com.quran.mobile.feature.progress.data.ProgressMapper +import com.quran.mobile.feature.progress.di.ProgressComponentInterface +import com.quran.mobile.feature.progress.ui.LocalSuraNames +import com.quran.mobile.feature.progress.ui.ProgressActions +import com.quran.mobile.feature.progress.ui.ProgressScreen +import com.quran.mobile.feature.progress.ui.ProgressSection +import com.quran.mobile.feature.progress.ui.ProgressSelection +import com.quran.mobile.feature.progress.ui.ReminderView +import com.quran.mobile.feature.progress.ui.noonOf +import kotlinx.coroutines.launch +import java.util.Calendar + +/** + * Progress: every reading bookmark's cycle and days, memorizing, salah and sessions. Opens on a + * bookmark ([EXTRA_BOOKMARK]) or on the bookmark editor ([EXTRA_EDIT_BOOKMARKS]). + */ +class ProgressActivity : AppCompatActivity() { + + private val component by lazy { + (application as QuranApplicationComponentProvider).provideQuranApplicationComponent() as ProgressComponentInterface + } + private var notificationsAllowed by mutableStateOf(false) + + private val notificationPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + notificationsAllowed = component.reminderNotifier().allowed() + if (!granted && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + !shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS) + ) { + openNotificationSettings() + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + val preferences = component.progressPreferences() + val naming = component.quranNaming() + val initialBookmark = intent.getStringExtra(EXTRA_BOOKMARK)?.let { name -> + ReadingBookmarkType.entries.firstOrNull { it.name == name } + } + val mapper = ProgressMapper( + bookmarkName = { slot, name -> ReadingBookmarkSlots.displayName(this, slot, name) }, + suraName = { sura -> naming.getSuraName(this, sura, false) }, + dayOfMonth = { day -> Calendar.getInstance().apply { timeInMillis = noonOf(day) }.get(Calendar.DAY_OF_MONTH) }, + ) + val snapshots = component.progressRepository().snapshots() + + setContent { + val snapshot by remember { snapshots }.collectAsState(null) + val changes by preferences.changes.collectAsState(0) + var selection by rememberSaveable(stateSaver = SelectionSaver) { + mutableStateOf(ProgressSelection(bookmark = initialBookmark)) + } + var editing by rememberSaveable { mutableStateOf(intent.getBooleanExtra(EXTRA_EDIT_BOOKMARKS, false)) } + var confirmCycle by remember { mutableStateOf(null) } + val reminder = remember(changes, notificationsAllowed) { + ReminderView(preferences.reminder, preferences.reminderMinute, notificationsAllowed) + } + val state = remember(snapshot, reminder) { + snapshot?.let { mapper.map(it, reminder, offered = ReadingBookmarkType.entries.size) } + } + val dark = isSystemInDarkTheme() + + QuranTheme { + CompositionLocalProvider(LocalSuraNames provides { sura -> naming.getSuraName(this, sura, false) }) { + when { + editing -> BookmarkEditor( + slotSettings = component.readingBookmarkSlotSettings(), + readingBookmarksDao = component.readingBookmarksDao(), + onBack = { + if (intent.getBooleanExtra(EXTRA_EDIT_BOOKMARKS, false)) finish() else editing = false + }, + ) + state != null -> ProgressScreen( + state = state, + selection = selection, + actions = ProgressActions( + onSelection = { selection = it }, + onAddBookmark = { editing = true }, + onAllowNotifications = ::allowNotifications, + onReminderTime = ::pickReminderTime, + onStartCycle = { confirmCycle = it }, + onPlayRecording = { id -> component.recordedSessionLaunchers().firstOrNull()?.open(this, id) }, + onBack = ::finish, + ), + dark = dark, + ) + } + confirmCycle?.let { slot -> + AlertDialog( + onDismissRequest = { confirmCycle = null }, + text = { Text(getString(R.string.progress_start_cycle)) }, + confirmButton = { + TextButton(onClick = { + confirmCycle = null + lifecycleScope.launch { component.bookmarkMoveRecorder().markCycleStart(slot.name) } + }) { Text(getString(android.R.string.ok)) } + }, + dismissButton = { + TextButton(onClick = { confirmCycle = null }) { Text(getString(android.R.string.cancel)) } + }, + ) + } + } + } + } + } + + override fun onResume() { + super.onResume() + notificationsAllowed = component.reminderNotifier().allowed() + } + + private fun allowNotifications() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS) + } else { + openNotificationSettings() + } + } + + private fun openNotificationSettings() { + val settings = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).putExtra(Settings.EXTRA_APP_PACKAGE, packageName) + runCatching { startActivity(settings) } + } + + private fun pickReminderTime() { + val preferences = component.progressPreferences() + val minute = preferences.reminderMinute + TimePickerDialog( + this, + { _, hour, minuteOfHour -> + preferences.reminderMinute = hour * 60 + minuteOfHour + preferences.reminder = true + component.reminderScheduler().reschedule() + if (!component.reminderNotifier().allowed()) allowNotifications() + }, + minute / 60, + minute % 60, + DateFormat.is24HourFormat(this), + ).show() + } + + companion object { + const val EXTRA_BOOKMARK = "progress_bookmark" + const val EXTRA_EDIT_BOOKMARKS = "progress_edit_bookmarks" + + /** Progress, open on [bookmark] if given. */ + fun intent(context: Context, bookmark: ReadingBookmarkType? = null): Intent = + Intent(context, ProgressActivity::class.java).apply { + bookmark?.let { putExtra(EXTRA_BOOKMARK, it.name) } + } + + /** The bookmark editor (from Settings). */ + fun editBookmarksIntent(context: Context): Intent = + Intent(context, ProgressActivity::class.java).putExtra(EXTRA_EDIT_BOOKMARKS, true) + + private val SelectionSaver = listSaver( + save = { listOf(it.section.name, it.bookmark?.name, it.session) }, + restore = { saved -> + ProgressSelection( + section = ProgressSection.entries.firstOrNull { it.name == saved[0] } ?: ProgressSection.BOOKMARKS, + bookmark = ReadingBookmarkType.entries.firstOrNull { it.name == saved[1] }, + session = saved[2], + ) + }, + ) + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ProgressScreenProvider.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ProgressScreenProvider.kt new file mode 100644 index 0000000000..dd44aa63ac --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ProgressScreenProvider.kt @@ -0,0 +1,21 @@ +package com.quran.mobile.feature.progress + +import android.content.Context +import com.quran.data.di.AppScope +import com.quran.mobile.di.ExtraScreenProvider +import dev.zacsweers.metro.ContributesIntoSet +import dev.zacsweers.metro.Inject + +/** "Progress" in the main screen's menu. */ +@ContributesIntoSet(AppScope::class) +@Inject +class ProgressScreenProvider : ExtraScreenProvider { + override val order: Int = 10 + override val id: Int = R.id.progress_menu + override val titleResId: Int = R.string.progress_title + + override fun onClick(context: Context): Boolean { + context.startActivity(ProgressActivity.intent(context)) + return true + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ProgressStartup.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ProgressStartup.kt new file mode 100644 index 0000000000..cd5ef34f8d --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ProgressStartup.kt @@ -0,0 +1,20 @@ +package com.quran.mobile.feature.progress + +import com.quran.data.di.AppScope +import com.quran.mobile.feature.progress.reminder.ReminderScheduler +import com.quran.mobile.progress.log.BookmarkMoveRecorder +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn + +/** What Progress does when the app starts: keep each bookmark's moves, and the daily reminder's check. */ +@SingleIn(AppScope::class) +class ProgressStartup @Inject constructor( + private val recorder: BookmarkMoveRecorder, + private val reminderScheduler: ReminderScheduler, +) { + /** Call once WorkManager is initialized. */ + fun start() { + recorder.start() + reminderScheduler.ensure() + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/bookmarks/BookmarkEditor.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/bookmarks/BookmarkEditor.kt new file mode 100644 index 0000000000..e4a13eef62 --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/bookmarks/BookmarkEditor.kt @@ -0,0 +1,205 @@ +package com.quran.mobile.feature.progress.bookmarks + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.unit.dp +import com.quran.data.dao.ReadingBookmarkSlotSettings +import com.quran.data.dao.ReadingBookmarksDao +import com.quran.data.model.bookmark.ReadingBookmarkPurpose +import com.quran.data.model.bookmark.ReadingBookmarkSlotSetting +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.labs.androidquran.common.ui.core.QuranIcons +import com.quran.labs.androidquran.common.ui.core.ReadingBookmarkSlots +import com.quran.mobile.feature.progress.R +import com.quran.mobile.feature.progress.ui.ProgressIcons +import com.quran.mobile.feature.progress.ui.bookmarkColor +import com.quran.mobile.feature.progress.ui.purposeName +import kotlinx.coroutines.launch +import androidx.appcompat.R as AppCompatR + +/** Days a reading cycle may be set to finish in (0: no deadline). */ +private val TargetDays = listOf(0, 7, 10, 15, 20, 30, 40, 60) + +/** + * The reading bookmarks: the three synced ones, and five more that can be turned on and stay on this + * device. Each can be named, and set to what it's for; a reading bookmark also to the days a cycle + * should take. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun BookmarkEditor( + slotSettings: ReadingBookmarkSlotSettings, + readingBookmarksDao: ReadingBookmarksDao, + onBack: () -> Unit, +) { + val settings by remember { slotSettings.settingsFlow() }.collectAsState(null) + val bookmarks by remember { readingBookmarksDao.readingBookmarksFlow() }.collectAsState(null) + val names = remember(bookmarks) { bookmarks.orEmpty().associate { it.slot to it.name } } + val drafts = remember { mutableStateMapOf() } + val scope = rememberCoroutineScope() + + fun save(slot: ReadingBookmarkType) { + val draft = drafts.remove(slot) ?: return + val name = draft.trim().ifBlank { null } + if (name != names[slot]) scope.launch { readingBookmarksDao.renameReadingBookmark(slot, name) } + } + + fun back() { + drafts.keys.toList().forEach(::save) + onBack() + } + BackHandler(onBack = ::back) + + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.progress_editor_title)) }, + navigationIcon = { + IconButton(onClick = ::back) { + Icon( + QuranIcons.ArrowBack, + contentDescription = stringResource(AppCompatR.string.abc_action_bar_up_description), + ) + } + }, + ) + }, + ) { padding -> + LazyColumn(Modifier.fillMaxSize().padding(padding), horizontalAlignment = Alignment.CenterHorizontally) { + item { + Text( + stringResource(R.string.progress_editor_explained), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.widthIn(max = 720.dp).fillMaxWidth().padding(horizontal = 20.dp, vertical = 12.dp), + ) + } + items(settings.orEmpty(), key = { it.slot.name }) { setting -> + SlotRow( + setting = setting, + name = drafts[setting.slot] ?: names[setting.slot].orEmpty(), + onName = { drafts[setting.slot] = it }, + onNameDone = { save(setting.slot) }, + onEnabled = { enabled -> scope.launch { slotSettings.setEnabled(setting.slot, enabled) } }, + onPurpose = { purpose -> scope.launch { slotSettings.setPurpose(setting.slot, purpose) } }, + onDays = { days -> scope.launch { slotSettings.setTargetDays(setting.slot, days) } }, + modifier = Modifier.widthIn(max = 720.dp).fillMaxWidth(), + ) + } + } + } +} + +@Composable +private fun SlotRow( + setting: ReadingBookmarkSlotSetting, + name: String, + onName: (String) -> Unit, + onNameDone: () -> Unit, + onEnabled: (Boolean) -> Unit, + onPurpose: (ReadingBookmarkPurpose) -> Unit, + onDays: (Int) -> Unit, + modifier: Modifier = Modifier, +) { + val slot = setting.slot + Column(modifier.padding(horizontal = 20.dp, vertical = 12.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(ProgressIcons.Bookmark, contentDescription = null, tint = bookmarkColor(slot), modifier = Modifier.size(24.dp)) + Column(Modifier.weight(1f).padding(start = 16.dp)) { + Text( + ReadingBookmarkSlots.displayName(slot, name.takeIf { it.isNotBlank() }), + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface, + ) + Text( + stringResource(if (slot.synced) R.string.progress_editor_synced else R.string.progress_editor_device), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (!slot.synced) Switch(checked = setting.enabled, onCheckedChange = onEnabled) + } + if (setting.enabled) { + OutlinedTextField( + value = name, + onValueChange = onName, + label = { Text(stringResource(R.string.progress_editor_name)) }, + placeholder = { Text(stringResource(ReadingBookmarkSlots[slot].nameResourceId)) }, + singleLine = true, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), + keyboardActions = KeyboardActions(onDone = { onNameDone() }), + modifier = Modifier + .fillMaxWidth() + .padding(top = 12.dp) + .onFocusChanged { if (!it.isFocused) onNameDone() }, + ) + Text( + stringResource(R.string.progress_editor_for), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 12.dp), + ) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + ReadingBookmarkPurpose.entries.forEach { purpose -> + FilterChip(selected = setting.purpose == purpose, onClick = { onPurpose(purpose) }, label = { Text(purposeName(purpose)) }) + } + } + if (setting.purpose == ReadingBookmarkPurpose.READING) { + Text( + stringResource(R.string.progress_editor_days), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 8.dp), + ) + Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + TargetDays.forEach { days -> + FilterChip( + selected = setting.targetDays == days, + onClick = { onDays(days) }, + label = { + Text(if (days == 0) stringResource(R.string.progress_no_deadline) else pluralStringResource(R.plurals.progress_days, days, days)) + }, + ) + } + } + } + } + } + HorizontalDivider(modifier, color = MaterialTheme.colorScheme.outlineVariant) +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/data/ProgressMapper.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/data/ProgressMapper.kt new file mode 100644 index 0000000000..f855faf7ef --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/data/ProgressMapper.kt @@ -0,0 +1,152 @@ +package com.quran.mobile.feature.progress.data + +import com.quran.data.model.bookmark.ReadingBookmarkPurpose +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.mobile.feature.progress.ui.BookmarkPlace +import com.quran.mobile.feature.progress.ui.BookmarkView +import com.quran.mobile.feature.progress.ui.DayColumn +import com.quran.mobile.feature.progress.ui.JuzLineState +import com.quran.mobile.feature.progress.ui.JuzPages +import com.quran.mobile.feature.progress.ui.MemorizingView +import com.quran.mobile.feature.progress.ui.ProgressUiState +import com.quran.mobile.feature.progress.ui.ReminderView +import com.quran.mobile.feature.progress.ui.SalahView +import com.quran.mobile.feature.progress.ui.SessionAyahView +import com.quran.mobile.feature.progress.ui.SessionView +import com.quran.mobile.progress.summary.BookmarkProgress +import com.quran.mobile.progress.summary.ProgressCalculator +import com.quran.mobile.progress.summary.SessionDay +import kotlinx.collections.immutable.toImmutableList +import kotlinx.collections.immutable.toImmutableMap +import kotlin.math.roundToInt + +/** + * Turns a [ProgressSnapshot] into what the screen shows. + * + * @param bookmarkName a bookmark's name: the user's, or its colour's. + * @param suraName a sura's name. + * @param dayOfMonth a local day's day of the month, which labels a chart of the last 30 days. + */ +class ProgressMapper( + private val bookmarkName: (ReadingBookmarkType, String?) -> String, + private val suraName: (Int) -> String, + private val dayOfMonth: (Long) -> Int, +) { + + fun map(snapshot: ProgressSnapshot, reminder: ReminderView, offered: Int): ProgressUiState { + val calculator = snapshot.calculator + val bookmarks = snapshot.bookmarks.map { bookmark(it, calculator, snapshot.today) } + val heldMost = snapshot.memorizing.juz.filter { it.held > 0 }.maxByOrNull { it.held }?.number + return ProgressUiState( + today = snapshot.today, + bookmarks = bookmarks.toImmutableList(), + memorizing = MemorizingView( + focusJuz = bookmarks.firstOrNull { it.purpose == ReadingBookmarkPurpose.MEMORIZATION && it.juz != null }?.juz ?: heldMost, + juz = snapshot.memorizing.juz.toImmutableList(), + suras = snapshot.memorizing.suras.mapValues { it.value.toImmutableList() }.toImmutableMap(), + days = sessionColumns(snapshot.memorizing.days, snapshot.today) { it.accuracy to it.hinted }, + averageAccuracy = snapshot.memorizing.days.filter { it.words > 0 }.takeIf { it.isNotEmpty() } + ?.let { days -> days.sumOf { it.recited } * 100 / days.sumOf { it.words } }, + hasHistory = snapshot.memorizing.hasData, + ), + salah = SalahView( + days = sessionColumns(snapshot.salah.days, snapshot.today) { it.sessions to it.hinted }, + prayers = snapshot.salah.days.sumOf { it.sessions }, + hasHistory = snapshot.salah.hasData, + ), + sessions = snapshot.sessions.asReversed().map { logged -> + val record = logged.record + SessionView( + id = record.id, + title = passage(record.startSura, record.startAyah, record.endSura, record.endAyah), + day = logged.day, + startedAtMs = record.startedAtMs, + mode = record.mode, + from = "${suraName(record.startSura)} ${record.startSura}:${record.startAyah}", + to = "${suraName(record.endSura)} ${record.endSura}:${record.endAyah}", + minutes = ((record.endedAtMs - record.startedAtMs + 59_999L) / 60_000L).toInt(), + recited = record.recited, + hinted = record.hinted, + missed = record.missed, + finished = record.finished, + recordingId = record.recordingId, + ayahs = record.ayahs.map { + SessionAyahView(suraName(it.sura), it.sura, it.ayah, it.ayahWords, it.words, it.hinted, it.missed) + }.toImmutableList(), + ) + }.toImmutableList(), + uncreditedTodayMinutes = (snapshot.uncreditedTodayMs / 60_000L).toInt(), + reminder = reminder, + canAddBookmark = snapshot.bookmarks.size < offered, + ) + } + + private fun bookmark(progress: BookmarkProgress, calculator: ProgressCalculator, today: Long): BookmarkView { + val position = progress.position + val page = position?.let(calculator::pageOf) + val pace = progress.pace + val startPage = progress.cycleStartPage + val cycleChart = pace != null + val columns = (0 until progress.chartDays).map { index -> + val day = progress.firstDay + index + val amount = progress.days.getOrNull(index) + DayColumn( + dayN = index + 1, + label = if (cycleChart) index + 1 else dayOfMonth(day), + above = if (day > today) null else amount?.pages ?: 0, + below = if (day > today) null else amount?.minutes ?: 0, + isToday = day == today, + ) + } + val elapsed = progress.days + val juzPages = (1..30).map { juz -> + val pages = calculator.juzPages(juz) + val read = if (page == null || startPage == null) 0 else (pages.first..pages.last).count { it in startPage until page } + JuzPages(juz, pages.first, pages.last, read) + } + return BookmarkView( + slot = progress.slot, + name = bookmarkName(progress.slot, progress.name), + purpose = progress.purpose, + targetDays = progress.targetDays, + place = position?.let { BookmarkPlace(page!!, suraName(it.sura), it.sura, it.ayah) }, + juz = position?.let { calculator.juzOf(it.sura, it.ayah) }, + cycleStartDay = progress.cycle?.takeIf { !it.partial }?.startDay, + followedSinceDay = progress.cycle?.takeIf { it.partial }?.startDay, + dayN = pace?.dayN, + finishByDay = pace?.finishByDay, + overdue = pace?.overdue == true, + ahead = pace?.ahead, + line = JuzLineState( + position = page?.let(calculator::juzPosition), + runStart = startPage?.let(calculator::juzPosition), + pace = pace?.let { calculator.juzPosition((startPage ?: 1) + it.expectedByToday.coerceAtMost(it.totalPages - 1)) }, + current = position?.let { calculator.juzOf(it.sura, it.ayah) }, + juz = juzPages.toImmutableList(), + ), + days = columns.toImmutableList(), + goal = pace?.let { (it.totalPages.toDouble() / it.targetDays).roundToInt() }, + averageMinutes = elapsed.takeIf { it.isNotEmpty() }?.let { days -> days.sumOf { it.minutes } / days.size }, + todayMinutes = progress.today?.takeIf { it.day == today }?.minutes, + cycleReadingMs = progress.cycleReadingMs, + cyclePages = progress.cyclePages, + lastCycleDays = progress.lastCycle?.days, + lastCycleStartDay = progress.lastCycle?.startDay, + lastCycleEndDay = progress.lastCycle?.endDay, + hasHistory = progress.moved, + ) + } + + /** E.g. "Al-Ikhlas 1–4", or "Al-Falaq 1 – An-Nas 6" across suras. */ + private fun passage(startSura: Int, startAyah: Int, endSura: Int, endAyah: Int): String = when { + startSura != endSura -> "${suraName(startSura)} $startAyah – ${suraName(endSura)} $endAyah" + startAyah == endAyah -> "${suraName(startSura)} $startAyah" + else -> "${suraName(startSura)} $startAyah–$endAyah" + } + + private fun sessionColumns(days: List, today: Long, values: (SessionDay) -> Pair) = + days.mapIndexed { index, day -> + val (above, below) = values(day) + DayColumn(index + 1, dayOfMonth(day.day), above, below, isToday = day.day == today, empty = day.sessions == 0) + }.toImmutableList() +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/data/ProgressRepository.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/data/ProgressRepository.kt new file mode 100644 index 0000000000..f52c8945ad --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/data/ProgressRepository.kt @@ -0,0 +1,105 @@ +package com.quran.mobile.feature.progress.data + +import com.quran.data.core.QuranInfo +import com.quran.data.dao.ReadingBookmarkSlotSettings +import com.quran.data.dao.ReadingBookmarksDao +import com.quran.data.dao.Settings +import com.quran.data.di.AppScope +import com.quran.data.model.bookmark.EmptyReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmarkSlotSetting +import com.quran.mobile.progress.ProgressPreferences +import com.quran.mobile.progress.history.DayMinutes +import com.quran.mobile.progress.history.LoggedSession +import com.quran.mobile.progress.history.ProgressHistory +import com.quran.mobile.progress.log.RecordedMove +import com.quran.mobile.progress.summary.BookmarkProgress +import com.quran.mobile.progress.summary.MemorizingProgress +import com.quran.mobile.progress.summary.ProgressCalculator +import com.quran.mobile.progress.summary.SalahProgress +import com.quran.mobile.progress.time.ProgressClock +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlin.time.Instant + +/** Everything Progress shows, at one moment. */ +data class ProgressSnapshot( + val today: Long, + val calculator: ProgressCalculator, + /** The bookmarks that are on, in slot order. */ + val bookmarks: List, + val memorizing: MemorizingProgress, + val salah: SalahProgress, + /** Every session, oldest first. */ + val sessions: List, + /** Reading today not credited to a bookmark yet. */ + val uncreditedTodayMs: Long, +) + +/** Puts together what Progress kept with the bookmarks and their settings, as they change. */ +@SingleIn(AppScope::class) +class ProgressRepository @Inject constructor( + private val readingBookmarksDao: ReadingBookmarksDao, + private val slotSettings: ReadingBookmarkSlotSettings, + private val history: ProgressHistory, + private val settings: Settings, + private val quranInfoProvider: () -> QuranInfo, + private val clock: ProgressClock, + private val preferences: ProgressPreferences, +) { + private data class Kept( + val bookmarks: List, + val settings: List, + val moves: Map>, + val minutes: List, + val sessions: List, + ) + + fun snapshots(): Flow { + val kept = combine( + readingBookmarksDao.readingBookmarksFlow(), + slotSettings.settingsFlow(), + history.moves(), + history.minutes(), + history.sessions(), + ) { bookmarks, settings, moves, minutes, sessions -> Kept(bookmarks, settings, moves, minutes, sessions) } + // the clock (a new day, or a debug build's moved clock) changes what's shown too + val today = combine(minutes(), preferences.changes) { _, _ -> clock.today() }.distinctUntilChanged() + return combine(kept, today) { it, day -> build(it, day) }.flowOn(Dispatchers.Default) + } + + suspend fun snapshot(): ProgressSnapshot = snapshots().first() + + private suspend fun build(kept: Kept, today: Long): ProgressSnapshot { + val calculator = ProgressCalculator(quranInfoProvider(), settings.pageType()) + val bySlot = kept.bookmarks.associateBy { it.slot } + val bookmarks = kept.settings.filter { it.enabled }.map { setting -> + val bookmark = bySlot[setting.slot] ?: EmptyReadingBookmark(setting.slot, Instant.DISTANT_PAST) + calculator.bookmark(bookmark, setting, kept.moves[setting.slot.name].orEmpty(), kept.minutes, today) + } + return ProgressSnapshot( + today = today, + calculator = calculator, + bookmarks = bookmarks, + memorizing = calculator.memorizing(kept.sessions, today), + salah = calculator.salah(kept.sessions, today), + sessions = kept.sessions, + uncreditedTodayMs = kept.minutes.filter { it.slot == null && it.day == today }.sumOf { it.ms }, + ) + } + + private fun minutes(): Flow = flow { + while (true) { + emit(System.currentTimeMillis() / 60_000L) + delay(60_000L) + } + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/di/ProgressComponentInterface.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/di/ProgressComponentInterface.kt new file mode 100644 index 0000000000..a9a0f59252 --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/di/ProgressComponentInterface.kt @@ -0,0 +1,45 @@ +package com.quran.mobile.feature.progress.di + +import com.quran.data.dao.ReadingBookmarkSlotSettings +import com.quran.data.dao.ReadingBookmarksDao +import com.quran.data.di.AppScope +import com.quran.mobile.di.RecordedSessionLauncher +import com.quran.mobile.feature.progress.data.ProgressRepository +import com.quran.mobile.feature.progress.reminder.ReminderNotifier +import com.quran.mobile.feature.progress.reminder.ReminderScheduler +import com.quran.mobile.progress.ProgressPreferences +import com.quran.mobile.progress.history.ProgressHistory +import com.quran.mobile.progress.log.BookmarkMoveRecorder +import com.quran.mobile.progress.reading.ReaderPresence +import com.quran.mobile.progress.time.ProgressClock +import com.quran.page.common.data.QuranNaming +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.ElementsIntoSet +import dev.zacsweers.metro.Provides + +/** Lets Android components that aren't injected (the screen, the reminder's worker) reach the feature. */ +@ContributesTo(AppScope::class) +interface ProgressComponentInterface { + fun progressRepository(): ProgressRepository + fun progressPreferences(): ProgressPreferences + fun progressHistory(): ProgressHistory + fun progressClock(): ProgressClock + fun readingBookmarkSlotSettings(): ReadingBookmarkSlotSettings + fun readingBookmarksDao(): ReadingBookmarksDao + fun bookmarkMoveRecorder(): BookmarkMoveRecorder + fun readerPresence(): ReaderPresence + fun reminderScheduler(): ReminderScheduler + fun reminderNotifier(): ReminderNotifier + fun quranNaming(): QuranNaming + fun recordedSessionLaunchers(): Set +} + +@BindingContainer +@ContributesTo(AppScope::class) +object ProgressBindings { + /** Memorize adds one when it's in the build. */ + @Provides + @ElementsIntoSet + fun provideRecordedSessionLaunchers(): Set = emptySet() +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/reminder/ReminderNotifier.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/reminder/ReminderNotifier.kt new file mode 100644 index 0000000000..d1decea7fb --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/reminder/ReminderNotifier.kt @@ -0,0 +1,94 @@ +package com.quran.mobile.feature.progress.reminder + +import android.Manifest +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import com.quran.data.di.AppScope +import com.quran.labs.androidquran.common.ui.core.ReadingBookmarkSlots +import com.quran.mobile.di.qualifier.ApplicationContext +import com.quran.mobile.feature.progress.ProgressActivity +import com.quran.mobile.feature.progress.R +import com.quran.mobile.feature.progress.ui.dayOnly +import com.quran.mobile.progress.reminder.Reminder +import com.quran.mobile.progress.summary.BookmarkProgress +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn + +/** Shows the daily reading reminder; a tap opens the bookmark in Progress. */ +@SingleIn(AppScope::class) +class ReminderNotifier @Inject constructor(@param:ApplicationContext private val context: Context) { + + /** Whether notifications may be shown (on Android 13 and later the user has to allow them). */ + fun allowed(): Boolean { + val permitted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || + ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED + return permitted && NotificationManagerCompat.from(context).areNotificationsEnabled() + } + + /** Shows [reminder]; false if notifications aren't allowed. */ + fun show(reminder: Reminder): Boolean { + if (!allowed()) return false + val bookmark: BookmarkProgress + val text = when (reminder) { + is Reminder.NotReadToday -> { + bookmark = reminder.bookmark + context.getString(R.string.progress_reminder_not_read, reminder.perDay, context.dayOnly(reminder.finishByDay)) + } + is Reminder.Behind -> { + bookmark = reminder.bookmark + context.getString(R.string.progress_reminder_behind, reminder.pages, reminder.perDay, context.dayOnly(reminder.finishByDay)) + } + is Reminder.Overdue -> { + bookmark = reminder.bookmark + context.getString(R.string.progress_reminder_overdue, reminder.remaining) + } + Reminder.None -> return false + } + createChannel() + val open = PendingIntent.getActivity( + context, + bookmark.slot.ordinal, + ProgressActivity.intent(context, bookmark.slot), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + val title = ReadingBookmarkSlots.displayName(context, bookmark.slot, bookmark.name) + val notification = NotificationCompat.Builder(context, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_progress_notification) + .setContentTitle(context.getString(R.string.progress_reminder_title, title)) + .setContentText(text) + .setStyle(NotificationCompat.BigTextStyle().bigText(text)) + .setContentIntent(open) + .setAutoCancel(true) + .setCategory(NotificationCompat.CATEGORY_REMINDER) + .setPriority(NotificationCompat.PRIORITY_DEFAULT) + .build() + return try { + NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notification) + true + } catch (_: SecurityException) { + false + } + } + + private fun createChannel() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + val manager = context.getSystemService(NotificationManager::class.java) ?: return + if (manager.getNotificationChannel(CHANNEL_ID) != null) return + val channel = NotificationChannel(CHANNEL_ID, context.getString(R.string.progress_reminder_channel), NotificationManager.IMPORTANCE_DEFAULT) + .apply { description = context.getString(R.string.progress_reminder_channel_description) } + manager.createNotificationChannel(channel) + } + + private companion object { + const val CHANNEL_ID = "progress_reminder" + // the app's own notifications use 1 to 5, Memorize's its own range + const val NOTIFICATION_ID = 4_210 + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/reminder/ReminderScheduler.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/reminder/ReminderScheduler.kt new file mode 100644 index 0000000000..780b6bc782 --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/reminder/ReminderScheduler.kt @@ -0,0 +1,52 @@ +package com.quran.mobile.feature.progress.reminder + +import android.content.Context +import androidx.work.ExistingWorkPolicy +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkManager +import com.quran.data.di.AppScope +import com.quran.mobile.di.qualifier.ApplicationContext +import com.quran.mobile.progress.ProgressPreferences +import com.quran.mobile.progress.reminder.ReminderDecision +import com.quran.mobile.progress.time.ProgressClock +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import java.util.concurrent.TimeUnit + +/** + * Keeps one check of the daily reminder waiting, at the time the user chose (WorkManager, so it + * survives restarts). Each check schedules the next. + */ +@SingleIn(AppScope::class) +class ReminderScheduler @Inject constructor( + @param:ApplicationContext private val context: Context, + private val preferences: ProgressPreferences, + private val clock: ProgressClock, +) { + /** At app start: leaves a waiting check as it is. */ + fun ensure() = schedule(ExistingWorkPolicy.KEEP) + + /** After the user changed the reminder: the waiting check moves to the new time. */ + fun reschedule() = schedule(ExistingWorkPolicy.REPLACE) + + /** From the check itself, for the next day's (replacing it would cancel the check that's running). */ + fun scheduleNext() = schedule(ExistingWorkPolicy.APPEND_OR_REPLACE) + + private fun schedule(policy: ExistingWorkPolicy) { + val workManager = WorkManager.getInstance(context) + if (!preferences.reminder) { + workManager.cancelUniqueWork(WORK_NAME) + return + } + val now = clock.nowMs() + val at = ReminderDecision.nextReminderAt(now, clock.zone(), preferences.reminderMinute) + val request = OneTimeWorkRequestBuilder() + .setInitialDelay((at - now).coerceAtLeast(0L), TimeUnit.MILLISECONDS) + .build() + workManager.enqueueUniqueWork(WORK_NAME, policy, request) + } + + private companion object { + const val WORK_NAME = "progress_reminder" + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/reminder/ReminderWorker.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/reminder/ReminderWorker.kt new file mode 100644 index 0000000000..0d2ad36e96 --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/reminder/ReminderWorker.kt @@ -0,0 +1,38 @@ +package com.quran.mobile.feature.progress.reminder + +import android.content.Context +import androidx.work.CoroutineWorker +import androidx.work.WorkerParameters +import com.quran.mobile.di.QuranApplicationComponentProvider +import com.quran.mobile.feature.progress.di.ProgressComponentInterface +import com.quran.mobile.progress.reminder.Reminder +import com.quran.mobile.progress.reminder.ReminderDecision + +/** The daily reminder's check: says what's due, if anything, then waits for the next day's. */ +class ReminderWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { + + override suspend fun doWork(): Result { + val component = (applicationContext as QuranApplicationComponentProvider) + .provideQuranApplicationComponent() as ProgressComponentInterface + val preferences = component.progressPreferences() + val clock = component.progressClock() + try { + val snapshot = component.progressRepository().snapshot() + val reminder = ReminderDecision.decide( + enabled = preferences.reminder, + nowMs = clock.nowMs(), + zone = clock.zone(), + reminderMinute = preferences.reminderMinute, + lastReminderDay = preferences.lastReminderDay, + readerOpen = component.readerPresence().open, + bookmarks = snapshot.bookmarks, + ) + if (reminder != Reminder.None && component.reminderNotifier().show(reminder)) { + preferences.lastReminderDay = clock.today() + } + } finally { + component.reminderScheduler().scheduleNext() + } + return Result.success() + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/settings/DebugSeed.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/settings/DebugSeed.kt new file mode 100644 index 0000000000..43ac015157 --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/settings/DebugSeed.kt @@ -0,0 +1,35 @@ +package com.quran.mobile.feature.progress.settings + +import com.quran.data.core.QuranInfo +import com.quran.data.dao.ReadingBookmarksDao +import com.quran.data.dao.Settings +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.mobile.progress.history.DebugHistory +import com.quran.mobile.progress.history.ProgressHistory +import com.quran.mobile.progress.time.ProgressClock +import dev.zacsweers.metro.Inject + +/** Debuggable builds only: replaces Progress's history with 12 days of teal's reading. */ +class DebugSeed @Inject constructor( + private val history: ProgressHistory, + private val debugHistory: DebugHistory, + private val readingBookmarksDao: ReadingBookmarksDao, + private val settings: Settings, + private val quranInfoProvider: () -> QuranInfo, + private val clock: ProgressClock, +) { + suspend fun seed() { + history.clear() + val page = debugHistory.seed( + slot = ReadingBookmarkType.TEAL.name, + today = clock.today(), + zone = clock.zone(), + quranInfo = quranInfoProvider(), + pageType = settings.pageType(), + pages = listOf(16, 22, 19, 26, 10, 0, 24, 21, 27, 15, 25, 24), + minutes = listOf(34, 49, 38, 55, 22, 3, 52, 42, 59, 31, 54, 58), + ) + // the bookmark itself where its history ends, so the next move is measured from there + readingBookmarksDao.setPageReadingBookmark(ReadingBookmarkType.TEAL, page) + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/settings/ProgressPreferencesProvider.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/settings/ProgressPreferencesProvider.kt new file mode 100644 index 0000000000..ad75178783 --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/settings/ProgressPreferencesProvider.kt @@ -0,0 +1,201 @@ +package com.quran.mobile.feature.progress.settings + +import android.app.AlertDialog +import android.app.TimePickerDialog +import android.text.format.DateFormat +import android.widget.Toast +import androidx.preference.Preference +import androidx.preference.PreferenceCategory +import androidx.preference.PreferenceDataStore +import androidx.preference.PreferenceGroup +import androidx.preference.SwitchPreferenceCompat +import com.quran.data.di.AppScope +import com.quran.mobile.di.ExtraPreferencesProvider +import com.quran.mobile.feature.progress.ProgressActivity +import com.quran.mobile.feature.progress.R +import com.quran.mobile.feature.progress.data.ProgressRepository +import com.quran.mobile.feature.progress.reminder.ReminderNotifier +import com.quran.mobile.feature.progress.reminder.ReminderScheduler +import com.quran.mobile.feature.progress.ui.timeOfDay +import com.quran.mobile.progress.ProgressPreferences +import com.quran.mobile.progress.history.ProgressHistory +import com.quran.mobile.progress.reminder.Reminder +import com.quran.mobile.progress.reminder.ReminderDecision +import com.quran.mobile.progress.time.ProgressClock +import dev.zacsweers.metro.ContributesIntoSet +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + +/** The "Progress" section of the app's settings: the reading bookmarks, the daily reminder, the session log. */ +@SingleIn(AppScope::class) +@ContributesIntoSet(AppScope::class) +@Inject +class ProgressPreferencesProvider( + private val preferences: ProgressPreferences, + private val reminderScheduler: ReminderScheduler, + private val history: ProgressHistory, + private val debugSeed: DebugSeed, + private val repository: ProgressRepository, + private val notifier: ReminderNotifier, + private val clock: ProgressClock, +) : ExtraPreferencesProvider { + + override val order: Int = 20 + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + + private val store = object : PreferenceDataStore() { + override fun getBoolean(key: String, defValue: Boolean): Boolean = when (key) { + KEY_REMINDER -> preferences.reminder + KEY_SESSION_LOG -> preferences.sessionLog + else -> defValue + } + + override fun putBoolean(key: String, value: Boolean) { + when (key) { + KEY_REMINDER -> { + preferences.reminder = value + reminderScheduler.reschedule() + } + KEY_SESSION_LOG -> preferences.sessionLog = value + } + } + } + + override fun addPreferences(root: PreferenceGroup) { + val context = root.context + val category = PreferenceCategory(context).apply { + key = KEY_CATEGORY + title = context.getString(R.string.progress_settings_category) + isIconSpaceReserved = false + } + root.addPreference(category) + category.addPreference(Preference(context).apply { + setup(KEY_BOOKMARKS, R.string.progress_settings_bookmarks, R.string.progress_settings_bookmarks_summary) + }) + category.addPreference(SwitchPreferenceCompat(context).apply { + setup(KEY_REMINDER, R.string.progress_settings_reminder, R.string.progress_settings_reminder_summary) + }) + category.addPreference(Preference(context).apply { + setup(KEY_REMINDER_TIME, R.string.progress_settings_reminder_time, null) + summary = context.timeOfDay(preferences.reminderMinute) + }) + category.addPreference(SwitchPreferenceCompat(context).apply { + setup(KEY_SESSION_LOG, R.string.progress_settings_session_log, R.string.progress_settings_session_log_summary) + }) + category.addPreference(Preference(context).apply { + setup(KEY_CLEAR, R.string.progress_settings_clear, R.string.progress_settings_clear_summary) + }) + if (preferences.debuggable) { + category.addPreference(Preference(context).apply { + setup(KEY_DEBUG_CLOCK, R.string.progress_settings_debug_clock, null) + summary = context.getString(R.string.progress_settings_debug_clock_summary, preferences.debugDayOffset) + }) + category.addPreference(Preference(context).apply { + setup(KEY_DEBUG_CLOCK_RESET, R.string.progress_settings_debug_clock_reset, null) + }) + category.addPreference(Preference(context).apply { + setup(KEY_DEBUG_SEED, R.string.progress_settings_debug_seed, null) + }) + category.addPreference(Preference(context).apply { + setup(KEY_DEBUG_REMINDER, R.string.progress_settings_debug_reminder, null) + }) + } + } + + override fun onPreferenceClick(preference: Preference): Boolean { + val context = preference.context + return when (preference.key) { + KEY_BOOKMARKS -> { + context.startActivity(ProgressActivity.editBookmarksIntent(context)) + true + } + KEY_REMINDER_TIME -> { + val minute = preferences.reminderMinute + TimePickerDialog( + context, + { _, hour, minuteOfHour -> + preferences.reminderMinute = hour * 60 + minuteOfHour + preference.summary = context.timeOfDay(preferences.reminderMinute) + reminderScheduler.reschedule() + }, + minute / 60, + minute % 60, + DateFormat.is24HourFormat(context), + ).show() + true + } + KEY_CLEAR -> { + AlertDialog.Builder(context) + .setTitle(R.string.progress_settings_clear) + .setMessage(R.string.progress_settings_clear_message) + .setPositiveButton(R.string.progress_settings_clear_confirm) { _, _ -> scope.launch { history.clear() } } + .setNegativeButton(android.R.string.cancel, null) + .show() + true + } + KEY_DEBUG_CLOCK -> { + preferences.debugDayOffset += 1 + preference.summary = context.getString(R.string.progress_settings_debug_clock_summary, preferences.debugDayOffset) + reminderScheduler.reschedule() + true + } + KEY_DEBUG_CLOCK_RESET -> { + preferences.debugDayOffset = 0 + preference.parent?.findPreference(KEY_DEBUG_CLOCK)?.summary = + context.getString(R.string.progress_settings_debug_clock_summary, 0) + reminderScheduler.reschedule() + true + } + KEY_DEBUG_SEED -> { + scope.launch { debugSeed.seed() } + true + } + KEY_DEBUG_REMINDER -> { + // today's reminder as it would come at its time (whatever the time now, and even if it came) + scope.launch { + val reminder = ReminderDecision.decide( + enabled = true, + nowMs = clock.nowMs(), + zone = clock.zone(), + reminderMinute = 0, + lastReminderDay = -1, + readerOpen = false, + bookmarks = repository.snapshot().bookmarks, + ) + if (reminder == Reminder.None || !notifier.show(reminder)) { + Toast.makeText(context, R.string.progress_settings_debug_reminder_none, Toast.LENGTH_SHORT).show() + } + } + true + } + else -> false + } + } + + private fun Preference.setup(key: String, title: Int, summary: Int?) { + this.key = key + this.preferenceDataStore = store + this.isIconSpaceReserved = false + this.isPersistent = true + setTitle(title) + if (summary != null) setSummary(summary) + } + + private companion object { + const val KEY_CATEGORY = "progress_category" + const val KEY_BOOKMARKS = "progress_bookmarks" + const val KEY_REMINDER = "progress_reminder" + const val KEY_REMINDER_TIME = "progress_reminder_time" + const val KEY_SESSION_LOG = "progress_session_log" + const val KEY_CLEAR = "progress_clear" + const val KEY_DEBUG_CLOCK = "progress_debug_clock" + const val KEY_DEBUG_CLOCK_RESET = "progress_debug_clock_reset" + const val KEY_DEBUG_SEED = "progress_debug_seed" + const val KEY_DEBUG_REMINDER = "progress_debug_reminder" + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/BookmarksPane.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/BookmarksPane.kt new file mode 100644 index 0000000000..845167c70e --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/BookmarksPane.kt @@ -0,0 +1,491 @@ +package com.quran.mobile.feature.progress.ui + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.VerticalDivider +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.colorResource +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import com.quran.data.model.bookmark.ReadingBookmarkPurpose +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.labs.androidquran.common.ui.core.QuranIcons +import com.quran.labs.androidquran.common.ui.core.ReadingBookmarkSlots +import com.quran.mobile.feature.progress.R +import kotlinx.collections.immutable.ImmutableList + +@Composable +internal fun bookmarkColor(slot: ReadingBookmarkType): Color = colorResource(ReadingBookmarkSlots[slot].colorResourceId) + +/** The bookmarks that are on, with where each is; the chosen one is highlighted. */ +@Composable +internal fun BookmarkList( + bookmarks: ImmutableList, + selected: ReadingBookmarkType?, + canAdd: Boolean, + onSelect: (ReadingBookmarkType) -> Unit, + onAdd: () -> Unit, + modifier: Modifier = Modifier, + showTitle: Boolean = true, +) { + Column(modifier.verticalScroll(rememberScrollState()).padding(vertical = 20.dp)) { + if (showTitle) { + Text( + stringResource(R.string.progress_section_bookmarks), + style = MaterialTheme.typography.headlineSmall, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(start = 20.dp, end = 20.dp, bottom = 14.dp), + ) + } + bookmarks.forEach { bookmark -> + val isSelected = bookmark.slot == selected + Row( + Modifier + .padding(horizontal = 8.dp, vertical = 2.dp) + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .background(if (isSelected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent) + .selectable(selected = isSelected, role = Role.Tab) { onSelect(bookmark.slot) } + .padding(horizontal = 12.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + if (bookmark.placed) ProgressIcons.Bookmark else QuranIcons.BookmarkBorder, + contentDescription = null, + tint = bookmarkColor(bookmark.slot), + modifier = Modifier.size(24.dp), + ) + Column(Modifier.padding(start = 14.dp)) { + Text(bookmark.name, style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurface) + Text( + listSummary(bookmark), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 2.dp), + ) + } + } + } + if (canAdd) { + Row( + Modifier + .padding(horizontal = 8.dp, vertical = 4.dp) + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .selectable(selected = false, role = Role.Button, onClick = onAdd) + .padding(horizontal = 12.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon(ProgressIcons.Add, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(24.dp)) + Text( + stringResource(R.string.progress_add_bookmark), + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(start = 14.dp), + ) + } + } + } +} + +/** E.g. "Reading · juz 14 · day 12 of 30". */ +@Composable +private fun listSummary(bookmark: BookmarkView): String { + val separator = stringResource(R.string.progress_separator) + val parts = buildList { + add(purposeName(bookmark.purpose)) + val juz = bookmark.juz + if (juz == null) { + add(stringResource(R.string.progress_not_placed)) + } else { + add(stringResource(R.string.progress_juz, juz)) + if (bookmark.purpose == ReadingBookmarkPurpose.READING) { + val dayN = bookmark.dayN + when { + dayN != null -> add(stringResource(R.string.progress_day_of, dayN, bookmark.targetDays)) + bookmark.targetDays == 0 -> add(stringResource(R.string.progress_no_deadline)) + } + } + } + } + return parts.joinToString(separator) +} + +/** + * One bookmark: its name and purpose, a sentence on its cycle, the juz line, the days (pages above, + * minutes below) and the cycle's facts. + */ +@Composable +internal fun BookmarkDetail( + bookmark: BookmarkView, + reminder: ReminderView, + uncreditedTodayMinutes: Int, + onAllowNotifications: () -> Unit, + onReminderTime: () -> Unit, + onStartCycle: () -> Unit, + modifier: Modifier = Modifier, + dark: Boolean = false, + /** False where the app bar already says it (a phone). */ + showName: Boolean = true, +) { + val color = bookmarkColor(bookmark.slot) + val panel = panelColor() + val context = context() + var selectedJuz by rememberSaveable(bookmark.slot) { mutableStateOf(null) } + Column( + modifier + .verticalScroll(rememberScrollState()) + .padding(horizontal = 28.dp, vertical = 22.dp) + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + if (showName) { + Text(bookmark.name, style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.onSurface) + } + Label(purposeName(bookmark.purpose)) + Spacer(Modifier.weight(1f)) + if (!bookmark.hasHistory) Label(stringResource(R.string.progress_sample), quiet = true) + } + val sentence = sentence(bookmark) + if (sentence.isNotEmpty()) { + Text( + sentence, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 6.dp, bottom = 18.dp), + ) + } + if (!bookmark.placed) { + Text( + stringResource(R.string.progress_not_placed_detail), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(top = 12.dp, bottom = 18.dp), + ) + // what its days will look like, until it is placed + DaysPanel(bookmark, color, panel, uncreditedTodayMinutes, dark) + return@Column + } + + Panel(panel) { + Caption(stringResource(R.string.progress_juz_title), paceText(bookmark)) + JuzLine( + line = bookmark.line, + color = color, + selectedJuz = selectedJuz, + onSelect = { selectedJuz = it }, + describe = { juz -> juzDetail(context, bookmark.line, juz) }, + modifier = Modifier.padding(top = 4.dp), + ) + JuzLegend( + color = color, + showPace = bookmark.line.pace != null, + now = stringResource(R.string.progress_legend_now), + pace = stringResource(R.string.progress_legend_pace), + read = stringResource(R.string.progress_legend_read), + modifier = Modifier.padding(top = 6.dp), + ) + selectedJuz?.let { juz -> + Text( + juzDetail(context, bookmark.line, juz), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(top = 8.dp), + ) + } + } + + DaysPanel(bookmark, color, panel, uncreditedTodayMinutes, dark) + + Facts(bookmark, reminder, panel, onAllowNotifications, onReminderTime) + + if (bookmark.purpose == ReadingBookmarkPurpose.READING) { + TextButton(onClick = onStartCycle, modifier = Modifier.padding(top = 4.dp)) { + Text(stringResource(R.string.progress_start_cycle)) + } + } + } +} + +/** Pages (above) and minutes (below) per day; sample days, faded, until the bookmark has moved. */ +@Composable +private fun DaysPanel(bookmark: BookmarkView, color: Color, panel: Color, uncreditedTodayMinutes: Int, dark: Boolean) { + val context = context() + Panel(panel) { + val goal = bookmark.goal + Caption( + stringResource(R.string.progress_days_title), + listOfNotNull( + stringResource(R.string.progress_pages_per_day), + goal?.let { stringResource(R.string.progress_goal, it) }, + ).joinToString(stringResource(R.string.progress_separator)), + ) + val columns = if (bookmark.hasHistory) bookmark.days else SampleProgress.reading(bookmark.days) + DayBars( + columns = columns, + aboveColor = color, + belowColor = MaterialTheme.colorScheme.primary, + aboveLine = goal, + belowLine = if (bookmark.hasHistory) bookmark.averageMinutes else null, + describe = { column -> dayDescription(context, column) }, + panel = panel, + faded = !bookmark.hasHistory, + dark = dark, + ) + Row(Modifier.fillMaxWidth().padding(top = 8.dp)) { + Text( + listOfNotNull( + stringResource(R.string.progress_minutes_per_day), + bookmark.averageMinutes?.takeIf { bookmark.hasHistory }?.let { stringResource(R.string.progress_average, it) }, + ).joinToString(stringResource(R.string.progress_separator)), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f), + ) + bookmark.todayMinutes?.takeIf { bookmark.hasHistory }?.let { + Text( + stringResource(R.string.progress_today_value, it), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + if (!bookmark.hasHistory) Note(stringResource(R.string.progress_no_history)) + if (uncreditedTodayMinutes > 0) { + Note(pluralStringResource(R.plurals.progress_uncredited, uncreditedTodayMinutes, uncreditedTodayMinutes)) + } + } +} + +/** E.g. "Started Sunday 3 November · finishes by 2 December · page 262, Al-Hijr 15:1". */ +@Composable +private fun sentence(bookmark: BookmarkView): String { + val context = context() + val separator = stringResource(R.string.progress_separator) + val parts = buildList { + bookmark.cycleStartDay?.let { add(stringResource(R.string.progress_started, context.dayWithWeekday(it))) } + bookmark.followedSinceDay?.let { add(stringResource(R.string.progress_kept_since, context.dayWithWeekday(it))) } + bookmark.finishByDay?.let { day -> + add( + if (bookmark.overdue) { + stringResource(R.string.progress_overdue_since, context.dayOnly(day)) + } else { + stringResource(R.string.progress_finishes_by, context.dayOnly(day)) + } + ) + } + bookmark.place?.let { add(stringResource(R.string.progress_at, it.page, it.suraName, it.sura, it.ayah)) } + } + return parts.joinToString(separator) +} + +@Composable +private fun paceText(bookmark: BookmarkView): String? { + val ahead = bookmark.ahead ?: return null + return when { + ahead > 0 -> pluralStringResource(R.plurals.progress_ahead, ahead, ahead, bookmark.targetDays) + ahead < 0 -> pluralStringResource(R.plurals.progress_behind, -ahead, -ahead, bookmark.targetDays) + else -> stringResource(R.string.progress_on_pace, bookmark.targetDays) + } +} + +private fun juzDetail(context: android.content.Context, line: JuzLineState, juz: Int): String { + val pages = line.juz.first { it.juz == juz } + return context.getString(R.string.progress_juz_detail, juz, pages.firstPage, pages.lastPage, pages.read, pages.pages) +} + +private fun dayDescription(context: android.content.Context, column: DayColumn): String { + val above = column.above ?: return context.getString(R.string.progress_day_to_come, column.label) + val res = context.resources + return context.getString( + R.string.progress_day_semantics, + column.label, + res.getQuantityString(R.plurals.progress_pages, above, above), + res.getQuantityString(R.plurals.progress_minutes, column.below ?: 0, column.below ?: 0), + ) +} + +/** The cycle's facts in one row: time read and pages, the last cycle, the reminder. */ +@Composable +private fun Facts( + bookmark: BookmarkView, + reminder: ReminderView, + panel: Color, + onAllowNotifications: () -> Unit, + onReminderTime: () -> Unit, +) { + val context = context() + val reading = bookmark.purpose == ReadingBookmarkPurpose.READING + Surface(color = panel, shape = RoundedCornerShape(16.dp), modifier = Modifier.fillMaxWidth()) { + // side by side where there's room, else one under the other + BoxWithConstraints { + val stacked = maxWidth < 560.dp + val facts: @Composable (Modifier) -> Unit = { fact -> + FactsContent(bookmark, reminder, reading, stacked, fact, onAllowNotifications, onReminderTime) + } + if (stacked) { + Column(Modifier.padding(vertical = 6.dp)) { facts(Modifier.fillMaxWidth().padding(vertical = 6.dp)) } + } else { + Row(Modifier.height(IntrinsicSize.Min).padding(vertical = 12.dp)) { facts(Modifier.weight(1f)) } + } + } + } +} + +@Composable +private fun FactsContent( + bookmark: BookmarkView, + reminder: ReminderView, + reading: Boolean, + stacked: Boolean, + fact: Modifier, + onAllowNotifications: () -> Unit, + onReminderTime: () -> Unit, +) { + val context = context() + val divider: @Composable () -> Unit = { + if (stacked) { + HorizontalDivider(Modifier.padding(horizontal = 16.dp), color = MaterialTheme.colorScheme.surfaceVariant) + } else { + Divider() + } + } + Fact(fact, duration(bookmark.cycleReadingMs), stringResource(R.string.progress_fact_reading, pages(bookmark.cyclePages))) + if (reading) { + divider() + val lastDays = bookmark.lastCycleDays + val lastStart = bookmark.lastCycleStartDay + val lastEnd = bookmark.lastCycleEndDay + if (lastDays != null && lastStart != null && lastEnd != null) { + Fact(fact, days(lastDays), stringResource(R.string.progress_fact_last, context.dayRange(lastStart, lastEnd))) + } else { + Fact(fact, stringResource(R.string.progress_fact_none), stringResource(R.string.progress_fact_last_label)) + } + // the reminder is about an open khatma with a deadline + if (bookmark.dayN == null) return + divider() + when { + !reminder.on -> Fact(fact, null, stringResource(R.string.progress_fact_reminder_off), onClick = onReminderTime) + !reminder.allowed -> Fact( + fact, + null, + stringResource(R.string.progress_reminder_needs_permission), + action = stringResource(R.string.progress_allow), + onClick = onAllowNotifications, + ) + else -> Fact( + fact, context.timeOfDay(reminder.minuteOfDay), stringResource(R.string.progress_fact_reminder), onClick = onReminderTime + ) + } + } +} + +@Composable +private fun Fact( + modifier: Modifier, + value: String?, + label: String, + action: String? = null, + onClick: (() -> Unit)? = null, +) { + val clickable = if (onClick != null) Modifier.selectable(selected = false, role = Role.Button, onClick = onClick) else Modifier + Column(modifier.then(clickable).padding(horizontal = 16.dp, vertical = 2.dp)) { + value?.let { + Text(it, style = MaterialTheme.typography.titleMedium.tabular(), color = MaterialTheme.colorScheme.onSurface) + } + Text(label, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + action?.let { + Text(it, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary, modifier = Modifier.padding(top = 4.dp)) + } + } +} + +@Composable +private fun Divider() { + VerticalDivider(Modifier.fillMaxHeight(), color = MaterialTheme.colorScheme.surfaceVariant) +} + +@Composable +internal fun Panel(color: Color, content: @Composable () -> Unit) { + Surface( + color = color, + shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp), + ) { + Column(Modifier.padding(start = 18.dp, end = 18.dp, top = 16.dp, bottom = 14.dp)) { content() } + } +} + +@Composable +internal fun Caption(title: String, detail: String?) { + Row(Modifier.fillMaxWidth().padding(bottom = 10.dp), verticalAlignment = Alignment.Bottom) { + Text(title, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.weight(1f)) + detail?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } + } +} + +@Composable +internal fun Note(text: String) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 8.dp), + ) +} + +/** A small outlined label, e.g. the purpose; [quiet] for "Sample data". */ +@Composable +internal fun Label(text: String, quiet: Boolean = false) { + Surface( + shape = RoundedCornerShape(8.dp), + border = BorderStroke(1.dp, if (quiet) MaterialTheme.colorScheme.surfaceVariant else MaterialTheme.colorScheme.outline), + color = Color.Transparent, + ) { + Text( + text, + style = if (quiet) MaterialTheme.typography.labelSmall else MaterialTheme.typography.labelMedium, + color = if (quiet) MaterialTheme.colorScheme.outline else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = if (quiet) 8.dp else 10.dp, vertical = 3.dp), + ) + } +} + +/** Shown in a pane with nothing chosen yet. */ +@Composable +internal fun Choose(text: String, modifier: Modifier = Modifier) { + Column(modifier.fillMaxSize().padding(28.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { + Text(text, style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/DayBars.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/DayBars.kt new file mode 100644 index 0000000000..0acdb8d15e --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/DayBars.kt @@ -0,0 +1,232 @@ +package com.quran.mobile.feature.progress.ui + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.lerp +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import kotlinx.collections.immutable.ImmutableList + +private val LabelHeight = 16.dp +private val AxisHeight = 22.dp +private val MinColumn = 14.dp +// the width a day gets when the chart scrolls (a phone) +private val ScrollColumn = 22.dp + +/** + * A bar's color: by day today's is a shade darker; by night (where a lighter shade reads as faded) + * the other days are a little dimmer instead. + */ +internal fun Color.forDay(today: Boolean, dark: Boolean): Color = when { + dark && !today -> copy(alpha = alpha * 0.72f) + !dark && today -> lerp(this, Color.Black, 0.35f) + else -> this +} + +/** + * Days side by side on one numbered axis: a value above it ([DayColumn.above], e.g. pages) and one + * hanging below it ([DayColumn.below], e.g. minutes), each bar with its value written on it. Today is + * a shade darker with its number in bold; days still to come are dashed outlines. Lines across the + * chart mark a goal above and an average below. The days run from the start side, so right to left in + * Arabic; when they don't fit, the chart scrolls, opening at today. + * + * @param describe what TalkBack says for a day. + * @param panel the color behind the chart, which the values are written on. + * @param faded draws the bars faded, for sample days. + */ +@Composable +internal fun DayBars( + columns: ImmutableList, + aboveColor: Color, + belowColor: Color?, + aboveLine: Int?, + belowLine: Int?, + describe: (DayColumn) -> String, + panel: Color, + modifier: Modifier = Modifier, + faded: Boolean = false, + dark: Boolean = false, + aboveHeight: Dp = 170.dp, + belowHeight: Dp = 130.dp, +) { + if (columns.isEmpty()) return + val numbers = rememberNumbers() + val aboveScale = maxOf(columns.maxOf { it.above ?: 0 }, aboveLine ?: 0, 1) * 1.1f + val belowScale = maxOf(columns.maxOf { it.below ?: 0 }, belowLine ?: 0, 1) * 1.1f + val lineColor = MaterialTheme.colorScheme.outline + val stub = MaterialTheme.colorScheme.outline.copy(alpha = 0.45f) + val showBelow = belowColor != null + val totalHeight = aboveHeight + AxisHeight + if (showBelow) belowHeight else 0.dp + + BoxWithConstraints(modifier.fillMaxWidth()) { + val fits = maxWidth / columns.size >= MinColumn + val density = LocalDensity.current + val today = columns.indexOfFirst { it.isToday } + // it opens with today in the middle (or as far as it goes: the scroll stops at the end) + val scroll = remember(today, maxWidth) { + val column = with(density) { ScrollColumn.toPx() } + val viewport = with(density) { maxWidth.toPx() } + // whole days: the first one shown starts at the edge + val first = if (today < 0) 0 else ((today + 1) - (viewport / column / 2).toInt()).coerceAtLeast(0) + ScrollState((first * column).toInt()) + } + val chart = if (fits) Modifier.fillMaxWidth() else Modifier.horizontalScroll(scroll).width(ScrollColumn * columns.size) + Box(chart.height(totalHeight)) { + // the goal and average lines, under the bars and their values + Canvas(Modifier.fillMaxSize()) { + val dash = PathEffect.dashPathEffect(floatArrayOf(6.dp.toPx(), 4.dp.toPx())) + val stroke = 1.5.dp.toPx() + val aboveBars = (aboveHeight - LabelHeight).toPx() + aboveLine?.let { goal -> + val y = aboveHeight.toPx() - goal / aboveScale * aboveBars + drawLine(lineColor, Offset(0f, y), Offset(size.width, y), stroke, pathEffect = dash) + } + if (showBelow) { + belowLine?.let { average -> + val belowBars = (belowHeight - LabelHeight).toPx() + val y = (aboveHeight + AxisHeight).toPx() + average / belowScale * belowBars + drawLine(lineColor, Offset(0f, y), Offset(size.width, y), stroke, pathEffect = dash) + } + } + } + Row(Modifier.fillMaxSize()) { + columns.forEach { column -> + val cell = if (fits) Modifier.weight(1f) else Modifier.width(ScrollColumn) + val description = describe(column) + Column( + cell.clearAndSetSemantics { contentDescription = description }, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + val above = aboveColor.forDay(column.isToday, dark) + Box(Modifier.fillMaxWidth().height(aboveHeight).padding(horizontal = 2.dp), contentAlignment = Alignment.BottomCenter) { + val value = column.above + if (value == null) { + ToCome(Modifier.fillMaxSize().padding(top = LabelHeight)) + } else if (!column.empty) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + BarValue(numbers(value), panel, column.isToday) + Bar(value, aboveScale, aboveHeight - LabelHeight, if (value == 0) stub else above, faded, top = true) + } + } + } + Box(Modifier.height(AxisHeight), contentAlignment = Alignment.Center) { + Text( + numbers(column.label), + style = MaterialTheme.typography.labelSmall.tabular(), + fontWeight = if (column.isToday) FontWeight.Bold else FontWeight.Normal, + color = if (column.isToday) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + softWrap = false, + overflow = TextOverflow.Visible, + ) + } + if (belowColor != null) { + val below = belowColor.forDay(column.isToday, dark) + Box(Modifier.fillMaxWidth().height(belowHeight).padding(horizontal = 2.dp), contentAlignment = Alignment.TopCenter) { + val value = column.below + if (value == null) { + ToCome(Modifier.fillMaxSize().padding(bottom = LabelHeight)) + } else if (!column.empty) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Bar(value, belowScale, belowHeight - LabelHeight, if (value == 0) stub else below, faded, top = false) + BarValue(numbers(value), panel, column.isToday) + } + } + } + } + } + } + } + } + if (!fits) { + // more days that way: the edge fades + val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl + if (scroll.canScrollBackward) EdgeFade(panel, Modifier.align(Alignment.CenterStart).height(totalHeight), fromLeft = !rtl) + if (scroll.canScrollForward) EdgeFade(panel, Modifier.align(Alignment.CenterEnd).height(totalHeight), fromLeft = rtl) + } + } +} + +@Composable +private fun BarValue(text: String, panel: Color, today: Boolean) { + Text( + text, + style = MaterialTheme.typography.labelSmall.tabular(), + fontWeight = if (today) FontWeight.Bold else FontWeight.Normal, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + softWrap = false, + overflow = TextOverflow.Visible, + modifier = Modifier.height(LabelHeight).background(panel), + ) +} + +/** A bar [value] of [scale] tall in [room]; a sliver for 0. */ +@Composable +private fun Bar(value: Int, scale: Float, room: Dp, color: Color, faded: Boolean, top: Boolean) { + val height = if (value == 0) 2.dp else (room * (value / scale)).coerceAtLeast(3.dp) + val corner = 3.dp + val shape = if (top) RoundedCornerShape(topStart = corner, topEnd = corner) else RoundedCornerShape(bottomStart = corner, bottomEnd = corner) + Box( + Modifier + .fillMaxWidth() + .height(height) + .clip(shape) + .background(if (faded) color.copy(alpha = color.alpha * 0.45f) else color) + ) +} + +/** A fade from the panel's color at the edge of a scrolled chart, where more days lie. */ +@Composable +private fun EdgeFade(panel: Color, modifier: Modifier, fromLeft: Boolean) { + val colors = listOf(panel, panel.copy(alpha = 0f)) + Box(modifier.width(28.dp).background(Brush.horizontalGradient(if (fromLeft) colors else colors.reversed()))) +} + +/** A day still to come: a faint dashed outline where its bar will be. */ +@Composable +private fun ToCome(modifier: Modifier) { + val color = MaterialTheme.colorScheme.outline.copy(alpha = 0.35f) + Box( + modifier.drawBehind { + drawRoundRect( + color = color, + cornerRadius = CornerRadius(4.dp.toPx()), + style = Stroke(width = 1.dp.toPx(), pathEffect = PathEffect.dashPathEffect(floatArrayOf(4.dp.toPx(), 3.dp.toPx()))), + ) + } + ) +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/JuzLine.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/JuzLine.kt new file mode 100644 index 0000000000..c1079b64c5 --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/JuzLine.kt @@ -0,0 +1,240 @@ +package com.quran.mobile.feature.progress.ui + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectHorizontalDragGestures +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.semantics.ProgressBarRangeInfo +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.progressBarRangeInfo +import androidx.compose.ui.semantics.setProgress +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import com.quran.mobile.progress.summary.Held +import kotlinx.collections.immutable.ImmutableList +import kotlin.math.roundToInt + +/** + * The Quran as one line numbered by its 30 juz: the part read this cycle in the bookmark's color, a + * ring where it is, and a dashed ring where a steady pace is by the end of today. It runs from the + * start side (right to left in Arabic). Tapping or dragging along it shows a juz's pages. + */ +@Composable +internal fun JuzLine( + line: JuzLineState, + color: Color, + selectedJuz: Int?, + onSelect: (Int) -> Unit, + describe: (Int) -> String, + modifier: Modifier = Modifier, +) { + val numbers = rememberNumbers() + val track = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.22f) + val surface = MaterialTheme.colorScheme.surface + val pace = MaterialTheme.colorScheme.primary + val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl + BoxWithConstraints(modifier.fillMaxWidth()) { + // on a narrow screen every number doesn't fit: 1, every fifth, and the ones that matter + val sparse = maxWidth / 30 < 20.dp + Column { + Row(Modifier.fillMaxWidth()) { + for (juz in 1..30) { + val emphasized = juz == line.current || juz == selectedJuz + val shown = !sparse || emphasized || juz == 1 || juz % 5 == 0 + Text( + if (shown) numbers(juz) else "", + style = MaterialTheme.typography.labelSmall.tabular(), + fontWeight = if (emphasized) FontWeight.Medium else FontWeight.Normal, + color = if (emphasized) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + maxLines = 1, + softWrap = false, + overflow = TextOverflow.Visible, + modifier = Modifier.weight(1f), + ) + } + } + Canvas(Modifier.fillMaxWidth().height(32.dp).padding(vertical = 2.dp)) { + fun x(at: Float) = (at / 30f * size.width).let { if (rtl) size.width - it else it } + val y = size.height / 2 + drawLine(track, Offset(0f, y), Offset(size.width, y), 4.dp.toPx(), StrokeCap.Round) + val position = line.position + val start = line.runStart + if (position != null && start != null && position > start) { + drawLine(color, Offset(x(start), y), Offset(x(position), y), 10.dp.toPx(), StrokeCap.Round) + } + line.pace?.let { drawPaceRing(pace, Offset(x(it), y)) } + position?.let { drawNowMarker(color, surface, Offset(x(it), y)) } + } + } + // the numbers and the line are one control: a tap or a drag chooses the juz under it, and + // TalkBack moves through the juz as along a slider + Box(Modifier.matchParentSize().juzControl(selectedJuz ?: line.current ?: 1, rtl, onSelect, describe)) + } +} + +/** The juz at [x] of a row [width] wide (numbered from the start side). */ +internal fun juzAt(x: Float, width: Int, rtl: Boolean): Int { + val fraction = (x / width).coerceIn(0f, 0.9999f) + return 1 + ((if (rtl) 1f - fraction else fraction) * 30).toInt().coerceIn(0, 29) +} + +/** One control over the 30 juz: tap or drag to choose one; for TalkBack, adjustable like a slider. */ +private fun Modifier.juzControl(current: Int, rtl: Boolean, onSelect: (Int) -> Unit, describe: (Int) -> String): Modifier = + this + .pointerInput(rtl) { detectTapGestures { onSelect(juzAt(it.x, size.width, rtl)) } } + .pointerInput(rtl) { detectHorizontalDragGestures { change, _ -> onSelect(juzAt(change.position.x, size.width, rtl)) } } + .semantics { + contentDescription = describe(current) + progressBarRangeInfo = ProgressBarRangeInfo(current.toFloat(), 1f..30f, steps = 28) + setProgress { value -> + onSelect(value.roundToInt().coerceIn(1, 30)) + true + } + } + +private fun DrawScope.drawNowMarker(color: Color, surface: Color, center: Offset) { + drawCircle(surface, radius = 12.dp.toPx(), center = center) + drawCircle(color, radius = 9.dp.toPx(), center = center, style = Stroke(6.dp.toPx())) +} + +private fun DrawScope.drawPaceRing(color: Color, center: Offset) { + drawCircle( + color, + radius = 11.dp.toPx(), + center = center, + style = Stroke(2.dp.toPx(), pathEffect = PathEffect.dashPathEffect(floatArrayOf(3.dp.toPx(), 3.dp.toPx()))), + ) +} + +/** The juz line's key: its marks drawn as on the line, each with its meaning. */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun JuzLegend(color: Color, showPace: Boolean, now: String, pace: String, read: String, modifier: Modifier = Modifier) { + val surface = MaterialTheme.colorScheme.surface + val paceColor = MaterialTheme.colorScheme.primary + FlowRow(modifier, horizontalArrangement = Arrangement.spacedBy(20.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { + LegendItem(now) { drawNowMarker(color, surface, Offset(size.width / 2, size.height / 2)) } + if (showPace) LegendItem(pace) { drawPaceRing(paceColor, Offset(size.width / 2, size.height / 2)) } + LegendItem(read) { + val y = size.height / 2 + drawLine(color, Offset(2.dp.toPx(), y), Offset(size.width - 2.dp.toPx(), y), 6.dp.toPx(), StrokeCap.Round) + } + } +} + +@Composable +private fun LegendItem(text: String, mark: DrawScope.() -> Unit) { + Row(verticalAlignment = Alignment.CenterVertically) { + Canvas(Modifier.size(26.dp), onDraw = mark) + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 6.dp), + ) + } +} + +/** + * Ayat held in each of the 30 juz, numbered like the juz line: a bar for the share held, with how + * many. A juz is a button that lists its suras. + */ +@Composable +internal fun HeldChart( + held: ImmutableList, + color: Color, + selectedJuz: Int?, + onSelect: (Int) -> Unit, + describe: (Held) -> String, + panel: Color, + faded: Boolean, + modifier: Modifier = Modifier, +) { + val numbers = rememberNumbers() + val stub = MaterialTheme.colorScheme.outline.copy(alpha = 0.45f) + val height = 120.dp + BoxWithConstraints(modifier.fillMaxWidth()) { + // counts that aren't 0; on a narrow screen, the numbers of 1, every fifth and the chosen juz + val sparse = maxWidth / 30 < 20.dp + Row(Modifier.fillMaxWidth()) { + held.forEach { juz -> + val share = if (juz.ayat == 0) 0f else juz.held.toFloat() / juz.ayat + val selected = juz.number == selectedJuz + Column( + Modifier + .weight(1f) + // a background, not a clip: the counts and numbers may be wider than a narrow column + .background(if (selected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent, RoundedCornerShape(6.dp)), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Box(Modifier.fillMaxWidth().height(height).padding(horizontal = 2.dp), contentAlignment = Alignment.BottomCenter) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text( + if (juz.held == 0) "" else numbers(juz.held), + style = MaterialTheme.typography.labelSmall.tabular(), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + softWrap = false, + overflow = TextOverflow.Visible, + modifier = Modifier.background(if (selected) Color.Transparent else panel), + ) + val bar = if (juz.held == 0) 2.dp else ((height - 16.dp) * share).coerceAtLeast(3.dp) + val tint = if (juz.held == 0) stub else color + Box( + Modifier + .fillMaxWidth() + .height(bar) + .clip(RoundedCornerShape(topStart = 3.dp, topEnd = 3.dp)) + .background(if (faded) tint.copy(alpha = 0.45f) else tint) + ) + } + } + Text( + if (!sparse || selected || juz.number == 1 || juz.number % 5 == 0) numbers(juz.number) else "", + style = MaterialTheme.typography.labelSmall.tabular(), + fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal, + color = if (selected) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + softWrap = false, + overflow = TextOverflow.Visible, + modifier = Modifier.padding(vertical = 3.dp), + ) + } + } + } + val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl + Box(Modifier.matchParentSize().juzControl(selectedJuz ?: 30, rtl, onSelect) { number -> describe(held[number - 1]) }) + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/ProgressIcons.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/ProgressIcons.kt new file mode 100644 index 0000000000..54359a69da --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/ProgressIcons.kt @@ -0,0 +1,57 @@ +package com.quran.mobile.feature.progress.ui + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.PathParser +import androidx.compose.ui.unit.dp + +/** Icons the app's shared set doesn't have (paths from Material Icons, Apache-2.0). */ +internal object ProgressIcons { + val Bookmark: ImageVector by lazy { + icon("Bookmark", "M17,3H7c-1.1,0 -1.99,0.9 -1.99,2L5,21l7,-3 7,3V5c0,-1.1 -0.9,-2 -2,-2z") + } + + val Add: ImageVector by lazy { + icon("Add", "M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z") + } + + /** Memorizing: a book. */ + val Memorizing: ImageVector by lazy { + icon( + "AutoStories", + "M19,1l-5,5v11l5,-4.5V1zM1,6v14.65c0,0.25 0.25,0.5 0.5,0.5c0.1,0 0.15,-0.05 0.25,-0.05C3.1,20.45 5.05,20 6.5,20" + + "c1.95,0 4.05,0.4 5.5,1.5V6c-1.45,-1.1 -3.55,-1.5 -5.5,-1.5S2.45,4.9 1,6zM23,19.5V6c-0.6,-0.45 -1.25,-0.75 -2,-1" + + "v13.5c-1.1,-0.35 -2.3,-0.5 -3.5,-0.5c-1.7,0 -4.15,0.65 -5.5,1.5v2c1.35,-0.85 3.8,-1.5 5.5,-1.5c1.65,0 3.35,0.3 4.75,1.05" + + "c0.1,0.05 0.15,0.05 0.25,0.05c0.25,0 0.5,-0.25 0.5,-0.5v-1.1z", + ) + } + + /** Salah. */ + val Mosque: ImageVector by lazy { + icon( + "Mosque", + "M7,8h10c0.29,0,0.57,0.06,0.84,0.13C17.93,7.8,18,7.46,18,7.09c0-1.31-0.65-2.53-1.74-3.25L12,1L7.74,3.84" + + " C6.65,4.56,6,5.78,6,7.09C6,7.46,6.07,7.8,6.16,8.13C6.43,8.06,6.71,8,7,8z", + "M24,7c0-1.1-2-3-2-3s-2,1.9-2,3c0,0.74,0.4,1.38,1,1.72V13h-2v-2c0-1.1-0.9-2-2-2H7c-1.1,0-2,0.9-2,2v2H3V8.72" + + " C3.6,8.38,4,7.74,4,7c0-1.1-2-3-2-3S0,5.9,0,7c0,0.74,0.4,1.38,1,1.72V21h9v-4c0-1.1,0.9-2,2-2s2,0.9,2,2v4h9V8.72" + + " C23.6,8.38,24,7.74,24,7z", + ) + } + + /** Sessions: a list by date. */ + val Sessions: ImageVector by lazy { + icon( + "EventNote", + "M17,10L7,10v2h10v-2zM19,3h-1L18,1h-2v2L8,3L8,1L6,1v2L5,3c-1.11,0 -1.99,0.9 -1.99,2L3,19c0,1.1 0.89,2 2,2h14" + + "c1.1,0 2,-0.9 2,-2L21,5c0,-1.1 -0.9,-2 -2,-2zM19,19L5,19L5,8h14v11zM14,14L7,14v2h7v-2z", + ) + } + + val PlayArrow: ImageVector by lazy { icon("PlayArrow", "M8,5v14l11,-7z") } + + private fun icon(name: String, vararg paths: String): ImageVector = + ImageVector.Builder(name, 24.dp, 24.dp, 24f, 24f) + .apply { paths.forEach { addPath(PathParser().parsePathString(it).toNodes(), fill = SolidColor(Color.Black)) } } + .build() +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/ProgressScreen.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/ProgressScreen.kt new file mode 100644 index 0000000000..b62d229e35 --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/ProgressScreen.kt @@ -0,0 +1,309 @@ +package com.quran.mobile.feature.progress.ui + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawing +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.NavigationBar +import androidx.compose.material3.NavigationBarItem +import androidx.compose.material3.NavigationBarItemDefaults +import androidx.compose.material3.NavigationRail +import androidx.compose.material3.NavigationRailItem +import androidx.compose.material3.NavigationRailItemDefaults +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.material3.VerticalDivider +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.labs.androidquran.common.ui.core.QuranIcons +import com.quran.labs.androidquran.common.ui.core.WidthClass +import com.quran.labs.androidquran.common.ui.core.widthClassOf +import com.quran.mobile.feature.progress.R +import androidx.appcompat.R as AppCompatR + +/** Sura names, for the screens that list suras. */ +internal val LocalSuraNames = staticCompositionLocalOf<(Int) -> String> { { sura -> sura.toString() } } + +/** What the user chose on the screen: the section, and the bookmark or session open in it. */ +@Immutable +data class ProgressSelection( + val section: ProgressSection = ProgressSection.BOOKMARKS, + val bookmark: ReadingBookmarkType? = null, + val session: String? = null, +) + +/** What the screen asks of its host. */ +@Immutable +class ProgressActions( + val onSelection: (ProgressSelection) -> Unit = {}, + val onAddBookmark: () -> Unit = {}, + val onAllowNotifications: () -> Unit = {}, + val onReminderTime: () -> Unit = {}, + val onStartCycle: (ReadingBookmarkType) -> Unit = {}, + val onPlayRecording: (String) -> Unit = {}, + val onBack: () -> Unit = {}, +) + +/** + * Progress, by the window's width (Material's navigation by size): + * - expanded (a tablet, e.g. the MatePad 12 X) and medium: a navigation rail, the list, and the + * chosen bookmark or session beside it (the list narrower where there's less room); + * - compact (a phone): a navigation bar and one pane at a time. + * + * On a wide screen a bookmark is always open (the first one, until another is chosen). + */ +@Composable +fun ProgressScreen( + state: ProgressUiState, + selection: ProgressSelection, + actions: ProgressActions, + dark: Boolean, + modifier: Modifier = Modifier, +) { + BoxWithConstraints( + modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.surface) + ) { + val width = maxWidth + when (widthClassOf(width)) { + WidthClass.Expanded -> Row(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.safeDrawing)) { + Rail(selection, actions) + // a tablet in portrait gives the list less, so the days beside it fit + TwoPanes(state, selection, actions, dark, listWidth = if (width >= 1200.dp) 300.dp else 240.dp) + } + WidthClass.Medium -> Row(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.safeDrawing)) { + Rail(selection, actions) + TwoPanes(state, selection, actions, dark, listWidth = 220.dp) + } + WidthClass.Compact -> CompactProgress(state, selection, actions, dark) + } + } +} + +private data class Destination(val section: ProgressSection, val label: Int, val icon: ImageVector) + +private val destinations = listOf( + Destination(ProgressSection.BOOKMARKS, R.string.progress_section_bookmarks, ProgressIcons.Bookmark), + Destination(ProgressSection.MEMORIZING, R.string.progress_section_memorizing, ProgressIcons.Memorizing), + Destination(ProgressSection.SALAH, R.string.progress_section_salah, ProgressIcons.Mosque), + Destination(ProgressSection.SESSIONS, R.string.progress_section_sessions, ProgressIcons.Sessions), +) + +@Composable +private fun BackButton(onBack: () -> Unit) { + IconButton(onClick = onBack) { + Icon( + QuranIcons.ArrowBack, + contentDescription = stringResource(AppCompatR.string.abc_action_bar_up_description), + ) + } +} + +@Composable +private fun Rail(selection: ProgressSelection, actions: ProgressActions) { + NavigationRail( + containerColor = panelColor(), + header = { BackButton(actions.onBack) }, + windowInsets = WindowInsets(0, 0, 0, 0), + ) { + destinations.forEach { destination -> + NavigationRailItem( + selected = selection.section == destination.section, + onClick = { actions.onSelection(selection.copy(section = destination.section)) }, + icon = { Icon(destination.icon, contentDescription = null) }, + label = { Text(stringResource(destination.label)) }, + colors = NavigationRailItemDefaults.colors(indicatorColor = MaterialTheme.colorScheme.primaryContainer), + ) + } + } +} + +@Composable +private fun androidx.compose.foundation.layout.RowScope.TwoPanes( + state: ProgressUiState, + selection: ProgressSelection, + actions: ProgressActions, + dark: Boolean, + listWidth: Dp, +) { + when (selection.section) { + ProgressSection.BOOKMARKS -> { + val open = state.bookmarks.firstOrNull { it.slot == selection.bookmark } ?: state.bookmarks.firstOrNull() + BookmarkList( + bookmarks = state.bookmarks, + selected = open?.slot, + canAdd = state.canAddBookmark, + onSelect = { actions.onSelection(selection.copy(bookmark = it)) }, + onAdd = actions.onAddBookmark, + modifier = Modifier.width(listWidth).fillMaxHeight(), + ) + VerticalDivider(color = MaterialTheme.colorScheme.surfaceVariant) + if (open == null) { + Choose(stringResource(R.string.progress_choose_bookmark), Modifier.weight(1f)) + } else { + BookmarkDetail( + bookmark = open, + reminder = state.reminder, + uncreditedTodayMinutes = state.uncreditedTodayMinutes, + onAllowNotifications = actions.onAllowNotifications, + onReminderTime = actions.onReminderTime, + onStartCycle = { actions.onStartCycle(open.slot) }, + modifier = Modifier.weight(1f).fillMaxHeight(), + dark = dark, + ) + } + } + ProgressSection.MEMORIZING -> MemorizingPane(state.memorizing, Modifier.weight(1f).fillMaxHeight(), dark) + ProgressSection.SALAH -> SalahPane(state.salah, Modifier.weight(1f).fillMaxHeight(), dark) + ProgressSection.SESSIONS -> { + SessionList( + sessions = state.sessions, + selected = selection.session, + onSelect = { actions.onSelection(selection.copy(session = it)) }, + modifier = Modifier.width(listWidth + 40.dp).fillMaxHeight(), + ) + VerticalDivider(color = MaterialTheme.colorScheme.surfaceVariant) + val open = state.sessions.firstOrNull { it.id == selection.session } + if (open == null) { + Choose(stringResource(R.string.progress_choose_session), Modifier.weight(1f)) + } else { + SessionDetail(open, actions.onPlayRecording, Modifier.weight(1f).fillMaxHeight()) + } + } + } +} + +/** One pane at a time: a list, or (once chosen) what's chosen in it, with Back to the list. */ +@Composable +private fun OnePane( + state: ProgressUiState, + selection: ProgressSelection, + actions: ProgressActions, + dark: Boolean, + modifier: Modifier = Modifier, + showTitles: Boolean = true, +) { + Box(modifier.fillMaxSize()) { + when (selection.section) { + ProgressSection.BOOKMARKS -> { + val open = state.bookmarks.firstOrNull { it.slot == selection.bookmark } + BackHandler(enabled = open != null) { actions.onSelection(selection.copy(bookmark = null)) } + if (open == null) { + BookmarkList( + bookmarks = state.bookmarks, + selected = null, + canAdd = state.canAddBookmark, + onSelect = { actions.onSelection(selection.copy(bookmark = it)) }, + onAdd = actions.onAddBookmark, + modifier = Modifier.fillMaxSize(), + showTitle = showTitles, + ) + } else { + BookmarkDetail( + bookmark = open, + reminder = state.reminder, + uncreditedTodayMinutes = state.uncreditedTodayMinutes, + onAllowNotifications = actions.onAllowNotifications, + onReminderTime = actions.onReminderTime, + onStartCycle = { actions.onStartCycle(open.slot) }, + modifier = Modifier.fillMaxSize(), + dark = dark, + showName = showTitles, + ) + } + } + ProgressSection.MEMORIZING -> MemorizingPane(state.memorizing, Modifier.fillMaxSize(), dark) + ProgressSection.SALAH -> SalahPane(state.salah, Modifier.fillMaxSize(), dark) + ProgressSection.SESSIONS -> { + val open = state.sessions.firstOrNull { it.id == selection.session } + BackHandler(enabled = open != null) { actions.onSelection(selection.copy(session = null)) } + if (open == null) { + SessionList( + sessions = state.sessions, + selected = null, + onSelect = { actions.onSelection(selection.copy(session = it)) }, + modifier = Modifier.fillMaxSize(), + showTitle = showTitles, + ) + } else { + SessionDetail(open, actions.onPlayRecording, Modifier.fillMaxSize(), showTitle = showTitles) + } + } + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun CompactProgress(state: ProgressUiState, selection: ProgressSelection, actions: ProgressActions, dark: Boolean) { + val inDetail = (selection.section == ProgressSection.BOOKMARKS && state.bookmarks.any { it.slot == selection.bookmark }) || + (selection.section == ProgressSection.SESSIONS && state.sessions.any { it.id == selection.session }) + Scaffold( + topBar = { + TopAppBar( + title = { + val openBookmark = state.bookmarks.firstOrNull { it.slot == selection.bookmark } + val openSession = state.sessions.firstOrNull { it.id == selection.session } + Text( + when { + selection.section == ProgressSection.BOOKMARKS && openBookmark != null -> openBookmark.name + selection.section == ProgressSection.SESSIONS && openSession != null -> openSession.title + else -> stringResource(destinations.first { it.section == selection.section }.label) + } + ) + }, + navigationIcon = { + BackButton { + when { + selection.section == ProgressSection.BOOKMARKS && inDetail -> actions.onSelection(selection.copy(bookmark = null)) + selection.section == ProgressSection.SESSIONS && inDetail -> actions.onSelection(selection.copy(session = null)) + else -> actions.onBack() + } + } + }, + colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.surface), + ) + }, + bottomBar = { + NavigationBar(containerColor = panelColor()) { + destinations.forEach { destination -> + NavigationBarItem( + selected = selection.section == destination.section, + onClick = { actions.onSelection(selection.copy(section = destination.section)) }, + icon = { Icon(destination.icon, contentDescription = null) }, + label = { Text(stringResource(destination.label)) }, + colors = NavigationBarItemDefaults.colors(indicatorColor = MaterialTheme.colorScheme.primaryContainer), + ) + } + } + }, + containerColor = MaterialTheme.colorScheme.surface, + ) { padding -> + Column(Modifier.padding(padding)) { + OnePane(state, selection, actions, dark, Modifier.weight(1f), showTitles = false) + } + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/ProgressText.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/ProgressText.kt new file mode 100644 index 0000000000..2b06274995 --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/ProgressText.kt @@ -0,0 +1,94 @@ +package com.quran.mobile.feature.progress.ui + +import android.content.Context +import android.text.format.DateUtils +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.material3.MaterialTheme +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.compositeOver +import androidx.compose.ui.text.TextStyle +import com.quran.data.model.bookmark.ReadingBookmarkPurpose +import com.quran.mobile.feature.progress.R +import com.quran.mobile.progress.time.LocalDays +import java.text.NumberFormat +import java.util.Locale +import java.util.TimeZone + +/** Numbers in charts line up: tabular figures. */ +internal fun TextStyle.tabular(): TextStyle = merge(TextStyle(fontFeatureSettings = "tnum")) + +/** The locale's digits (Arabic-Indic in Arabic). */ +@Composable +internal fun rememberNumbers(): (Int) -> String { + val locale = LocalConfiguration.current.locales[0] ?: Locale.getDefault() + val format = remember(locale) { NumberFormat.getIntegerInstance(locale).apply { isGroupingUsed = false } } + return remember(format) { { value: Int -> format.format(value) } } +} + +/** Noon of a local day: safely inside it whatever the time zone does. */ +internal fun noonOf(day: Long, zone: TimeZone = TimeZone.getDefault()): Long = + LocalDays.startOfDayMs(day, zone) + 12 * 3_600_000L + +/** E.g. "Sunday 3 November". */ +internal fun Context.dayWithWeekday(day: Long): String = DateUtils.formatDateTime( + this, noonOf(day), DateUtils.FORMAT_SHOW_WEEKDAY or DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_NO_YEAR, +) + +/** E.g. "2 December". */ +internal fun Context.dayOnly(day: Long): String = + DateUtils.formatDateTime(this, noonOf(day), DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_NO_YEAR) + +/** E.g. "2 – 30 October". */ +internal fun Context.dayRange(first: Long, last: Long): String = DateUtils.formatDateRange( + this, noonOf(first), noonOf(last), DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_NO_YEAR, +) + +/** E.g. "8:00 pm", in the device's 12 or 24 hour clock. */ +internal fun Context.timeOfDay(minuteOfDay: Int): String = + DateUtils.formatDateTime(this, LocalDays.timeOnDay(0, minuteOfDay, TimeZone.getDefault()), DateUtils.FORMAT_SHOW_TIME) + +@Composable +internal fun duration(ms: Long): String { + val minutes = (ms / 60_000L).toInt() + return if (minutes >= 60) { + stringResource(R.string.progress_hours_minutes, minutes / 60, minutes % 60) + } else { + stringResource(R.string.progress_minutes_only, minutes) + } +} + +@Composable +internal fun purposeName(purpose: ReadingBookmarkPurpose): String = stringResource( + when (purpose) { + ReadingBookmarkPurpose.READING -> R.string.progress_purpose_reading + ReadingBookmarkPurpose.MEMORIZATION -> R.string.progress_purpose_memorization + ReadingBookmarkPurpose.REVIEW -> R.string.progress_purpose_review + } +) + +@Composable +internal fun pages(count: Int): String = pluralStringResource(R.plurals.progress_pages, count, count) + +@Composable +internal fun minutes(count: Int): String = pluralStringResource(R.plurals.progress_minutes, count, count) + +@Composable +internal fun days(count: Int): String = pluralStringResource(R.plurals.progress_days, count, count) + +@Composable +internal fun context(): Context = LocalContext.current + +/** + * The panels' color: the app's surface with a touch of its surface variant (Material's container + * roles aren't part of the app's theme). + */ +@Composable +internal fun panelColor(): Color { + val scheme = MaterialTheme.colorScheme + return scheme.surfaceVariant.copy(alpha = 0.38f).compositeOver(scheme.surface) +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/ProgressUiState.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/ProgressUiState.kt new file mode 100644 index 0000000000..02b31cc812 --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/ProgressUiState.kt @@ -0,0 +1,142 @@ +package com.quran.mobile.feature.progress.ui + +import androidx.compose.runtime.Immutable +import com.quran.data.model.bookmark.ReadingBookmarkPurpose +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.mobile.progress.summary.Held +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.ImmutableMap +import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.persistentMapOf + +enum class ProgressSection { BOOKMARKS, MEMORIZING, SALAH, SESSIONS } + +/** + * One column of a day chart: [above] the axis, [below] it; null for a day still to come. [empty] for + * a day with nothing to show (no session that day), drawn as just its number. + */ +@Immutable +data class DayColumn( + val dayN: Int, + val label: Int, + val above: Int?, + val below: Int?, + val isToday: Boolean, + val empty: Boolean = false, +) + +/** Where a bookmark stands on the juz line: 0 is the start of juz 1, 30 the end of juz 30. */ +@Immutable +data class JuzLineState( + val position: Float?, + /** Where the read part starts (the cycle's start, or where Progress first saw it). */ + val runStart: Float?, + /** Where a steady pace is by the end of today, for a cycle with a deadline. */ + val pace: Float?, + /** The juz the bookmark is in. */ + val current: Int?, + /** Pages of each juz, and how many of them were read this cycle. */ + val juz: ImmutableList, +) + +@Immutable +data class JuzPages(val juz: Int, val firstPage: Int, val lastPage: Int, val read: Int) { + val pages: Int get() = lastPage - firstPage + 1 +} + +/** Where a bookmark is, for its sentence: its page, and the sura and ayah it marks. */ +@Immutable +data class BookmarkPlace(val page: Int, val suraName: String, val sura: Int, val ayah: Int) + +@Immutable +data class BookmarkView( + val slot: ReadingBookmarkType, + val name: String, + val purpose: ReadingBookmarkPurpose, + val targetDays: Int, + val place: BookmarkPlace?, + val juz: Int?, + /** The open cycle's start (local day), when it's known. */ + val cycleStartDay: Long?, + /** Since when Progress has followed it, when the cycle's start isn't known. */ + val followedSinceDay: Long?, + val dayN: Int?, + val finishByDay: Long?, + val overdue: Boolean, + /** Pages ahead of a steady pace (negative when behind), for a cycle with a deadline. */ + val ahead: Int?, + val line: JuzLineState, + val days: ImmutableList, + /** Pages a day that finish in time, drawn as the goal line. */ + val goal: Int?, + val averageMinutes: Int?, + val todayMinutes: Int?, + val cycleReadingMs: Long, + val cyclePages: Int, + val lastCycleDays: Int?, + val lastCycleStartDay: Long?, + val lastCycleEndDay: Long?, + /** Whether it has moved since Progress kept track; if not, its days are sample ones. */ + val hasHistory: Boolean, +) { + val placed: Boolean get() = place != null +} + +@Immutable +data class MemorizingView( + /** The juz shown first: the memorization bookmark's, else the one with the most held. */ + val focusJuz: Int?, + val juz: ImmutableList, + val suras: ImmutableMap>, + /** Accuracy (percent) above, hints below. */ + val days: ImmutableList, + val averageAccuracy: Int?, + val hasHistory: Boolean, +) + +@Immutable +data class SalahView( + /** Prayers followed above, hints below. */ + val days: ImmutableList, + val prayers: Int, + val hasHistory: Boolean, +) + +@Immutable +data class SessionAyahView(val suraName: String, val sura: Int, val ayah: Int, val ayahWords: Int, val words: Int, val hinted: Int, val missed: Int) + +@Immutable +data class SessionView( + val id: String, + /** Its passage, e.g. "Al-Ikhlas 1–4". */ + val title: String, + val day: Long, + val startedAtMs: Long, + val mode: String, + val from: String, + val to: String, + val minutes: Int, + val recited: Int, + val hinted: Int, + val missed: Int, + val finished: Boolean, + val recordingId: String?, + val ayahs: ImmutableList, +) + +@Immutable +data class ReminderView(val on: Boolean, val minuteOfDay: Int, val allowed: Boolean) + +@Immutable +data class ProgressUiState( + val today: Long, + val bookmarks: ImmutableList = persistentListOf(), + val memorizing: MemorizingView = MemorizingView(null, persistentListOf(), persistentMapOf(), persistentListOf(), null, false), + val salah: SalahView = SalahView(persistentListOf(), 0, false), + /** Newest first. */ + val sessions: ImmutableList = persistentListOf(), + val uncreditedTodayMinutes: Int = 0, + val reminder: ReminderView = ReminderView(on = true, minuteOfDay = 20 * 60, allowed = true), + /** Whether more bookmarks can be turned on. */ + val canAddBookmark: Boolean = true, +) diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/SampleProgress.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/SampleProgress.kt new file mode 100644 index 0000000000..c59ecaca84 --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/SampleProgress.kt @@ -0,0 +1,34 @@ +package com.quran.mobile.feature.progress.ui + +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.toImmutableList + +/** Days shown, faded and labelled "Sample data", until there is history to show. */ +internal object SampleProgress { + private val pages = listOf(16, 22, 19, 26, 10, 0, 24, 21, 27, 15, 25, 24) + private val minutes = listOf(34, 49, 38, 55, 22, 3, 52, 42, 59, 31, 54, 58) + private val accuracy = listOf(88, 91, 84, 0, 93, 95, 90, 0, 96, 92, 94, 97) + private val hints = listOf(9, 6, 11, 0, 5, 3, 6, 0, 2, 4, 3, 2) + private val prayers = listOf(5, 4, 5, 5, 3, 5, 5, 4, 5, 5, 5, 2) + private val salahHints = listOf(2, 3, 1, 0, 4, 1, 0, 2, 1, 0, 1, 0) + + /** [columns] with sample values in place of their own, for the days up to today. */ + fun reading(columns: ImmutableList): ImmutableList = fill(columns, pages, minutes) + + fun memorizing(columns: ImmutableList): ImmutableList = fill(columns, accuracy, hints) + + fun salah(columns: ImmutableList): ImmutableList = fill(columns, prayers, salahHints) + + private fun fill(columns: List, above: List, below: List): ImmutableList { + val today = columns.indexOfFirst { it.isToday }.takeIf { it >= 0 } ?: (columns.size - 1) + return columns.mapIndexed { index, column -> + if (column.above == null) { + column + } else { + // the last sample day lands on today + val sample = (above.size - 1 + index - today).mod(above.size) + column.copy(above = above[sample], below = below[sample], empty = above[sample] == 0 && below[sample] == 0) + } + }.toImmutableList() + } +} diff --git a/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/SessionsPanes.kt b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/SessionsPanes.kt new file mode 100644 index 0000000000..ed8e628c26 --- /dev/null +++ b/feature/progress/src/main/kotlin/com/quran/mobile/feature/progress/ui/SessionsPanes.kt @@ -0,0 +1,354 @@ +package com.quran.mobile.feature.progress.ui + +import android.text.format.DateUtils +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.luminance +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import com.quran.labs.androidquran.common.ui.core.QuranIcons +import com.quran.mobile.feature.progress.R +import kotlinx.collections.immutable.ImmutableList + +/** Memorizing: ayat held per juz (and per sura of the juz chosen), then accuracy and hints per day. */ +@Composable +internal fun MemorizingPane(view: MemorizingView, modifier: Modifier = Modifier, dark: Boolean = false) { + val panel = panelColor() + val context = context() + var selectedJuz by rememberSaveable(view.focusJuz) { mutableStateOf(view.focusJuz) } + val accent = MaterialTheme.colorScheme.primary + Column(modifier.verticalScroll(rememberScrollState()).padding(horizontal = 28.dp, vertical = 22.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + stringResource(R.string.progress_section_memorizing), + style = MaterialTheme.typography.headlineMedium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f), + ) + if (!view.hasHistory) Label(stringResource(R.string.progress_sample), quiet = true) + } + Text( + stringResource(R.string.progress_held_explained), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 6.dp, bottom = 18.dp), + ) + Panel(panel) { + Caption(stringResource(R.string.progress_held_title), null) + HeldChart( + held = view.juz, + color = accent, + selectedJuz = selectedJuz, + onSelect = { selectedJuz = it }, + describe = { juz -> + context.getString(R.string.progress_juz, juz.number) + ": " + context.getString(R.string.progress_held_of, juz.held, juz.ayat) + }, + panel = panel, + faded = !view.hasHistory, + ) + selectedJuz?.let { juz -> + val held = view.juz.firstOrNull { it.number == juz } + if (held != null) { + Text( + stringResource(R.string.progress_held_summary, juz, held.held, held.ayat), + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(top = 12.dp, bottom = 4.dp), + ) + } + view.suras[juz].orEmpty().forEach { sura -> HeldRow(sura.number, sura.held, sura.ayat, accent) } + } + } + Panel(panel) { + Caption(stringResource(R.string.progress_accuracy_title), stringResource(R.string.progress_accuracy_per_day)) + DayBars( + columns = if (view.hasHistory) view.days else SampleProgress.memorizing(view.days), + aboveColor = accent, + belowColor = MaterialTheme.colorScheme.tertiary, + aboveLine = null, + belowLine = null, + describe = { column -> "${column.label}: ${column.above ?: 0}%, ${column.below ?: 0}" }, + panel = panel, + faded = !view.hasHistory, + dark = dark, + aboveHeight = 150.dp, + belowHeight = 100.dp, + ) + Text( + stringResource(R.string.progress_hints_per_day), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 8.dp), + ) + if (!view.hasHistory) Note(stringResource(R.string.progress_no_sessions)) + } + } +} + +@Composable +private fun HeldRow(sura: Int, held: Int, ayat: Int, color: Color) { + val naming = LocalSuraNames.current + Row(Modifier.fillMaxWidth().padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically) { + Text( + naming(sura), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.width(140.dp), + ) + // the share held, as a bar the width of the row + Row(Modifier.weight(1f).height(8.dp).clip(RoundedCornerShape(4.dp)).background(MaterialTheme.colorScheme.surfaceVariant)) { + val share = if (ayat == 0) 0f else held.toFloat() / ayat + if (share > 0f) Spacer(Modifier.weight(share).height(8.dp).background(color)) + if (share < 1f) Spacer(Modifier.weight(1f - share)) + } + Text( + stringResource(R.string.progress_held_of, held, ayat), + style = MaterialTheme.typography.bodySmall.tabular(), + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 12.dp), + ) + } +} + +/** Salah: prayers followed above the days, hints below. */ +@Composable +internal fun SalahPane(view: SalahView, modifier: Modifier = Modifier, dark: Boolean = false) { + val panel = panelColor() + Column(modifier.verticalScroll(rememberScrollState()).padding(horizontal = 28.dp, vertical = 22.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + stringResource(R.string.progress_salah_title), + style = MaterialTheme.typography.headlineMedium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f), + ) + if (!view.hasHistory) Label(stringResource(R.string.progress_sample), quiet = true) + } + Spacer(Modifier.height(18.dp)) + Panel(panel) { + Caption(stringResource(R.string.progress_days_title), stringResource(R.string.progress_prayers_per_day)) + DayBars( + columns = if (view.hasHistory) view.days else SampleProgress.salah(view.days), + aboveColor = MaterialTheme.colorScheme.primary, + belowColor = MaterialTheme.colorScheme.tertiary, + aboveLine = null, + belowLine = null, + describe = { column -> "${column.label}: ${column.above ?: 0}, ${column.below ?: 0}" }, + panel = panel, + faded = !view.hasHistory, + dark = dark, + aboveHeight = 150.dp, + belowHeight = 100.dp, + ) + Text( + stringResource(R.string.progress_salah_hints), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 8.dp), + ) + if (!view.hasHistory) Note(stringResource(R.string.progress_no_sessions)) + } + } +} + +/** Sessions by day, newest first; the chosen one is highlighted. */ +@Composable +internal fun SessionList( + sessions: ImmutableList, + selected: String?, + onSelect: (String) -> Unit, + modifier: Modifier = Modifier, + showTitle: Boolean = true, +) { + val context = context() + Column(modifier.verticalScroll(rememberScrollState()).padding(vertical = 20.dp)) { + if (showTitle) { + Text( + stringResource(R.string.progress_section_sessions), + style = MaterialTheme.typography.headlineSmall, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(start = 20.dp, end = 20.dp, bottom = 14.dp), + ) + } + if (sessions.isEmpty()) { + Text( + stringResource(R.string.progress_sessions_empty), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 20.dp), + ) + } + var lastDay: Long? = null + sessions.forEach { session -> + if (session.day != lastDay) { + lastDay = session.day + Text( + context.dayWithWeekday(session.day), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 12.dp, bottom = 4.dp), + ) + } + val isSelected = session.id == selected + Row( + Modifier + .padding(horizontal = 8.dp, vertical = 2.dp) + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .background(if (isSelected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent) + .selectable(selected = isSelected, role = Role.Tab) { onSelect(session.id) } + .padding(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon(modeIcon(session.mode), contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(22.dp)) + Column(Modifier.padding(start = 14.dp)) { + Text(session.title, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.onSurface) + Text( + modeName(session.mode) + stringResource(R.string.progress_separator) + + DateUtils.formatDateTime(context, session.startedAtMs, DateUtils.FORMAT_SHOW_TIME), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + stringResource(R.string.progress_session_counts, session.recited, session.hinted, session.missed) + + stringResource(R.string.progress_separator) + minutes(session.minutes), + style = MaterialTheme.typography.bodySmall.tabular(), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } +} + +/** + * One session: its passage, a strip of its ayat (each as wide as its words, coloured by how it went), + * then each ayah. A recorded session opens in Recording sessions, where it plays back on its pages + * with its timeline. + */ +@Composable +internal fun SessionDetail(session: SessionView, onPlay: (String) -> Unit, modifier: Modifier = Modifier, showTitle: Boolean = true) { + val context = context() + val separator = stringResource(R.string.progress_separator) + Column(modifier.verticalScroll(rememberScrollState()).padding(horizontal = 28.dp, vertical = 22.dp)) { + if (showTitle) { + Text(session.title, style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.onSurface) + } + Text( + listOfNotNull( + modeName(session.mode), + context.dayWithWeekday(session.day), + DateUtils.formatDateTime(context, session.startedAtMs, DateUtils.FORMAT_SHOW_TIME), + minutes(session.minutes), + stringResource(R.string.progress_session_finished).takeIf { session.finished }, + ).joinToString(separator), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 6.dp, bottom = 14.dp), + ) + session.recordingId?.let { id -> + FilledTonalButton(onClick = { onPlay(id) }, modifier = Modifier.padding(bottom = 14.dp)) { + Icon(ProgressIcons.PlayArrow, contentDescription = null, modifier = Modifier.size(18.dp)) + Text(stringResource(R.string.progress_play_recording), modifier = Modifier.padding(start = 8.dp)) + } + } + Panel(panelColor()) { + Caption( + stringResource(R.string.progress_session_ayat), + stringResource(R.string.progress_session_counts, session.recited, session.hinted, session.missed), + ) + AyahStrip(session.ayahs) + Spacer(Modifier.height(10.dp)) + session.ayahs.forEachIndexed { index, ayah -> + if (index > 0) HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant) + Row(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalArrangement = Arrangement.SpaceBetween) { + Text( + stringResource(R.string.progress_session_ayah, ayah.suraName, ayah.sura, ayah.ayah), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + ) + Text( + stringResource(R.string.progress_ayah_counts, ayah.words, ayah.ayahWords, ayah.hinted, ayah.missed), + style = MaterialTheme.typography.bodySmall.tabular(), + color = if (ayah.hinted + ayah.missed == 0 && ayah.words >= ayah.ayahWords) { + MaterialTheme.colorScheme.onSurfaceVariant + } else { + MaterialTheme.colorScheme.error + }, + ) + } + } + } + } +} + +/** + * The session's ayat in a row, each as wide as its words: given hints in teal, skipped words in the + * skipped colour (as on the page), the rest quiet. It runs from the start side. + */ +@Composable +private fun AyahStrip(ayahs: ImmutableList) { + val dark = MaterialTheme.colorScheme.surface.luminance() < 0.5f + val quiet = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.35f) + val hinted = if (dark) Color(0xFF4DB6AC) else Color(0xFF00897B) + val skipped = if (dark) Color(0xFFCE93D8) else Color(0xFFFB8C00) + Row(Modifier.fillMaxWidth().height(14.dp), horizontalArrangement = Arrangement.spacedBy(2.dp)) { + ayahs.forEach { ayah -> + val color = when { + ayah.missed > 0 -> skipped + ayah.hinted > 0 -> hinted + else -> quiet + } + Spacer( + Modifier + .weight(ayah.ayahWords.coerceAtLeast(1).toFloat()) + .height(14.dp) + .clip(RoundedCornerShape(3.dp)) + .background(color) + ) + } + } +} + +@Composable +private fun modeName(mode: String): String = stringResource( + when (mode) { + "SALAH" -> R.string.progress_mode_salah + "RECITE" -> R.string.progress_mode_recite + else -> R.string.progress_mode_memorize + } +) + +private fun modeIcon(mode: String): ImageVector = when (mode) { + "SALAH" -> ProgressIcons.Mosque + "RECITE" -> QuranIcons.MenuBook + else -> QuranIcons.Mic +} diff --git a/feature/progress/src/main/res/drawable/ic_progress_notification.xml b/feature/progress/src/main/res/drawable/ic_progress_notification.xml new file mode 100644 index 0000000000..013ac99fae --- /dev/null +++ b/feature/progress/src/main/res/drawable/ic_progress_notification.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/feature/progress/src/main/res/values-ar/strings.xml b/feature/progress/src/main/res/values-ar/strings.xml new file mode 100644 index 0000000000..d9b3b9b85b --- /dev/null +++ b/feature/progress/src/main/res/values-ar/strings.xml @@ -0,0 +1,163 @@ + + + التقدم + رجوع + + العلامات + الحفظ + الصلاة + الجلسات + + إضافة علامة + قراءة + حفظ + مراجعة + بيانات مثال + غير موضوعة + الجزء %1$d + اليوم %1$d من %2$d + بلا موعد + " · " + + بدأت %1$s + تنتهي بحلول %1$s + كان موعدها %1$s + متابعة منذ %1$s + صفحة %1$d، %2$s %3$d:%4$d + الأجزاء + + على وتيرة %2$d يومًا + متقدمة صفحة واحدة عن وتيرة %2$d يومًا + متقدمة صفحتين عن وتيرة %2$d يومًا + متقدمة %1$d صفحات عن وتيرة %2$d يومًا + متقدمة %1$d صفحة عن وتيرة %2$d يومًا + متقدمة %1$d صفحة عن وتيرة %2$d يومًا + + + على وتيرة %2$d يومًا + متأخرة صفحة واحدة عن وتيرة %2$d يومًا + متأخرة صفحتين عن وتيرة %2$d يومًا + متأخرة %1$d صفحات عن وتيرة %2$d يومًا + متأخرة %1$d صفحة عن وتيرة %2$d يومًا + متأخرة %1$d صفحة عن وتيرة %2$d يومًا + + على وتيرة %1$d يومًا + موضعها + موضع الوتيرة اليوم + ما قُرئ في هذه الختمة + الجزء %1$d: الصفحات %2$d–%3$d، قُرئ %4$d من %5$d في هذه الختمة + الأيام + صفحات كل يوم + الهدف %1$d + دقائق القراءة كل يوم + %1$d في المتوسط + %1$d اليوم + اليوم %1$d: %2$s، %3$s + اليوم %1$d، لم يأت بعد + + لا صفحات + صفحة واحدة + صفحتان + %d صفحات + %d صفحة + %d صفحة + + + لا دقائق + دقيقة واحدة + دقيقتان + %d دقائق + %d دقيقة + %d دقيقة + + + لا أيام + يوم واحد + يومان + %d أيام + %d يومًا + %d يوم + + %1$d س %2$d د + %1$d د + + لا دقائق قراءة اليوم تنتظر علامة + دقيقة قراءة اليوم تُحسب لأول علامة تنقلها + دقيقتا قراءة اليوم تُحسبان لأول علامة تنقلها + %d دقائق قراءة اليوم تُحسب لأول علامة تنقلها + %d دقيقة قراءة اليوم تُحسب لأول علامة تنقلها + %d دقيقة قراءة اليوم تُحسب لأول علامة تنقلها + + قراءة في هذه الختمة، %1$s + آخر ختمة، %1$s + لا شيء بعد + آخر ختمة + تذكير يومي ما دامت الختمة مفتوحة + التذكير اليومي متوقف + اسمح بالإشعارات للتذكير اليومي + سماح + تظهر هنا الصفحات والدقائق حين تقرأ وتنقل هذه العلامة. وحتى ذلك الحين تعرض الأعمدة أيامًا للمثال. + ضع هذه العلامة من قائمة الآية في القارئ، فتبدأ أيامها هنا. + ابدأ ختمة جديدة الآن + + الآيات المحفوظة، حسب الجزء + تُعد الآية محفوظة إذا قرأت كل كلماتها دون تلقين في آخر مرة حفظتها. + %1$d من %2$d آية + الجزء %1$d: %2$d من %3$d آية محفوظة + الجزء %1$d، حسب السورة + الكلمات المقروءة دون مساعدة + النسبة كل يوم + التلقين كل يوم + تمتلئ هذه الرسوم حين تحفظ بالميكروفون. وحتى ذلك الحين تعرض أيامًا للمثال. + + الصلوات المتابَعة + الصلوات كل يوم + التلقين كل يوم + + تظهر هنا حسب اليوم الجلسات التي تقرأ فيها بالميكروفون. + الحفظ + التلاوة + الصلاة + مقروءة %1$d، تلقين %2$d، متروكة %3$d + حتى النهاية + تشغيل التسجيل + %1$s %2$d:%3$d + الآيات + %1$d من %2$d كلمة، تلقين %3$d، متروكة %4$d + اختر جلسة لترى كل آية. + اختر علامة لترى أيامها. + + تذكير القراءة + مرة كل يوم ما دامت الختمة مفتوحة، إن تأخرت أو لم تُقرأ ذلك اليوم + %1$s + %1$d صفحة كل يوم تتمها بحلول %2$s. + متأخرة %1$d صفحة. %2$d صفحة كل يوم تتمها بحلول %3$s. + بقيت %1$d صفحة لإتمام هذه الختمة. + + التقدم + علامات موضع القراءة + فعّل علامات أخرى، وسمّها، واختر الغرض من كل منها + التذكير اليومي + ما دامت الختمة مفتوحة، إن تأخرت أو لم تُقرأ ذلك اليوم + وقت التذكير + حفظ نتائج الجلسات + لرسوم الحفظ والصلاة والجلسات: أعداد فقط، تبقى على هذا الجهاز + مسح سجل التقدم + تنقلات العلامات ووقت القراءة ونتائج الجلسات + يمسح هذا ما حفظه التقدم على هذا الجهاز. تبقى علاماتك في أماكنها. + مسح + تقديم الساعة يومًا (للتجربة) + متقدمة الآن %1$d يومًا. اضغط لزيادة يوم. + إرجاع الساعة إلى اليوم (للتجربة) + ملء 12 يومًا من القراءة (للتجربة) + عرض تذكير اليوم الآن (للتجربة) + لا شيء مستحق: لا ختمة مفتوحة بموعد متأخرة أو لم تُقرأ اليوم، أو الإشعارات متوقفة + + علامات موضع القراءة + متزامنة + على هذا الجهاز فقط + الاسم + الغرض + أيام الإتمام + تتزامن الأزرق المخضر والبرتقالي والأحمر مع حسابك. أما الألوان الأخرى فتبقى على هذا الجهاز، وتظهر في قائمة العلامات في القارئ حين تُفعَّل. + diff --git a/feature/progress/src/main/res/values/ids.xml b/feature/progress/src/main/res/values/ids.xml new file mode 100644 index 0000000000..7dcfa4d25d --- /dev/null +++ b/feature/progress/src/main/res/values/ids.xml @@ -0,0 +1,4 @@ + + + + diff --git a/feature/progress/src/main/res/values/strings.xml b/feature/progress/src/main/res/values/strings.xml new file mode 100644 index 0000000000..852fcddd96 --- /dev/null +++ b/feature/progress/src/main/res/values/strings.xml @@ -0,0 +1,148 @@ + + + Progress + Back + + + Bookmarks + Memorizing + Salah + Sessions + + + Add a bookmark + Reading + Memorization + Review + Sample data + not placed + juz %1$d + day %1$d of %2$d + no deadline + " · " + + + Started %1$s + finishes by %1$s + was due %1$s + Followed since %1$s + page %1$d, %2$s %3$d:%4$d + Juz + + %1$d page ahead of a %2$d-day pace + %1$d pages ahead of a %2$d-day pace + + + %1$d page behind a %2$d-day pace + %1$d pages behind a %2$d-day pace + + on a %1$d-day pace + where it is + where the pace is today + read this cycle + Juz %1$d: pages %2$d–%3$d, %4$d of %5$d read this cycle + Days + pages per day + goal %1$d + minutes reading per day + %1$d on average + %1$d today + Day %1$d: %2$s, %3$s + Day %1$d, still to come + + %d page + %d pages + + + %d minute + %d minutes + + + %d day + %d days + + %1$d h %2$d m + %1$d m + + %d minute read today goes to the next bookmark you move + %d minutes read today go to the next bookmark you move + + reading this cycle, %1$s + last khatma, %1$s + None yet + last khatma + daily reminder while this khatma is open + Daily reminder off + Allow notifications for the daily reminder + Allow + Pages and minutes appear here as you read and move this bookmark. Until then, the bars show sample days. + Place this bookmark from an ayah\'s menu in the reader, and its days start here. + Start a new khatma now + + + Ayat held, by juz + An ayah is held when, the last time you memorized it, you recited every word without a hint. + %1$d of %2$d ayat + Juz %1$d: %2$d of %3$d ayat held + Juz %1$d, by sura + Words recited without help + percent per day + hints per day + These charts fill in as you memorize with the microphone. Until then, they show sample days. + + + Prayers followed + prayers per day + hints given per day + + + Sessions you recite with the microphone appear here, by day. + Memorize + Recitation + Salah + Recited %1$d, hints %2$d, skipped %3$d + to the end + Play the recording + %1$s %2$d:%3$d + Ayat + %1$d of %2$d words, hints %3$d, skipped %4$d + Choose a session to see each ayah. + Choose a bookmark to see its days. + + + Reading reminder + Once a day, while a khatma is open, if it\'s behind or wasn\'t read yet that day + %1$s + %1$d pages a day finish it by %2$s. + %1$d pages behind. %2$d a day still finish it by %3$s. + %1$d pages to go to finish this khatma. + + + Progress + Reading bookmarks + Turn on more bookmarks, name them, and set what each is for + Daily reminder + While a khatma is open, if it\'s behind or wasn\'t read yet that day + Reminder time + Keep session results + For the Memorizing, Salah and Sessions charts: counts only, kept on this device + Clear progress history + Bookmark moves, reading time and session results + This clears what Progress kept on this device. Your bookmarks stay where they are. + Clear + Move the clock a day ahead (debug) + Now %1$d days ahead. Tap to add one. + Put the clock back to today (debug) + Fill in 12 days of reading (debug) + Show today\'s reminder now (debug) + Nothing is due: no open khatma with a deadline is behind or unread today, or notifications are off + + + Reading bookmarks + Synced + On this device only + Name + For + Days to finish + Teal, orange and red sync with your account. The other colours stay on this device, and appear in the reader\'s bookmark menu once turned on. + diff --git a/feature/progress/src/sharedTest/kotlin/com/quran/mobile/feature/progress/ui/SampleStates.kt b/feature/progress/src/sharedTest/kotlin/com/quran/mobile/feature/progress/ui/SampleStates.kt new file mode 100644 index 0000000000..0f05386b62 --- /dev/null +++ b/feature/progress/src/sharedTest/kotlin/com/quran/mobile/feature/progress/ui/SampleStates.kt @@ -0,0 +1,152 @@ +package com.quran.mobile.feature.progress.ui + +import com.quran.data.core.QuranInfo +import com.quran.data.model.bookmark.EmptyReadingBookmark +import com.quran.data.model.bookmark.PageReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmarkPurpose +import com.quran.data.model.bookmark.ReadingBookmarkSlotSetting +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.labs.androidquran.pages.data.madani.MadaniDataSource +import com.quran.mobile.feature.progress.data.ProgressMapper +import com.quran.mobile.feature.progress.data.ProgressSnapshot +import com.quran.mobile.progress.history.DayMinutes +import com.quran.mobile.progress.history.LoggedSession +import com.quran.mobile.progress.log.BookmarkPosition +import com.quran.mobile.progress.log.MoveKind +import com.quran.mobile.progress.log.RecordedMove +import com.quran.mobile.progress.session.AyahResult +import com.quran.mobile.progress.session.SessionRecord +import com.quran.mobile.progress.summary.ProgressCalculator +import com.quran.mobile.progress.time.LocalDays +import java.util.TimeZone +import kotlin.time.Instant + +/** + * Progress as the renders and the device screenshots show it: made-up data in UTC, a khatma started + * on Tuesday 3 November 2026 and seen on Saturday 14 November, a memorization bookmark, one with no + * deadline, one not placed, and twelve days of Memorize and Salah sessions. + */ +object SampleStates { + private val zone = TimeZone.getTimeZone("UTC") + private val quranInfo = QuranInfo(MadaniDataSource()) + private val calculator = ProgressCalculator(quranInfo, "madani") + private val today = LocalDays.epochDay(1_794_657_600_000L, zone) + private val started = today - 11 + + /** The selections the screenshots go through: a name for each, and what's chosen. */ + val screens = listOf( + "bookmarks" to ProgressSelection(ProgressSection.BOOKMARKS), + "bookmark" to ProgressSelection(ProgressSection.BOOKMARKS, bookmark = ReadingBookmarkType.TEAL), + "bookmark_new" to ProgressSelection(ProgressSection.BOOKMARKS, bookmark = ReadingBookmarkType.RED), + "memorizing" to ProgressSelection(ProgressSection.MEMORIZING), + "salah" to ProgressSelection(ProgressSection.SALAH), + "sessions" to ProgressSelection(ProgressSection.SESSIONS, session = "s1"), + ) + + fun state(arabic: Boolean): ProgressUiState { + val suras = if (arabic) mapOf(11 to "هود", 15 to "الحجر", 112 to "الإخلاص", 113 to "الفلق", 114 to "الناس", 67 to "الملك", 2 to "البقرة") + else mapOf(11 to "Hud", 15 to "Al-Hijr", 112 to "Al-Ikhlas", 113 to "Al-Falaq", 114 to "An-Nas", 67 to "Al-Mulk", 2 to "Al-Baqara") + val names = if (arabic) mapOf(ReadingBookmarkType.TEAL to "الختمة", ReadingBookmarkType.ORANGE to "الحفظ", ReadingBookmarkType.RED to "الدراسة") + else mapOf(ReadingBookmarkType.TEAL to "Khatma", ReadingBookmarkType.ORANGE to "Hifz", ReadingBookmarkType.RED to "Study") + val mapper = ProgressMapper( + bookmarkName = { slot, name -> name ?: names[slot] ?: slot.name.lowercase().replaceFirstChar { it.uppercase() } }, + suraName = { suras[it] ?: "Sura $it" }, + dayOfMonth = { day -> ((day - LocalDays.epochDay(1_793_491_200_000L, zone)) + 1).toInt().let { if (it < 1) it + 31 else it } }, + ) + val pages = listOf(16, 22, 19, 26, 10, 0, 24, 21, 27, 15, 25, 24) + val minutes = listOf(34, 49, 38, 55, 22, 3, 52, 42, 59, 31, 54, 58) + val (tealMoves, tealPage, tealMinutes) = reading("TEAL", pages, minutes) + // a cycle finished before: 2 to 30 October + val lastStart = started - 32 + val earlier = listOf( + RecordedMove(LocalDays.timeOnDay(lastStart, 7 * 60, zone), lastStart, MoveKind.BASELINE, BookmarkPosition(1, "madani", 1, 1)), + RecordedMove(LocalDays.timeOnDay(lastStart + 27, 21 * 60, zone), lastStart + 27, MoveKind.MOVE, BookmarkPosition(604, "madani", 114, 1)), + ) + val earlierMinutes = listOf(DayMinutes("TEAL", lastStart + 10, 27_600_000L, earlier[1].atMs - 1)) + val teal = calculator.bookmark( + PageReadingBookmark(ReadingBookmarkType.TEAL, tealPage, Instant.fromEpochMilliseconds(0), names[ReadingBookmarkType.TEAL]), + ReadingBookmarkSlotSetting(ReadingBookmarkType.TEAL, true, ReadingBookmarkPurpose.READING, 30), + earlier + tealMoves.drop(0).let { moves -> + // the wrap from the end back to Al-Fatiha starts this cycle + listOf(moves.first().copy(kind = MoveKind.MOVE)) + moves.drop(1) + }, + earlierMinutes + tealMinutes, + today, + ) + val hifz = calculator.bookmark( + PageReadingBookmark(ReadingBookmarkType.ORANGE, 582, Instant.fromEpochMilliseconds(0), names[ReadingBookmarkType.ORANGE]), + ReadingBookmarkSlotSetting(ReadingBookmarkType.ORANGE, true, ReadingBookmarkPurpose.MEMORIZATION, 0), + listOf(RecordedMove(LocalDays.timeOnDay(today - 20, 9 * 60, zone), today - 20, MoveKind.BASELINE, BookmarkPosition(562, "madani", 67, 1)), + RecordedMove(LocalDays.timeOnDay(today - 2, 9 * 60, zone), today - 2, MoveKind.MOVE, BookmarkPosition(582, "madani", 78, 1))), + emptyList(), + today, + ) + val study = calculator.bookmark( + PageReadingBookmark(ReadingBookmarkType.RED, 42, Instant.fromEpochMilliseconds(0), names[ReadingBookmarkType.RED]), + ReadingBookmarkSlotSetting(ReadingBookmarkType.RED, true, ReadingBookmarkPurpose.READING, 0), + listOf(RecordedMove(LocalDays.timeOnDay(today, 9 * 60, zone), today, MoveKind.BASELINE, BookmarkPosition(42, "madani", 2, 253))), + emptyList(), + today, + ) + val kahf = calculator.bookmark( + EmptyReadingBookmark(ReadingBookmarkType.GREEN, Instant.fromEpochMilliseconds(0), if (arabic) "كهف الجمعة" else "Friday Al-Kahf"), + ReadingBookmarkSlotSetting(ReadingBookmarkType.GREEN, true, ReadingBookmarkPurpose.READING, 0), + emptyList(), + emptyList(), + today, + ) + val sessions = loggedSessions() + val snapshot = ProgressSnapshot( + today = today, + calculator = calculator, + bookmarks = listOf(teal, hifz, study, kahf), + memorizing = calculator.memorizing(sessions, today), + salah = calculator.salah(sessions, today), + sessions = sessions, + uncreditedTodayMs = 0, + ) + return mapper.map(snapshot, ReminderView(on = true, minuteOfDay = 20 * 60, allowed = true), offered = 8) + } + + /** A cycle of [slot] from Al-Fatiha on [started], moving on by [pages] a day with [minutes] read. */ + private fun reading(slot: String, pages: List, minutes: List): Triple, Int, List> { + val moves = mutableListOf( + RecordedMove(LocalDays.timeOnDay(started, 7 * 60, zone), started, MoveKind.BASELINE, BookmarkPosition(1, "madani", 1, 1)) + ) + val credited = mutableListOf() + var page = 1 + pages.forEachIndexed { index, count -> + val day = started + index + val at = LocalDays.timeOnDay(day, 21 * 60, zone) + if (count > 0) { + page += count + val bounds = quranInfo.getPageBounds(page) + moves += RecordedMove(at, day, MoveKind.MOVE, BookmarkPosition(page, "madani", bounds[0], bounds[1])) + } + credited += DayMinutes(slot, day, minutes[index] * 60_000L, at) + } + return Triple(moves, page, credited) + } + + private fun loggedSessions(): List { + val result = mutableListOf() + var index = 0 + fun add(day: Long, mode: String, hinted: Int, sura: Int = 112) { + val ayahs = (1..4).map { AyahResult(sura, it, ayahWords = 4, words = 4, hinted = if (it == 2) hinted else 0, missed = 0, mistakes = 0) } + val start = LocalDays.timeOnDay(day, 6 * 60 + index * 7, zone) + result += LoggedSession( + day, + SessionRecord( + "s${++index}", mode, start, start + 9 * 60_000L, 500_000, sura, 1, sura, 4, 16, 16 - hinted, hinted, 0, 0, + finished = true, recordingId = if (index == 1) "r1" else null, ayahs = ayahs, + ), + ) + } + listOf(9, 6, 11, 0, 5, 3, 6, 0, 2, 4, 3, 2).forEachIndexed { i, hints -> + val day = today - 11 + i + if (hints > 0 || i % 4 != 3) add(day, "MEMORIZE", hints, sura = 112 + i % 3) + repeat(if (i % 5 == 4) 3 else 5) { add(day, "SALAH", if (it == 0) i % 3 else 0, sura = 1) } + } + return result.sortedBy { it.record.startedAtMs } + } +} diff --git a/feature/progress/src/test/kotlin/com/quran/mobile/feature/progress/ProgressMapperTest.kt b/feature/progress/src/test/kotlin/com/quran/mobile/feature/progress/ProgressMapperTest.kt new file mode 100644 index 0000000000..ebfbedd884 --- /dev/null +++ b/feature/progress/src/test/kotlin/com/quran/mobile/feature/progress/ProgressMapperTest.kt @@ -0,0 +1,105 @@ +package com.quran.mobile.feature.progress + +import com.google.common.truth.Truth.assertThat +import com.quran.data.core.QuranInfo +import com.quran.data.model.bookmark.EmptyReadingBookmark +import com.quran.data.model.bookmark.PageReadingBookmark +import com.quran.data.model.bookmark.ReadingBookmarkSlotSetting +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.labs.androidquran.common.ui.core.WidthClass +import com.quran.labs.androidquran.common.ui.core.widthClassOf +import com.quran.labs.androidquran.pages.data.madani.MadaniDataSource +import com.quran.mobile.feature.progress.data.ProgressMapper +import com.quran.mobile.feature.progress.data.ProgressSnapshot +import com.quran.mobile.feature.progress.ui.ReminderView +import com.quran.mobile.progress.history.DayMinutes +import com.quran.mobile.progress.log.BookmarkPosition +import com.quran.mobile.progress.log.MoveKind +import com.quran.mobile.progress.log.RecordedMove +import com.quran.mobile.progress.summary.ProgressCalculator +import org.junit.Test +import kotlin.time.Instant +import androidx.compose.ui.unit.dp + +class ProgressMapperTest { + private val calculator = ProgressCalculator(QuranInfo(MadaniDataSource()), "madani") + private val mapper = ProgressMapper( + bookmarkName = { slot, name -> name ?: slot.name }, + suraName = { "S$it" }, + dayOfMonth = { (it % 30).toInt() + 1 }, + ) + private val today = 100L + private val teal = ReadingBookmarkSlotSetting(ReadingBookmarkType.TEAL, enabled = true, targetDays = 30) + + private fun snapshot(vararg bookmarks: com.quran.mobile.progress.summary.BookmarkProgress) = ProgressSnapshot( + today = today, + calculator = calculator, + bookmarks = bookmarks.toList(), + memorizing = calculator.memorizing(emptyList(), today), + salah = calculator.salah(emptyList(), today), + sessions = emptyList(), + uncreditedTodayMs = 0, + ) + + private fun map(vararg bookmarks: com.quran.mobile.progress.summary.BookmarkProgress) = + mapper.map(snapshot(*bookmarks), ReminderView(on = true, minuteOfDay = 1200, allowed = true), offered = 8) + + @Test + fun aCycleChartHasEveryDayOfTheCycleAndTheRestStillToCome() { + val moves = listOf( + RecordedMove(0, 98, MoveKind.BASELINE, BookmarkPosition(1, "madani", 1, 1)), + RecordedMove(1, 99, MoveKind.MOVE, BookmarkPosition(21, "madani", 2, 137)), + RecordedMove(2, 100, MoveKind.MOVE, BookmarkPosition(41, "madani", 2, 253)), + ) + val progress = calculator.bookmark( + PageReadingBookmark(ReadingBookmarkType.TEAL, 41, Instant.fromEpochMilliseconds(0)), teal, moves, + listOf(DayMinutes("TEAL", 100, 30 * 60_000L, 2)), today, + ) + val view = map(progress).bookmarks.single() + assertThat(view.days).hasSize(30) + assertThat(view.days.take(3).map { it.above }).containsExactly(0, 20, 20).inOrder() + assertThat(view.days[2].below).isEqualTo(30) + assertThat(view.days[2].isToday).isTrue() + assertThat(view.days.drop(3).all { it.above == null && it.below == null }).isTrue() + // the labels are the cycle's days + assertThat(view.days.map { it.label }).isEqualTo((1..30).toList()) + assertThat(view.dayN).isEqualTo(3) + assertThat(view.goal).isEqualTo(20) + assertThat(view.juz).isEqualTo(2) + // juz 1 is read; juz 2 has its first 19 pages read + assertThat(view.line.juz[0].read).isEqualTo(view.line.juz[0].pages) + assertThat(view.line.juz[1].read).isEqualTo(41 - view.line.juz[1].firstPage) + assertThat(view.line.position).isGreaterThan(1f) + assertThat(view.hasHistory).isTrue() + } + + @Test + fun anUnplacedBookmarkHasNoPlaceAndNoHistory() { + val progress = calculator.bookmark( + EmptyReadingBookmark(ReadingBookmarkType.GREEN, Instant.fromEpochMilliseconds(0), "Friday"), + teal.copy(slot = ReadingBookmarkType.GREEN, targetDays = 0), emptyList(), emptyList(), today, + ) + val state = map(progress) + val view = state.bookmarks.single() + assertThat(view.name).isEqualTo("Friday") + assertThat(view.placed).isFalse() + assertThat(view.hasHistory).isFalse() + assertThat(state.canAddBookmark).isTrue() + } + + @Test + fun aDayWithoutSessionsIsEmpty() { + val state = map() + assertThat(state.salah.days).hasSize(30) + assertThat(state.salah.days.all { it.empty }).isTrue() + assertThat(state.memorizing.hasHistory).isFalse() + } + + @Test + fun widthClassesFollowMaterial() { + assertThat(widthClassOf(411.dp)).isEqualTo(WidthClass.Compact) + assertThat(widthClassOf(700.dp)).isEqualTo(WidthClass.Medium) + assertThat(widthClassOf(920.dp)).isEqualTo(WidthClass.Expanded) + assertThat(widthClassOf(1400.dp)).isEqualTo(WidthClass.Expanded) + } +} diff --git a/feature/progress/src/test/kotlin/com/quran/mobile/feature/progress/ui/ProgressScreenRenderTest.kt b/feature/progress/src/test/kotlin/com/quran/mobile/feature/progress/ui/ProgressScreenRenderTest.kt new file mode 100644 index 0000000000..ed3e4fa663 --- /dev/null +++ b/feature/progress/src/test/kotlin/com/quran/mobile/feature/progress/ui/ProgressScreenRenderTest.kt @@ -0,0 +1,134 @@ +package com.quran.mobile.feature.progress.ui + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.os.Looper +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.unit.LayoutDirection +import com.quran.data.model.bookmark.ReadingBookmarkType +import com.quran.labs.androidquran.common.ui.core.QuranTheme +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import java.io.File +import java.time.Duration +import java.util.Locale +import java.util.TimeZone + +/** + * Draws Progress to PNG files (build/outputs/progress-renders) to look at without a device: the + * Huawei MatePad 12 X (2800×1840 at xhdpi) in landscape and portrait, a medium window and a phone; + * English and Arabic; day and night. Only with -Pprogress.render. + */ +@Config(sdk = [34]) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@RunWith(RobolectricTestRunner::class) +class ProgressScreenRenderTest { + + private val output = File("build/outputs/progress-renders").apply { mkdirs() } + private val zone = TimeZone.getTimeZone("UTC") + + @Before + fun onlyWhenAsked() { + assumeTrue(System.getProperty("progress.render") != null) + TimeZone.setDefault(zone) + } + + @Test + fun `the bookmarks`() { + eachLook("bookmarks", ProgressSelection(ProgressSection.BOOKMARKS)) + } + + @Test + fun `a bookmark`() { + eachLook("bookmark", ProgressSelection(ProgressSection.BOOKMARKS, bookmark = ReadingBookmarkType.TEAL), wide = false) + } + + @Test + fun `a bookmark with no history yet`() { + eachLook("bookmark_new", ProgressSelection(ProgressSection.BOOKMARKS, bookmark = ReadingBookmarkType.RED)) + } + + @Test + fun `a bookmark not placed yet`() { + eachLook("bookmark_unplaced", ProgressSelection(ProgressSection.BOOKMARKS, bookmark = ReadingBookmarkType.GREEN)) + } + + @Test + fun `the memorizing`() { + eachLook("memorizing", ProgressSelection(ProgressSection.MEMORIZING)) + } + + @Test + fun `the salah`() { + eachLook("salah", ProgressSelection(ProgressSection.SALAH)) + } + + @Test + fun `the sessions`() { + eachLook("sessions", ProgressSelection(ProgressSection.SESSIONS, session = "s1")) + } + + // -------------------------------------------------------------------------------- rendering + + /** [selection] in light and dark, English and Arabic, on each device ([wide]: on the wide ones too). */ + private fun eachLook(name: String, selection: ProgressSelection, wide: Boolean = true) { + val devices = listOfNotNull( + Triple("phone", "w411dp-h891dp", "xxhdpi"), + Triple("phone_landscape", "w891dp-h411dp", "xxhdpi"), + Triple("small_phone", "w360dp-h640dp", "xhdpi"), + Triple("small_tablet", "w715dp-h1198dp", "mdpi").takeIf { wide }, + Triple("matepad_landscape", "w1400dp-h920dp", "xhdpi").takeIf { wide }, + Triple("matepad_portrait", "w920dp-h1400dp", "xhdpi").takeIf { wide }, + Triple("medium", "w700dp-h1000dp", "mdpi").takeIf { wide }, + ) + for ((device, size, density) in devices) { + for (arabic in listOf(false, true)) { + for (dark in listOf(false, true)) { + val qualifiers = listOf(if (arabic) "ar" else "en", size, if (dark) "night" else "notnight", density).joinToString("-") + render("${name}_${device}_${if (arabic) "ar" else "en"}_${if (dark) "dark" else "light"}", qualifiers, dark, arabic) { + ProgressScreen(SampleStates.state(arabic), selection, ProgressActions(), dark) + } + } + } + } + } + + private fun render(file: String, qualifiers: String, dark: Boolean, rtl: Boolean, content: @Composable () -> Unit) { + RuntimeEnvironment.setQualifiers(qualifiers) + // as on a device with the app in that language: dates and numbers follow it + Locale.setDefault(if (rtl) Locale.forLanguageTag("ar-EG") else Locale.US) + val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup() + val activity = controller.get() + activity.actionBar?.hide() + activity.setContent { + CompositionLocalProvider(LocalLayoutDirection provides if (rtl) LayoutDirection.Rtl else LayoutDirection.Ltr) { + QuranTheme(useDarkTheme = dark) { + Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surface)) { content() } + } + } + } + repeat(3) { shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100)) } + val view = activity.window.decorView + val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888) + view.draw(Canvas(bitmap)) + File(output, "$file.png").outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } + controller.pause().stop().destroy() + } +} diff --git a/feature/recitation/src/main/java/com/quran/mobile/recitation/presenter/RecitationPresenterImpl.kt b/feature/recitation/src/main/java/com/quran/mobile/recitation/presenter/RecitationPresenterImpl.kt index ba43a9ecb7..81750a7490 100644 --- a/feature/recitation/src/main/java/com/quran/mobile/recitation/presenter/RecitationPresenterImpl.kt +++ b/feature/recitation/src/main/java/com/quran/mobile/recitation/presenter/RecitationPresenterImpl.kt @@ -4,6 +4,7 @@ import android.app.Activity import com.quran.data.di.QuranScope import com.quran.data.model.SuraAyah import com.quran.recitation.presenter.RecitationPresenter +import com.quran.recitation.presenter.RecitationStart import dev.zacsweers.metro.Inject import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -17,6 +18,6 @@ class RecitationPresenterImpl @Inject constructor(): RecitationPresenter { override fun isRecitationEnabledFlow(): StateFlow = MutableStateFlow(false) override fun onRequestPermissionsResult(requestCode: Int, grantResults: IntArray) {} - override fun startOrStopRecitation(startAyah: () -> SuraAyah, showModeSelection: Boolean) {} + override fun startOrStopRecitation(startAyah: () -> SuraAyah, start: RecitationStart) {} override fun endSession() {} } diff --git a/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/AccountSettingsRow.kt b/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/AccountSettingsRow.kt index 2598f2b1ee..c47aed15a3 100644 --- a/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/AccountSettingsRow.kt +++ b/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/AccountSettingsRow.kt @@ -24,7 +24,6 @@ import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.quran.labs.androidquran.common.ui.core.QuranIcons import com.quran.labs.androidquran.common.ui.core.QuranTheme -import com.quran.labs.androidquran.common.ui.core.modifier.autoMirror import com.quran.mobile.feature.sync.state.AccountSettingsEvent import com.quran.mobile.feature.sync.state.AccountSettingsState @@ -103,8 +102,7 @@ private fun SignInPromptRow(onClick: () -> Unit, modifier: Modifier = Modifier) Icon( imageVector = QuranIcons.ChevronRight, contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.autoMirror() + tint = MaterialTheme.colorScheme.onSurfaceVariant ) } } diff --git a/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/AccountSyncScreen.kt b/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/AccountSyncScreen.kt index 9a3b30aa47..d71b0b7801 100644 --- a/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/AccountSyncScreen.kt +++ b/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/AccountSyncScreen.kt @@ -49,7 +49,6 @@ import androidx.compose.ui.unit.dp import com.quran.labs.androidquran.common.ui.core.LocalQuranColors import com.quran.labs.androidquran.common.ui.core.QuranIcons import com.quran.labs.androidquran.common.ui.core.QuranTheme -import com.quran.labs.androidquran.common.ui.core.modifier.autoMirror import com.quran.mobile.feature.sync.state.AccountProfile import com.quran.mobile.feature.sync.state.AccountSyncEvent import com.quran.mobile.feature.sync.state.AccountSyncState @@ -106,8 +105,7 @@ internal fun AccountSyncScreen( IconButton(onClick = onBackPressed) { Icon( imageVector = QuranIcons.ArrowBack, - contentDescription = stringResource(AppCompatR.string.abc_action_bar_up_description), - modifier = Modifier.autoMirror() + contentDescription = stringResource(AppCompatR.string.abc_action_bar_up_description) ) } } diff --git a/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/QuranSyncScreen.kt b/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/QuranSyncScreen.kt index bc5a8672dd..a6a5f01f86 100644 --- a/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/QuranSyncScreen.kt +++ b/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/QuranSyncScreen.kt @@ -42,7 +42,6 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.quran.labs.androidquran.common.ui.core.QuranIcons -import com.quran.labs.androidquran.common.ui.core.modifier.autoMirror import com.quran.shared.auth.model.AuthState import kotlinx.coroutines.launch @@ -70,8 +69,7 @@ internal fun QuranSyncScreen( IconButton(onClick = onBackPressed) { Icon( imageVector = QuranIcons.ArrowBack, - contentDescription = "", - modifier = Modifier.autoMirror() + contentDescription = "" ) } } diff --git a/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/SyncAccountCard.kt b/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/SyncAccountCard.kt index 4166261944..a9acb9f421 100644 --- a/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/SyncAccountCard.kt +++ b/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/SyncAccountCard.kt @@ -40,7 +40,6 @@ import coil3.compose.AsyncImage import com.quran.labs.androidquran.common.ui.core.LocalQuranColors import com.quran.labs.androidquran.common.ui.core.QuranIcons import com.quran.labs.androidquran.common.ui.core.QuranTheme -import com.quran.labs.androidquran.common.ui.core.modifier.autoMirror import com.quran.mobile.feature.sync.state.AccountProfile import com.quran.mobile.feature.sync.state.SyncActivityState import com.quran.mobile.feature.sync.state.SyncActivityState.Status @@ -119,8 +118,7 @@ private fun ProfileRow(profile: AccountProfile, onClick: () -> Unit) { Icon( imageVector = QuranIcons.ChevronRight, contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.autoMirror() + tint = MaterialTheme.colorScheme.onSurfaceVariant ) } } @@ -262,9 +260,7 @@ private fun ReviewHeldItemsRow(onClick: () -> Unit) { imageVector = QuranIcons.ChevronRight, contentDescription = null, tint = caution, - modifier = Modifier - .autoMirror() - .size(20.dp) + modifier = Modifier.size(20.dp) ) } } diff --git a/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/SyncActivityScreen.kt b/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/SyncActivityScreen.kt index 1d1887102b..7f222a41cc 100644 --- a/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/SyncActivityScreen.kt +++ b/feature/sync/src/main/kotlin/com/quran/mobile/feature/sync/SyncActivityScreen.kt @@ -21,7 +21,6 @@ import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.quran.labs.androidquran.common.ui.core.QuranIcons import com.quran.labs.androidquran.common.ui.core.QuranTheme -import com.quran.labs.androidquran.common.ui.core.modifier.autoMirror import com.quran.mobile.feature.sync.state.HeldItemRowState import com.quran.mobile.feature.sync.state.SyncActivityState import kotlinx.collections.immutable.ImmutableList @@ -51,8 +50,7 @@ internal fun SyncActivityScreen( IconButton(onClick = onBackPressed) { Icon( imageVector = QuranIcons.ArrowBack, - contentDescription = stringResource(AppCompatR.string.abc_action_bar_up_description), - modifier = Modifier.autoMirror() + contentDescription = stringResource(AppCompatR.string.abc_action_bar_up_description) ) } } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 1f3e034b9c..2d04b14eb5 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,4 +1,6 @@ [versions] +androidxTestRunner = "1.7.0" +sherpaOnnx = "1.13.8" agp = "9.5.1" junit = "1.3.0" kotlin = "2.4.21" @@ -75,6 +77,8 @@ turbineVersion = "1.2.1" koverVersion = "0.9.11" [libraries] +androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidxTestRunner" } +sherpa-onnx = { module = "com.k2fsa.sherpa.onnx:sherpa-onnx", version.ref = "sherpaOnnx" } androidx-junit = { module = "androidx.test.ext:junit", version.ref = "junit" } androidx-media3-exoplayer = { module = "androidx.media3:media3-exoplayer", version.ref = "media3ExoplayerVersion" } androidx-media3-session = { module = "androidx.media3:media3-session", version.ref = "media3ExoplayerVersion" } diff --git a/pages/data/madani/src/main/kotlin/com/quran/labs/androidquran/pages/data/madani/Madani1440DataSource.kt b/pages/data/madani/src/main/kotlin/com/quran/labs/androidquran/pages/data/madani/Madani1440DataSource.kt new file mode 100644 index 0000000000..dc6cdea905 --- /dev/null +++ b/pages/data/madani/src/main/kotlin/com/quran/labs/androidquran/pages/data/madani/Madani1440DataSource.kt @@ -0,0 +1,141 @@ +package com.quran.labs.androidquran.pages.data.madani + +/** + * The pages of the King Fahd Complex's newer Madani prints (the 1421, 1439, 1440 and 1441 + * editions share them): the same 604 pages as the 1405 print, but 25 of them begin at another ayah. + * Made from the editions' public ayahinfo databases (quran-asr-lab bench/page_tables.py). + */ +open class Madani1440DataSource : MadaniDataSource() { + + override val suraForPageArray = intArrayOf( + /* 1 - 15 */ 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + /* 16 - 30 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + /* 31 - 45 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + /* 46 - 60 */ 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + /* 61 - 75 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + /* 76 - 90 */ 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + /* 91 - 105 */ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + /* 106 - 120 */ 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + /* 121 - 135 */ 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, + /* 136 - 150 */ 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + /* 151 - 165 */ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + /* 166 - 180 */ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, + /* 181 - 195 */ 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, + /* 196 - 210 */ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, + /* 211 - 225 */ 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, + /* 226 - 240 */ 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, + /* 241 - 255 */ 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, + /* 256 - 270 */ 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, + /* 271 - 285 */ 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, + /* 286 - 300 */ 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, + /* 301 - 315 */ 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, + /* 316 - 330 */ 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, + /* 331 - 345 */ 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, + /* 346 - 360 */ 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, + /* 361 - 375 */ 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, + /* 376 - 390 */ 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, + /* 391 - 405 */ 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 30, + /* 406 - 420 */ 30, 30, 30, 30, 30, 31, 31, 31, 31, 32, 32, 32, 33, 33, 33, + /* 421 - 435 */ 33, 33, 33, 33, 33, 33, 33, 34, 34, 34, 34, 34, 34, 34, 35, + /* 436 - 450 */ 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 37, 37, 37, 37, 37, + /* 451 - 465 */ 37, 37, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, + /* 466 - 480 */ 39, 39, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41, + /* 481 - 495 */ 41, 41, 42, 42, 42, 42, 42, 42, 42, 43, 43, 43, 43, 43, 43, + /* 496 - 510 */ 44, 44, 44, 45, 45, 45, 45, 46, 46, 46, 46, 47, 47, 47, 47, + /* 511 - 525 */ 48, 48, 48, 48, 48, 49, 49, 50, 50, 50, 51, 51, 51, 52, 52, + /* 526 - 540 */ 53, 53, 53, 54, 54, 54, 55, 55, 55, 56, 56, 56, 57, 57, 57, + /* 541 - 555 */ 57, 58, 58, 58, 58, 59, 59, 59, 60, 60, 60, 61, 62, 62, 63, + /* 556 - 570 */ 64, 64, 65, 65, 66, 66, 67, 67, 67, 68, 68, 69, 69, 70, 70, + /* 571 - 585 */ 71, 72, 72, 73, 73, 74, 74, 75, 76, 76, 77, 78, 78, 79, 80, + /* 586 - 600 */ 80, 82, 83, 83, 84, 86, 87, 88, 89, 90, 92, 94, 96, 98, 100, + /* 601 - 604 */ 103, 106, 109, 112 + ) + + override val ayahForPageArray = intArrayOf( + /* 1 - 15 */ 1, 1, 6, 17, 25, 30, 38, 49, 58, 62, 70, 77, 84, 89, 94, + /* 16 - 30 */ 102, 106, 113, 120, 127, 135, 142, 146, 154, 164, 170, 177, 182, 187, 191, + /* 31 - 45 */ 197, 203, 211, 216, 220, 225, 231, 234, 238, 246, 249, 253, 257, 260, 265, + /* 46 - 60 */ 270, 275, 282, 283, 1, 10, 16, 23, 30, 38, 46, 53, 62, 71, 78, + /* 61 - 75 */ 84, 92, 101, 109, 116, 122, 133, 141, 149, 154, 158, 166, 174, 181, 187, + /* 76 - 90 */ 195, 1, 7, 12, 15, 20, 24, 27, 34, 38, 45, 52, 60, 66, 75, + /* 91 - 105 */ 80, 87, 92, 95, 102, 106, 114, 122, 128, 135, 141, 148, 155, 163, 171, + /* 106 - 120 */ 176, 3, 6, 10, 14, 18, 24, 32, 37, 42, 46, 51, 58, 65, 71, + /* 121 - 135 */ 78, 84, 91, 96, 104, 109, 114, 1, 9, 19, 28, 36, 45, 53, 60, + /* 136 - 150 */ 69, 74, 82, 91, 95, 102, 111, 119, 125, 131, 138, 143, 147, 152, 158, + /* 151 - 165 */ 1, 12, 23, 31, 38, 44, 52, 58, 68, 74, 82, 88, 96, 105, 121, + /* 166 - 180 */ 131, 138, 144, 150, 156, 160, 164, 171, 179, 188, 196, 1, 9, 17, 26, + /* 181 - 195 */ 34, 41, 46, 53, 62, 70, 1, 7, 14, 21, 27, 32, 37, 41, 48, + /* 196 - 210 */ 55, 62, 69, 73, 80, 87, 94, 100, 107, 112, 118, 123, 1, 7, 15, + /* 211 - 225 */ 21, 26, 34, 43, 54, 62, 71, 79, 89, 98, 107, 6, 13, 20, 29, + /* 226 - 240 */ 38, 46, 54, 63, 72, 82, 89, 98, 109, 118, 5, 15, 23, 31, 38, + /* 241 - 255 */ 44, 53, 64, 70, 79, 87, 96, 104, 1, 6, 14, 19, 29, 35, 43, + /* 256 - 270 */ 6, 11, 19, 25, 34, 43, 1, 16, 32, 52, 71, 91, 7, 15, 27, + /* 271 - 285 */ 35, 43, 55, 65, 73, 80, 88, 94, 103, 111, 119, 1, 8, 18, 28, + /* 286 - 300 */ 39, 50, 59, 67, 76, 87, 97, 105, 5, 16, 21, 28, 35, 46, 54, + /* 301 - 315 */ 62, 75, 84, 98, 1, 12, 26, 39, 52, 65, 77, 96, 13, 38, 52, + /* 316 - 330 */ 65, 77, 88, 99, 114, 126, 1, 11, 25, 36, 45, 58, 73, 82, 91, + /* 331 - 345 */ 102, 1, 6, 16, 24, 31, 39, 47, 56, 65, 73, 1, 18, 28, 43, + /* 346 - 360 */ 60, 75, 90, 105, 1, 11, 21, 28, 32, 37, 44, 54, 59, 62, 3, + /* 361 - 375 */ 12, 21, 33, 44, 56, 68, 1, 20, 40, 61, 84, 112, 137, 160, 184, + /* 376 - 390 */ 207, 1, 14, 23, 36, 45, 56, 64, 77, 89, 6, 14, 22, 29, 36, + /* 391 - 405 */ 44, 51, 60, 71, 78, 85, 7, 15, 24, 31, 39, 46, 53, 64, 6, + /* 406 - 420 */ 16, 25, 33, 42, 51, 1, 12, 20, 29, 1, 12, 21, 1, 7, 16, + /* 421 - 435 */ 23, 31, 36, 44, 51, 55, 63, 1, 8, 15, 23, 32, 40, 49, 4, + /* 436 - 450 */ 12, 19, 31, 39, 45, 13, 28, 41, 55, 71, 1, 25, 52, 77, 103, + /* 451 - 465 */ 127, 154, 1, 17, 27, 43, 62, 84, 6, 11, 22, 32, 41, 48, 57, + /* 466 - 480 */ 68, 75, 8, 17, 26, 34, 41, 50, 59, 67, 78, 1, 12, 21, 30, + /* 481 - 495 */ 39, 47, 1, 11, 16, 23, 32, 45, 52, 11, 23, 34, 48, 61, 74, + /* 496 - 510 */ 1, 19, 40, 1, 14, 23, 33, 6, 15, 21, 29, 1, 12, 20, 30, + /* 511 - 525 */ 1, 10, 16, 24, 29, 5, 12, 1, 16, 36, 7, 31, 52, 15, 32, + /* 526 - 540 */ 1, 27, 45, 7, 28, 50, 19, 42, 70, 17, 51, 77, 4, 12, 19, + /* 541 - 555 */ 25, 1, 7, 12, 22, 4, 10, 17, 1, 6, 12, 6, 1, 9, 5, + /* 556 - 570 */ 1, 10, 1, 6, 1, 8, 1, 13, 27, 17, 43, 9, 36, 11, 41, + /* 571 - 585 */ 11, 1, 14, 1, 20, 19, 48, 20, 6, 26, 20, 1, 31, 17, 1, + /* 586 - 600 */ 41, 1, 5, 34, 25, 1, 11, 23, 23, 19, 10, 3, 13, 6, 6, + /* 601 - 604 */ 1, 1, 1, 1 + ) + + override val quarterStartByPage = intArrayOf( + /* 1 - 15 */ -1, -1, -1, -1, 1, -1, 2, -1, 3, -1, 4, -1, -1, 5, -1, + /* 16 - 30 */ -1, 6, -1, 7, -1, -1, 8, -1, 9, -1, -1, 10, -1, 11, -1, + /* 31 - 45 */ -1, 12, -1, 13, -1, -1, 14, -1, 15, -1, -1, 16, -1, 17, -1, + /* 46 - 60 */ 18, -1, -1, 19, -1, 20, -1, -1, 21, -1, 22, -1, -1, 23, -1, + /* 61 - 75 */ -1, 24, -1, 25, -1, -1, 26, -1, 27, -1, -1, 28, -1, 29, -1, + /* 76 - 90 */ -1, 30, -1, 31, -1, -1, 32, -1, 33, -1, -1, 34, -1, 35, -1, + /* 91 - 105 */ -1, 36, -1, 37, -1, -1, 38, -1, -1, 39, -1, 40, -1, 41, -1, + /* 106 - 120 */ 42, -1, -1, 43, -1, -1, 44, -1, 45, -1, -1, 46, -1, 47, -1, + /* 121 - 135 */ 48, -1, -1, 49, -1, 50, -1, -1, 51, -1, -1, 52, -1, 53, -1, + /* 136 - 150 */ -1, 54, -1, -1, 55, -1, 56, -1, 57, -1, 58, -1, 59, -1, -1, + /* 151 - 165 */ 60, -1, -1, 61, -1, 62, -1, 63, -1, -1, -1, 64, -1, 65, -1, + /* 166 - 180 */ -1, 66, -1, -1, 67, -1, -1, 68, -1, 69, -1, 70, -1, 71, -1, + /* 181 - 195 */ -1, 72, -1, 73, -1, -1, 74, -1, 75, -1, -1, 76, -1, 77, -1, + /* 196 - 210 */ 78, -1, -1, 79, -1, 80, -1, -1, 81, -1, 82, -1, -1, 83, -1, + /* 211 - 225 */ -1, 84, -1, 85, -1, -1, 86, -1, 87, -1, -1, 88, -1, 89, -1, + /* 226 - 240 */ 90, -1, 91, -1, -1, 92, -1, 93, -1, -1, 94, -1, 95, -1, -1, + /* 241 - 255 */ -1, 96, -1, 97, -1, -1, 98, -1, 99, -1, -1, 100, -1, 101, -1, + /* 256 - 270 */ 102, -1, -1, 103, -1, -1, 104, -1, 105, -1, -1, 106, -1, -1, 107, + /* 271 - 285 */ -1, 108, -1, -1, 109, -1, 110, -1, -1, 111, -1, 112, -1, 113, -1, + /* 286 - 300 */ -1, 114, -1, 115, -1, -1, 116, -1, -1, 117, -1, 118, -1, 119, -1, + /* 301 - 315 */ -1, 120, -1, 121, -1, 122, -1, -1, 123, -1, -1, 124, -1, -1, 125, + /* 316 - 330 */ -1, 126, -1, 127, -1, -1, 128, -1, 129, -1, 130, -1, -1, 131, -1, + /* 331 - 345 */ -1, 132, -1, 133, -1, 134, -1, -1, 135, -1, -1, 136, -1, 137, -1, + /* 346 - 360 */ -1, 138, -1, -1, 139, -1, 140, -1, 141, -1, 142, -1, -1, 143, -1, + /* 361 - 375 */ -1, 144, -1, 145, -1, -1, 146, -1, 147, -1, 148, -1, -1, 149, -1, + /* 376 - 390 */ -1, 150, -1, 151, -1, -1, 152, -1, 153, -1, 154, -1, -1, 155, -1, + /* 391 - 405 */ -1, 156, -1, 157, -1, 158, -1, -1, 159, -1, -1, 160, -1, 161, -1, + /* 406 - 420 */ -1, 162, -1, -1, 163, -1, -1, 164, -1, 165, -1, -1, 166, -1, 167, + /* 421 - 435 */ -1, 168, -1, -1, 169, 170, -1, -1, 171, -1, 172, -1, 173, -1, -1, + /* 436 - 450 */ 174, -1, -1, 175, -1, -1, 176, -1, 177, -1, 178, -1, -1, 179, -1, + /* 451 - 465 */ 180, -1, -1, 181, -1, 182, -1, -1, 183, -1, -1, 184, -1, 185, -1, + /* 466 - 480 */ -1, 186, -1, 187, -1, -1, 188, -1, 189, -1, -1, 190, -1, 191, -1, + /* 481 - 495 */ -1, 192, -1, 193, -1, 194, -1, 195, -1, -1, 196, -1, 197, -1, -1, + /* 496 - 510 */ 198, -1, -1, 199, -1, -1, 200, -1, -1, 201, -1, 202, -1, -1, 203, + /* 511 - 525 */ -1, -1, 204, -1, 205, -1, 206, -1, 207, -1, -1, 208, -1, 209, -1, + /* 526 - 540 */ 210, -1, -1, 211, -1, 212, -1, -1, 213, -1, 214, -1, -1, 215, -1, + /* 541 - 555 */ -1, 216, -1, 217, -1, -1, 218, -1, -1, 219, -1, -1, 220, 221, -1, + /* 556 - 570 */ -1, -1, 222, -1, 223, -1, 224, -1, 225, -1, 226, -1, -1, 227, -1, + /* 571 - 585 */ -1, 228, -1, -1, 229, -1, 230, -1, 231, -1, -1, 232, -1, -1, 233, + /* 586 - 600 */ -1, 234, -1, 235, -1, 236, -1, -1, 237, -1, 238, -1, -1, -1, 239, + /* 601 - 604 */ -1, -1, -1, -1 + ) +} diff --git a/pages/data/madani/src/main/kotlin/com/quran/labs/androidquran/pages/data/shemerly/ShemerlyDataSource.kt b/pages/data/madani/src/main/kotlin/com/quran/labs/androidquran/pages/data/shemerly/ShemerlyDataSource.kt new file mode 100644 index 0000000000..252a39288a --- /dev/null +++ b/pages/data/madani/src/main/kotlin/com/quran/labs/androidquran/pages/data/shemerly/ShemerlyDataSource.kt @@ -0,0 +1,145 @@ +package com.quran.labs.androidquran.pages.data.shemerly + +import com.quran.labs.androidquran.pages.data.madani.MadaniDataSource + +/** + * The pages of the Shemerly print (popular in Egypt): 521 pages, with ayat that run on to the next + * page. A page's first ayah is the first one with any part on it, and an ayah's page is the one it + * begins on. Made from the edition's public ayahinfo database (quran-asr-lab bench/page_tables.py). + */ +class ShemerlyDataSource : MadaniDataSource() { + + override val numberOfPages = 521 + + override val pageForSuraArray = intArrayOf( + /* 1 - 15 */ 1, 2, 41, 63, 86, 104, 122, 144, 152, 168, 180, 192, 204, 209, 215, + /* 16 - 30 */ 220, 232, 242, 252, 259, 267, 275, 283, 290, 299, 305, 314, 322, 331, 337, + /* 31 - 45 */ 343, 346, 349, 357, 363, 368, 373, 379, 384, 391, 399, 404, 410, 416, 418, + /* 46 - 60 */ 422, 426, 429, 433, 436, 438, 441, 443, 446, 448, 451, 454, 458, 461, 464, + /* 61 - 75 */ 467, 468, 470, 471, 473, 475, 477, 479, 481, 483, 485, 487, 489, 490, 492, + /* 76 - 90 */ 494, 496, 497, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, + /* 91 - 105 */ 511, 511, 512, 513, 513, 513, 514, 515, 515, 516, 516, 517, 517, 518, 518, + /* 106 - 114 */ 519, 519, 519, 520, 520, 520, 521, 521, 521 + ) + + override val suraForPageArray = intArrayOf( + /* 1 - 15 */ 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + /* 16 - 30 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + /* 31 - 45 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, + /* 46 - 60 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + /* 61 - 75 */ 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + /* 76 - 90 */ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, + /* 91 - 105 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, + /* 106 - 120 */ 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + /* 121 - 135 */ 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + /* 136 - 150 */ 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, + /* 151 - 165 */ 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + /* 166 - 180 */ 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + /* 181 - 195 */ 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, + /* 196 - 210 */ 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, + /* 211 - 225 */ 14, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, + /* 226 - 240 */ 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, + /* 241 - 255 */ 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, + /* 256 - 270 */ 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, + /* 271 - 285 */ 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, + /* 286 - 300 */ 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, + /* 301 - 315 */ 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, + /* 316 - 330 */ 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, + /* 331 - 345 */ 29, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 31, 31, 31, + /* 346 - 360 */ 31, 32, 32, 33, 33, 33, 33, 33, 33, 33, 33, 33, 34, 34, 34, + /* 361 - 375 */ 34, 34, 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 37, 37, 37, + /* 376 - 390 */ 37, 37, 37, 37, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, + /* 391 - 405 */ 39, 40, 40, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 42, + /* 406 - 420 */ 42, 42, 42, 42, 42, 43, 43, 43, 43, 43, 44, 44, 44, 45, 45, + /* 421 - 435 */ 45, 46, 46, 46, 46, 47, 47, 47, 47, 48, 48, 48, 48, 49, 49, + /* 436 - 450 */ 49, 50, 50, 51, 51, 51, 52, 52, 53, 53, 53, 54, 54, 55, 55, + /* 451 - 465 */ 55, 56, 56, 56, 57, 57, 57, 57, 58, 58, 58, 59, 59, 59, 60, + /* 466 - 480 */ 60, 61, 61, 62, 63, 63, 64, 64, 65, 65, 66, 67, 67, 67, 68, + /* 481 - 495 */ 68, 69, 69, 70, 70, 71, 71, 72, 73, 73, 74, 74, 75, 76, 76, + /* 496 - 510 */ 77, 77, 78, 79, 79, 80, 81, 82, 83, 84, 85, 86, 87, 89, 89, + /* 511 - 521 */ 91, 92, 94, 96, 98, 99, 101, 104, 106, 109, 112 + ) + + override val ayahForPageArray = intArrayOf( + /* 1 - 15 */ 1, 1, 5, 16, 24, 30, 39, 50, 60, 65, 75, 83, 90, 98, 105, + /* 16 - 30 */ 113, 122, 130, 139, 145, 154, 164, 173, 179, 187, 193, 199, 210, 217, 221, + /* 31 - 45 */ 229, 233, 238, 247, 251, 257, 262, 267, 275, 282, 285, 7, 14, 23, 31, + /* 46 - 60 */ 41, 50, 61, 72, 80, 89, 99, 109, 117, 126, 139, 149, 154, 163, 172, + /* 61 - 75 */ 181, 189, 198, 4, 11, 16, 23, 27, 35, 43, 51, 60, 69, 77, 84, + /* 76 - 90 */ 91, 95, 102, 111, 120, 129, 137, 145, 154, 163, 172, 2, 5, 11, 16, + /* 91 - 105 */ 23, 32, 41, 46, 52, 60, 67, 75, 83, 92, 99, 106, 113, 1, 9, + /* 106 - 120 */ 20, 31, 40, 51, 59, 70, 78, 89, 94, 103, 113, 122, 130, 139, 145, + /* 121 - 135 */ 152, 159, 3, 18, 28, 37, 43, 52, 60, 71, 81, 89, 101, 117, 131, + /* 136 - 150 */ 140, 146, 155, 160, 167, 176, 186, 195, 1, 11, 21, 32, 41, 48, 59, + /* 151 - 165 */ 67, 75, 7, 17, 24, 32, 38, 46, 55, 64, 71, 79, 87, 95, 103, + /* 166 - 180 */ 111, 118, 125, 3, 12, 20, 26, 35, 45, 58, 68, 76, 88, 98, 108, + /* 181 - 195 */ 7, 17, 26, 36, 45, 56, 65, 77, 87, 96, 109, 120, 6, 18, 26, + /* 196 - 210 */ 36, 43, 52, 64, 73, 82, 93, 103, 1, 7, 16, 23, 31, 39, 4, + /* 211 - 225 */ 10, 21, 28, 39, 51, 14, 32, 54, 77, 1, 12, 25, 34, 44, 58, + /* 226 - 240 */ 68, 76, 85, 93, 104, 115, 126, 7, 17, 28, 40, 52, 61, 71, 83, + /* 241 - 255 */ 96, 106, 6, 17, 24, 32, 44, 53, 62, 77, 88, 102, 4, 20, 35, + /* 256 - 270 */ 49, 63, 76, 98, 17, 40, 58, 72, 86, 97, 114, 128, 2, 17, 31, + /* 271 - 285 */ 44, 59, 75, 87, 102, 2, 11, 20, 30, 40, 51, 62, 73, 5, 22, + /* 286 - 300 */ 34, 51, 71, 88, 106, 2, 12, 22, 31, 35, 43, 53, 59, 63, 6, + /* 301 - 315 */ 18, 32, 45, 59, 73, 12, 34, 56, 83, 112, 139, 165, 190, 217, 7, + /* 316 - 330 */ 18, 32, 42, 55, 65, 82, 1, 10, 19, 29, 38, 47, 58, 70, 79, + /* 331 - 345 */ 1, 11, 22, 32, 42, 52, 64, 8, 20, 29, 40, 50, 1, 14, 22, + /* 346 - 360 */ 33, 8, 20, 1, 9, 19, 27, 35, 43, 51, 57, 69, 3, 13, 22, + /* 361 - 375 */ 33, 43, 1, 8, 14, 28, 39, 1, 15, 34, 49, 67, 1, 22, 51, + /* 376 - 390 */ 81, 110, 141, 172, 9, 24, 38, 59, 79, 5, 13, 23, 37, 46, 58, + /* 391 - 405 */ 71, 4, 13, 25, 34, 45, 57, 67, 81, 6, 16, 28, 39, 47, 3, + /* 406 - 420 */ 13, 20, 29, 42, 51, 12, 25, 39, 55, 71, 1, 20, 45, 5, 17, + /* 421 - 435 */ 27, 1, 11, 18, 27, 1, 10, 18, 31, 2, 11, 18, 27, 2, 11, + /* 436 - 450 */ 17, 14, 34, 7, 33, 54, 17, 37, 6, 30, 56, 14, 37, 5, 33, + /* 451 - 465 */ 61, 9, 47, 75, 3, 12, 19, 26, 3, 9, 19, 2, 10, 19, 1, + /* 466 - 480 */ 9, 1, 10, 3, 1, 9, 7, 17, 4, 12, 6, 1, 12, 26, 16, + /* 481 - 495 */ 41, 6, 31, 4, 37, 7, 28, 13, 1, 19, 13, 43, 12, 1, 19, + /* 496 - 510 */ 1, 36, 14, 1, 35, 18, 9, 8, 15, 4, 4, 4, 16, 1, 24, + /* 511 - 521 */ 1, 10, 1, 3, 1, 6, 5, 1, 1, 1, 1 + ) + + override val pageForJuzArray = intArrayOf( + /* 1 - 15 */ 1, 19, 35, 51, 67, 83, 98, 115, 131, 147, 163, 180, 198, 215, 232, + /* 16 - 30 */ 249, 267, 283, 301, 319, 335, 352, 369, 387, 403, 422, 439, 458, 477, 497 + ) + + override val quarterStartByPage = intArrayOf( + /* 1 - 15 */ -1, -1, -1, -1, 1, -1, 2, -1, 3, -1, 4, -1, 5, -1, 6, + /* 16 - 30 */ -1, 7, -1, 8, -1, 9, -1, 10, -1, 11, -1, 12, -1, 13, -1, + /* 31 - 45 */ 14, -1, 15, -1, 16, -1, 17, 18, -1, 19, -1, -1, 20, -1, 21, + /* 46 - 60 */ -1, 22, -1, 23, -1, 24, -1, 25, -1, 26, -1, 27, -1, 28, -1, + /* 61 - 75 */ 29, -1, 30, -1, 31, -1, 32, -1, 33, -1, 34, -1, 35, -1, 36, + /* 76 - 90 */ -1, 37, -1, 38, -1, 39, -1, 40, 41, -1, 42, -1, -1, 43, -1, + /* 91 - 105 */ 44, 45, -1, 46, -1, 47, -1, 48, -1, 49, -1, 50, -1, -1, 51, + /* 106 - 120 */ -1, 52, -1, 53, -1, 54, -1, -1, 55, 56, -1, 57, -1, 58, 59, + /* 121 - 135 */ -1, 60, -1, -1, 61, -1, 62, -1, 63, -1, 64, -1, -1, 65, -1, + /* 136 - 150 */ 66, -1, 67, -1, 68, -1, 69, -1, 70, -1, 71, 72, -1, -1, 73, + /* 151 - 165 */ -1, 74, -1, 75, -1, 76, 77, -1, 78, -1, 79, -1, 80, -1, 81, + /* 166 - 180 */ -1, 82, -1, 83, -1, 84, -1, -1, 85, -1, 86, -1, 87, -1, 88, + /* 181 - 195 */ -1, 89, -1, 90, -1, 91, -1, 92, -1, 93, -1, -1, 94, -1, 95, + /* 196 - 210 */ -1, -1, 96, -1, 97, -1, 98, -1, 99, -1, 100, -1, 101, -1, 102, + /* 211 - 225 */ -1, 103, -1, -1, 104, -1, 105, -1, -1, 106, -1, 107, -1, 108, -1, + /* 226 - 240 */ 109, -1, 110, -1, 111, -1, 112, -1, 113, -1, 114, -1, 115, -1, -1, + /* 241 - 255 */ 116, -1, 117, -1, -1, 118, 119, -1, 120, -1, 121, -1, -1, 122, -1, + /* 256 - 270 */ 123, -1, -1, 124, -1, 125, -1, 126, -1, 127, -1, 128, -1, 129, -1, + /* 271 - 285 */ 130, -1, 131, -1, 132, -1, 133, -1, 134, -1, 135, -1, 136, -1, -1, + /* 286 - 300 */ 137, -1, 138, -1, 139, -1, 140, -1, 141, -1, 142, -1, -1, 143, -1, + /* 301 - 315 */ 144, -1, 145, -1, 146, -1, 147, -1, 148, -1, -1, 149, -1, 150, -1, + /* 316 - 330 */ 151, -1, -1, 152, 153, -1, -1, 154, 155, -1, -1, 156, -1, 157, -1, + /* 331 - 345 */ 158, -1, 159, -1, 160, -1, 161, -1, -1, 162, -1, 163, -1, 164, -1, + /* 346 - 360 */ -1, 165, -1, 166, 167, -1, 168, -1, 169, -1, 170, -1, 171, -1, 172, + /* 361 - 375 */ -1, 173, -1, -1, 174, -1, 175, -1, 176, -1, 177, -1, 178, -1, -1, + /* 376 - 390 */ 179, -1, 180, -1, 181, -1, 182, -1, -1, 183, -1, 184, -1, 185, -1, + /* 391 - 405 */ 186, -1, 187, -1, 188, -1, 189, -1, -1, 190, 191, -1, 192, -1, 193, + /* 406 - 420 */ -1, 194, -1, 195, -1, 196, -1, -1, 197, -1, 198, -1, -1, 199, -1, + /* 421 - 435 */ -1, 200, -1, 201, -1, 202, -1, -1, 203, -1, 204, -1, 205, -1, 206, + /* 436 - 450 */ -1, 207, -1, 208, -1, -1, 209, -1, 210, -1, 211, -1, 212, -1, -1, + /* 451 - 465 */ 213, -1, -1, 214, -1, 215, -1, 216, -1, 217, -1, -1, 218, -1, 219, + /* 466 - 480 */ -1, -1, 220, -1, 221, -1, -1, 222, -1, 223, -1, 224, -1, 225, -1, + /* 481 - 495 */ 226, -1, -1, 227, -1, -1, 228, -1, -1, 229, -1, 230, -1, -1, 231, + /* 496 - 510 */ -1, 232, -1, -1, 233, -1, 234, -1, 235, -1, -1, 236, -1, -1, 237, + /* 511 - 521 */ -1, -1, 238, -1, -1, 239, -1, -1, -1, -1, -1 + ) + + override val juzDisplayPageArrayOverride = emptyMap() +} diff --git a/pages/linebyline/build.gradle.kts b/pages/linebyline/build.gradle.kts new file mode 100644 index 0000000000..47d9b8f2f4 --- /dev/null +++ b/pages/linebyline/build.gradle.kts @@ -0,0 +1,14 @@ +plugins { + id("quran.android.library.android") + alias(libs.plugins.metro) +} + +android.namespace = "com.quran.labs.androidquran.pages.linebyline" + +dependencies { + implementation(project(":common:data")) + implementation(project(":common:pages")) + implementation(project(":feature:linebyline")) + + implementation(libs.androidx.fragment.ktx) +} diff --git a/pages/linebyline/src/main/kotlin/com/quran/labs/androidquran/pages/linebyline/LineByLinePages.kt b/pages/linebyline/src/main/kotlin/com/quran/labs/androidquran/pages/linebyline/LineByLinePages.kt new file mode 100644 index 0000000000..36f5670d10 --- /dev/null +++ b/pages/linebyline/src/main/kotlin/com/quran/labs/androidquran/pages/linebyline/LineByLinePages.kt @@ -0,0 +1,42 @@ +package com.quran.labs.androidquran.pages.linebyline + +import android.content.Context +import android.view.View +import androidx.fragment.app.Fragment +import com.quran.data.di.AppScope +import com.quran.data.source.PageContentType +import com.quran.data.source.PageProvider +import com.quran.labs.androidquran.extra.feature.linebyline.QuranLineByLineFragment +import com.quran.labs.androidquran.extra.feature.linebyline.QuranLineByLineWrapperView +import com.quran.page.common.data.PageMode +import com.quran.page.common.factory.PageViewFactory +import com.quran.page.common.factory.PageViewFactoryProvider +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.Provides + +/** + * Shows the page types drawn line by line (PageContentType.Line) with feature:linebyline, in the + * open source build (app/pluggable.gradle). quran.com's own build wires its page views in extras. + */ +@BindingContainer +@ContributesTo(AppScope::class) +object LineByLinePagesModule { + + @Provides + fun providePageViewFactoryProvider(pageProviders: Map): PageViewFactoryProvider = + PageViewFactoryProvider { pageType -> + LineByLinePageViewFactory.takeIf { pageProviders[pageType]?.getPageContentType() is PageContentType.Line } + } +} + +internal object LineByLinePageViewFactory : PageViewFactory { + + // a single Arabic page is a fragment of its own; every other mode keeps its usual fragment, which + // asks for the Arabic page's view below + override fun providePage(pageNumber: Int, pageMode: PageMode): Fragment? = + if (pageMode is PageMode.SingleArabicPage) QuranLineByLineFragment.newInstance(pageNumber) else null + + override fun providePageView(context: Context, pageNumber: Int, pageMode: PageMode): View = + QuranLineByLineWrapperView(context, pageNumber, dualScreenMode = true) +} diff --git a/pages/madani/build.gradle.kts b/pages/madani/build.gradle.kts index 21b9612cbb..0086fb9861 100644 --- a/pages/madani/build.gradle.kts +++ b/pages/madani/build.gradle.kts @@ -12,5 +12,7 @@ dependencies { implementation(project(":common:upgrade")) implementation(project(":pages:common:madani")) + + implementation(libs.androidx.annotation) api(project(":pages:data:madani")) } diff --git a/pages/madani/src/main/java/com/quran/data/page/provider/QuranDataModule.kt b/pages/madani/src/main/java/com/quran/data/page/provider/QuranDataModule.kt index fefefe9b29..95840b152a 100644 --- a/pages/madani/src/main/java/com/quran/data/page/provider/QuranDataModule.kt +++ b/pages/madani/src/main/java/com/quran/data/page/provider/QuranDataModule.kt @@ -3,12 +3,17 @@ package com.quran.data.page.provider import com.quran.common.upgrade.LocalDataUpgrade import com.quran.common.upgrade.PreferencesUpgrade import com.quran.data.constant.DependencyInjectionConstants +import com.quran.data.page.provider.edition.Madani1421PageProvider +import com.quran.data.page.provider.edition.Madani1439LinesPageProvider +import com.quran.data.page.provider.edition.Madani1440PageProvider +import com.quran.data.page.provider.edition.Madani1441LinesPageProvider +import com.quran.data.page.provider.edition.ShemerlyPageProvider import com.quran.data.page.provider.madani.MadaniPageProvider +import com.quran.data.page.provider.tajweed.TajweedPageProvider import com.quran.data.pageinfo.mapper.AyahMapper import com.quran.data.pageinfo.mapper.IdentityAyahMapper import com.quran.data.source.PageProvider import com.quran.page.common.draw.ImageDrawHelper -import com.quran.page.common.factory.PageViewFactoryProvider import dev.zacsweers.metro.BindingContainer import dev.zacsweers.metro.ElementsIntoSet import dev.zacsweers.metro.IntoMap @@ -20,11 +25,6 @@ import dev.zacsweers.metro.StringKey @BindingContainer object QuranDataModule { - @Provides - fun providePageViewFactoryProvider(): PageViewFactoryProvider { - return PageViewFactoryProvider { null } - } - @Named(DependencyInjectionConstants.FALLBACK_PAGE_TYPE) @JvmStatic @Provides @@ -38,6 +38,42 @@ object QuranDataModule { return MadaniPageProvider() } + @JvmStatic + @Provides + @IntoMap + @StringKey(TajweedPageProvider.KEY) + fun provideTajweedPageSet(): PageProvider = TajweedPageProvider() + + @JvmStatic + @Provides + @IntoMap + @StringKey(Madani1421PageProvider.KEY) + fun provideMadani1421PageSet(): PageProvider = Madani1421PageProvider() + + @JvmStatic + @Provides + @IntoMap + @StringKey(Madani1440PageProvider.KEY) + fun provideMadani1440PageSet(): PageProvider = Madani1440PageProvider() + + @JvmStatic + @Provides + @IntoMap + @StringKey(Madani1439LinesPageProvider.KEY) + fun provideMadani1439LinesPageSet(): PageProvider = Madani1439LinesPageProvider() + + @JvmStatic + @Provides + @IntoMap + @StringKey(Madani1441LinesPageProvider.KEY) + fun provideMadani1441LinesPageSet(): PageProvider = Madani1441LinesPageProvider() + + @JvmStatic + @Provides + @IntoMap + @StringKey(ShemerlyPageProvider.KEY) + fun provideShemerlyPageSet(): PageProvider = ShemerlyPageProvider() + @JvmStatic @Provides @ElementsIntoSet diff --git a/pages/madani/src/main/java/com/quran/data/page/provider/edition/HafsEditionPageProvider.kt b/pages/madani/src/main/java/com/quran/data/page/provider/edition/HafsEditionPageProvider.kt new file mode 100644 index 0000000000..ccba71b3dd --- /dev/null +++ b/pages/madani/src/main/java/com/quran/data/page/provider/edition/HafsEditionPageProvider.kt @@ -0,0 +1,64 @@ +package com.quran.data.page.provider.edition + +import androidx.annotation.StringRes +import com.quran.data.page.provider.madani.MadaniPageProvider +import com.quran.data.source.DisplaySize +import com.quran.data.source.PageProvider +import com.quran.data.source.PageSizeCalculator + +/** + * A Hafs mushaf edition as quran.com's own app downloads it from files.quran.app/hafs/[folder], at + * a single width. Its reciters, and so the hints of the memorize feature, are the Madani page + * type's; an edition with other pages also has its own data source and mushaf type. + * + * The images zip carries the edition's ayahinfo database too, so it lands in + * [directory]/databases. Editions of the same layout family may share [directory]: their files + * differ by width. + */ +abstract class HafsEditionPageProvider( + folder: String, + private val width: String, + private val imageVersion: Int, + private val directory: String, + @StringRes private val title: Int, + @StringRes private val description: Int, + madani: MadaniPageProvider = MadaniPageProvider(), +) : PageProvider by madani { + + private val baseUrl = "$SERVER/$folder" + + override fun getPageSizeCalculator(displaySize: DisplaySize): PageSizeCalculator = + FixedWidthCalculator(width) + + // the full zip holds a .vN file for each version up to this one + override fun getImageVersion() = imageVersion + + override fun getImagesBaseUrl() = "$baseUrl/" + + override fun getImagesZipBaseUrl() = "$baseUrl/zips/" + + override fun getPatchBaseUrl() = "$baseUrl/patches/v" + + override fun getAyahInfoBaseUrl() = "$baseUrl/databases/ayahinfo/" + + override fun getImagesDirectoryName() = directory + + override fun getAyahInfoDirectoryName() = "$directory/databases" + + override fun getPreviewTitle() = title + + override fun getPreviewDescription() = description + + private class FixedWidthCalculator(private val width: String) : PageSizeCalculator { + override fun getWidthParameter() = width + + override fun getTabletWidthParameter() = width + + // there is only one width + override fun setOverrideParameter(parameter: String) = Unit + } + + private companion object { + const val SERVER = "https://files.quran.app/hafs" + } +} diff --git a/pages/madani/src/main/java/com/quran/data/page/provider/edition/MadaniEditions.kt b/pages/madani/src/main/java/com/quran/data/page/provider/edition/MadaniEditions.kt new file mode 100644 index 0000000000..1a4db5ace9 --- /dev/null +++ b/pages/madani/src/main/java/com/quran/data/page/provider/edition/MadaniEditions.kt @@ -0,0 +1,121 @@ +package com.quran.data.page.provider.edition + +import com.quran.data.source.MushafType +import com.quran.data.source.PageContentType +import com.quran.data.source.QuranDataSource +import com.quran.labs.androidquran.pages.data.madani.Madani1440DataSource +import com.quran.labs.androidquran.pages.data.shemerly.ShemerlyDataSource +import com.quran.labs.androidquran.pages.madani.R + +// The editions of quran.com's Page Type (experimental) list, under the keys its own app uses. + +/** The King Fahd Complex's newer prints share one page layout, and one directory. */ +private const val NEW_MADANI = "new_madani" +private val madani1440Pages by lazy { Madani1440DataSource() } +private val shemerlyPages by lazy { ShemerlyDataSource() } + +/** Madani Mushaf (1421). */ +class Madani1421PageProvider : HafsEditionPageProvider( + folder = "madani_1421", + width = "1120", + imageVersion = 2, + directory = NEW_MADANI, + title = R.string.madani_1421_title, + description = R.string.madani_1421_description, +) { + override fun getDataSource(): QuranDataSource = madani1440Pages + + override fun mushafType() = MushafType.MADANI_1440 + + companion object { + const val KEY = "new_madani" + } +} + +/** Madani Mushaf (1440). */ +class Madani1440PageProvider : HafsEditionPageProvider( + folder = "madani_1440", + width = "1352", + imageVersion = 4, + directory = NEW_MADANI, + title = R.string.madani_1440_title, + description = R.string.madani_1440_description, +) { + override fun getDataSource(): QuranDataSource = madani1440Pages + + override fun mushafType() = MushafType.MADANI_1440 + + companion object { + const val KEY = "new_madani_1441" + } +} + +/** + * The editions drawn line by line (feature:linebyline): each page is 15 line images. Without them + * the app falls back to the 1440 edition, as quran.com's app does. + */ +abstract class MadaniLinesPageProvider( + folder: String, + width: String, + private val pageType: String, + title: Int, + description: Int, +) : HafsEditionPageProvider(folder, width, imageVersion = 1, NEW_MADANI, title, description) { + + override fun getDataSource(): QuranDataSource = madani1440Pages + + override fun mushafType() = MushafType.MADANI_1440 + + override fun getPageContentType() = + PageContentType.Line(ratio = 174f / 1080f, lineHeight = 174, allowOverlapOfLines = true) + + override fun getFallbackPageType() = Madani1440PageProvider.KEY + + // the line view picks its marker colors by it + override fun pageType() = pageType +} + +/** Madani Mushaf (1439), optimized for larger screens. */ +class Madani1439LinesPageProvider : MadaniLinesPageProvider( + folder = "madani_1439", + width = "1080", + pageType = "madani_1439", + title = R.string.madani_1439_lines_title, + description = R.string.madani_1439_lines_description, +) { + companion object { + // ends in "lines": the checks for missing page images skip it + const val KEY = "new_madani_1439_lines" + } +} + +/** Madani Mushaf (1441), optimized for larger screens. */ +class Madani1441LinesPageProvider : MadaniLinesPageProvider( + folder = "madani_1441", + width = "1440", + pageType = "madani_1441", + title = R.string.madani_1441_lines_title, + description = R.string.madani_1441_lines_description, +) { + companion object { + const val KEY = "madani_1441_lines" + } +} + +/** The Shemerly print, popular in Egypt: 521 pages. */ +class ShemerlyPageProvider : HafsEditionPageProvider( + folder = "shemerly", + width = "1200", + imageVersion = 1, + directory = "shemerly", + title = R.string.shemerly_title, + description = R.string.shemerly_description, +) { + override fun getDataSource(): QuranDataSource = shemerlyPages + + override fun mushafType() = MushafType.SHEMERLY + + companion object { + const val KEY = "shemerly" + } +} diff --git a/pages/madani/src/main/java/com/quran/data/page/provider/madani/MadaniPageProvider.kt b/pages/madani/src/main/java/com/quran/data/page/provider/madani/MadaniPageProvider.kt index 84f8fb3545..a743ff6375 100644 --- a/pages/madani/src/main/java/com/quran/data/page/provider/madani/MadaniPageProvider.kt +++ b/pages/madani/src/main/java/com/quran/data/page/provider/madani/MadaniPageProvider.kt @@ -72,12 +72,32 @@ class MadaniPageProvider : PageProvider { path = "2", hasGaplessAlternative = false, db = null + ), + // also the voices of the memorize feature's hints (feature:memorize PromptPlayer) + Qari( + HUSARY_MUALLIM, + audioR.string.qari_husary_muallim_gapless, + url = "https://download.quranicaudio.com/quran/husary_muallim/", + path = "husary_muallim", + hasGaplessAlternative = false, + db = "husary_muallim" + ), + Qari( + HUSARY_MUJAWWAD, + audioR.string.qari_husary_mujawwad_gapless, + url = "https://download.quranicaudio.com/quran/generated/husary_mujawwad/", + path = "husary_mujawwad", + hasGaplessAlternative = false, + db = "husary_mujawwad" ) ) } companion object { private const val baseUrl = "https://android.quran.com/data" + // ids well above the upstream reciter list so they can never collide with it + const val HUSARY_MUALLIM = 1001 + const val HUSARY_MUJAWWAD = 1002 private val dataSource by lazy { MadaniDataSource() } } } diff --git a/pages/madani/src/main/java/com/quran/data/page/provider/tajweed/TajweedPageProvider.kt b/pages/madani/src/main/java/com/quran/data/page/provider/tajweed/TajweedPageProvider.kt new file mode 100644 index 0000000000..225a2f460d --- /dev/null +++ b/pages/madani/src/main/java/com/quran/data/page/provider/tajweed/TajweedPageProvider.kt @@ -0,0 +1,21 @@ +package com.quran.data.page.provider.tajweed + +import com.quran.data.page.provider.edition.HafsEditionPageProvider +import com.quran.labs.androidquran.pages.madani.R + +/** + * The Madani mushaf with its tajweed rules in color: the same pages, ayat and reciters as the + * Madani page type; only its images and glyph boxes differ. Shown under Page Type (experimental). + */ +class TajweedPageProvider : HafsEditionPageProvider( + folder = "tajweed", + width = "1280", + imageVersion = 7, + directory = "tajweed", + title = R.string.tajweed_title, + description = R.string.tajweed_description, +) { + companion object { + const val KEY = "tajweed" + } +} diff --git a/pages/madani/src/main/res/values-ar/strings.xml b/pages/madani/src/main/res/values-ar/strings.xml new file mode 100644 index 0000000000..813f6b82c4 --- /dev/null +++ b/pages/madani/src/main/res/values-ar/strings.xml @@ -0,0 +1,17 @@ + + + مصحف المدينة السالفة + مصحف المدينة الطبعة من عام ١٤٠٥ من مجمع الملك فهد لطباعة المصحف الشريف + مصحف التجويد + مصحف التجويد. + مصحف المدينة (١٤٢١) + مصحف المدينة الطبعة من عام ١٤٢١ من مجمع الملك فهد لطباعة المصحف الشريف + مصحف المدينة (١٤٤٠) + مصحف المدينة الطبعة من عام ١٤٤٠ من مجمع الملك فهد لطباعة المصحف الشريف + مصحف المدينة (١٤٣٩) - ملائم للشاشات الأطول + مصحف المدينة الطبعة من عام ١٤٣٩ من مجمع الملك فهد لطباعة المصحف الشريف + مصحف المدينة (١٤٤١) - ملائم للشاشات الأطول + مصحف المدينة الطبعة من عام ١٤٤١ من مجمع الملك فهد لطباعة المصحف الشريف + مصحف الشمرلي + المصحف الشريف طبعة الشمرلي المنتشرة بكثرة في مصر وبعض البلدان العربية. + diff --git a/pages/madani/src/main/res/values/strings.xml b/pages/madani/src/main/res/values/strings.xml index 2e185d439d..34486811c8 100644 --- a/pages/madani/src/main/res/values/strings.xml +++ b/pages/madani/src/main/res/values/strings.xml @@ -2,4 +2,16 @@ Classic Madani Mushaf The classic Madani script. + Tajweed Mushaf + Mushaf with Tajweed coloring. + Madani Mushaf (1421) + The 1421 new Madani script from the King Fahd Quran Complex. + Madani Mushaf (1440) + The 1440 Madani script from the King Fahd Quran Complex. + Madani Mushaf (1439) - optimized for larger screens + The 1439 Madani script from the King Fahd Quran Complex. + Madani Mushaf (1441) - optimized for larger screens + The 1441 Madani script from the King Fahd Quran Complex. + Shemerly Mushaf + Mushaf, Shemerly Print, popular in Egypt and a few other countries. diff --git a/settings.gradle.kts b/settings.gradle.kts index 05b653bc11..9d9a4a36ef 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -16,6 +16,10 @@ dependencyResolutionManagement { maven("https://quran.github.io/mobile-sync/maven") { content { includeGroup("com.quran") } } + // sherpa-onnx (speech engine of the memorize feature); fetched by tools/memorize/fetch_sherpa_onnx.sh + maven(file("third_party/maven")) { + content { includeGroup("com.k2fsa.sherpa.onnx") } + } } } @@ -36,6 +40,7 @@ include(":common:linebyline:data") include(":common:linebyline:ui") include(":common:recitation") include(":common:preference") +include(":common:progress") include(":common:search") include(":common:toolbar") include(":common:translation") @@ -50,7 +55,11 @@ include(":feature:audiobar") include(":feature:ayahbookmark") include(":feature:downloadmanager") include(":feature:linebyline") +include(":feature:memorize") +include(":feature:memorize:engine-sherpa") +include(":feature:memorize:tracker") include(":feature:pagetheme") +include(":feature:progress") include(":feature:qarilist") include(":feature:recitation") include(":feature:sync") @@ -59,6 +68,7 @@ include(":pages:data:madani") include(":pages:data:warsh") include(":pages:common:madani") include(":pages:common:warsh") +include(":pages:linebyline") include(":autoquran") if (File(rootDir, "extras/settings-extra.gradle").exists()) { diff --git a/tools/memorize/align_timing_pack.py b/tools/memorize/align_timing_pack.py new file mode 100644 index 0000000000..6219604a59 --- /dev/null +++ b/tools/memorize/align_timing_pack.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +"""Builds a word-timing pack by forced alignment of a qari's own audio files. + +The streaming phoneme model (sherpa-onnx, zipformer2-CTC) is run over each sura file; its tokens +carry timestamps (positions in the audio). The token sequence is aligned (edit distance) with the +expected phoneme sequence of the sura. When quran.com (QDC) segments exist for the recitation, the +expected sequence follows their order, which includes the reciter going back to repeat words +(waqf/ibtida); otherwise it's the plain mushaf order. Each word keeps its last occurrence, the one +that continues forward, which is what a "next word" hint should play. + +A word's start is its first token's time (minus a small lead), and its end is the next word's start +when the recitation continues, or its last token plus a tail before a pause. + +Output schema: see build_timing_pack.py (word numbering = glyph words). + +Usage (in the ML environment: needs sherpa-onnx and numpy): + python -I tools/memorize/align_timing_pack.py --audio-dir DIR --model-dir MODEL --lexicon lexicon_v1.db \ + --voice husary_murattal --out husary_murattal_wbw.db [--qdc-reciter 6] [--suras 1 2 ...] +""" +import argparse +import hashlib +import json +import os +import sqlite3 +import subprocess +import sys +import time +import urllib.request + +import numpy as np +import sherpa_onnx + +# quran-transcript phonetic script -> letter level (same folding as the app's PhonemeNormalizer) +SPECIAL = {"ڇ": "", "ۜ": "", "ـ": "", "ں": "ن", "۾": "م", "ٲ": "ء", "ؙ": "ُ", "۪": "َ"} +LONG = {"ا": "ا", "ۥ": "و", "ۦ": "ي"} +VOWELS = set("َُِ") +QDC_URL = "https://api.qurancdn.com/api/qdc/audio/reciters/{reciter}/audio_files?chapter={sura}&segments=true" + +LEAD_MS = 120 # audio kept before a word's first token +TAIL_MS = 260 # audio kept after a word's last token when a pause follows +MAX_GAP_MS = 700 # a gap longer than this between words counts as a pause + + +def normalize(text): + out = [] + for ch in text: + if ch.isspace(): + continue + ch = SPECIAL.get(ch, ch) + if not ch: + continue + ch = LONG.get(ch, ch) + if ch in VOWELS: + continue # consonant skeleton + long vowels: robust to vowel recognition errors + if out and out[-1] == ch: + continue + out.append(ch) + return "".join(out) + + +def load_audio(path): + cmd = ["ffmpeg", "-nostdin", "-v", "error", "-i", path, "-ac", "1", "-ar", "16000", "-f", "f32le", "-"] + return np.frombuffer(subprocess.run(cmd, check=True, capture_output=True).stdout, dtype=np.float32) + + +def recognize(model_dir, audio): + rec = sherpa_onnx.OnlineRecognizer.from_zipformer2_ctc( + tokens=os.path.join(model_dir, "tokens.txt"), model=os.path.join(model_dir, "quran-stt-int8.onnx"), + num_threads=4, enable_endpoint_detection=False) + s = rec.create_stream() + step = 16000 + for i in range(0, len(audio), step): + s.accept_waveform(16000, audio[i:i + step]) + while rec.is_ready(s): + rec.decode_stream(s) + s.accept_waveform(16000, np.zeros(16000, dtype=np.float32)) + s.input_finished() + while rec.is_ready(s): + rec.decode_stream(s) + r = rec.get_result_all(s) + symbols = [] # (symbol, ms) + for tok, ts in zip(r.tokens, r.timestamps): + for ch in normalize(tok): + if not symbols or symbols[-1][0] != ch: + symbols.append((ch, int(ts * 1000))) + return symbols + + +def expected_sequence(con, sura, qdc): + """[(ayah, word, phonemes)] in recited order.""" + words = {(a, w): normalize(p) for a, w, p in + con.execute("select ayah, word, wasl from words where sura=? order by ayah, word", (sura,))} + if not qdc: + return [(a, w, p) for (a, w), p in sorted(words.items())] + seq = [] + for v in qdc["audio_files"][0]["verse_timings"]: + s, a = (int(x) for x in v["verse_key"].split(":")) + segments = [seg for seg in (v.get("segments") or []) if len(seg) >= 3] + order = [int(seg[0]) for seg in segments] or sorted(w for (aa, w) in words if aa == a) + for w in order: + if (a, w) in words: + seq.append((a, w, words[(a, w)])) + # words QDC has no segment for still have to be in the sequence + present = set(order) + for (aa, w) in sorted(words): + if aa == a and w not in present: + seq.append((a, w, words[(aa, w)])) + return seq + + +def align(symbols, seq): + """Global alignment of heard symbols with the expected sequence; returns, per sequence item, + the (first, last) indexes of heard symbols aligned with it, or None.""" + expected = [] + owner = [] + for k, (_, _, ph) in enumerate(seq): + for ch in ph: + expected.append(ch) + owner.append(k) + heard = [c for c, _ in symbols] + n, m = len(heard), len(expected) + # banded DP would be faster; files are at most a few hours so a full DP in numpy rows is fine + INF = 1 << 30 + prev = np.arange(m + 1, dtype=np.int32) + back = np.zeros((n + 1, m + 1), dtype=np.uint8) # 0 diag, 1 up (extra heard), 2 left (missing) + back[0, 1:] = 2 + exp_arr = np.array([ord(c) for c in expected], dtype=np.int32) + for i in range(1, n + 1): + cur = np.empty(m + 1, dtype=np.int32) + cur[0] = i + back[i, 0] = 1 + sub = prev[:-1] + (exp_arr != ord(heard[i - 1])).astype(np.int32) + up = prev[1:] + 1 + best = np.minimum(sub, up) + choice = np.where(sub <= up, 0, 1).astype(np.uint8) + # left moves need a sequential pass + for j in range(1, m + 1): + v = best[j - 1] + c = choice[j - 1] + left = cur[j - 1] + 1 + if left < v: + v, c = left, 2 + cur[j] = v + back[i, j] = c + prev = cur + spans = [None] * len(seq) + i, j = n, m + while i > 0 and j > 0: + c = back[i, j] + if c == 0: + k = owner[j - 1] + f, l = spans[k] if spans[k] else (i - 1, i - 1) + spans[k] = (min(f, i - 1), max(l, i - 1)) + i, j = i - 1, j - 1 + elif c == 1: + i -= 1 + else: + j -= 1 + return spans + + +def fetch_qdc(reciter, sura, cache_dir): + path = os.path.join(cache_dir, str(reciter), f"{sura}.json") + if os.path.exists(path): + return json.load(open(path, encoding="utf-8")) + req = urllib.request.Request(QDC_URL.format(reciter=reciter, sura=sura), headers={"User-Agent": "quran-android-tools"}) + data = json.load(urllib.request.urlopen(req, timeout=60)) + os.makedirs(os.path.dirname(path), exist_ok=True) + json.dump(data, open(path, "w", encoding="utf-8")) + return data + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--audio-dir", required=True) + ap.add_argument("--model-dir", required=True) + ap.add_argument("--lexicon", required=True) + ap.add_argument("--voice", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--qdc-reciter", type=int) + ap.add_argument("--cache-dir", default=os.path.expanduser("~/quran-asr-lab/cache/qdc")) + ap.add_argument("--suras", nargs="*", type=int, default=list(range(1, 115))) + a = ap.parse_args() + + con = sqlite3.connect(a.lexicon) + out_exists = os.path.exists(a.out) + db = sqlite3.connect(a.out) + if not out_exists: + db.execute("create table properties(property text primary key, value text)") + db.execute("create table timings(sura integer not null, ayah integer not null, time integer not null, " + "words text not null, primary key(sura, ayah))") + db.execute("create table audio_files(sura integer primary key, size integer not null, md5 text not null)") + db.executemany("insert into properties values (?, ?)", [ + ("version", "1"), ("schema_version", "2"), ("wbw", "1"), ("word_numbering", "glyph"), + ("voice", a.voice), ("source", "forced alignment of the qari's own audio"), + ]) + for sura in a.suras: + path = os.path.join(a.audio_dir, f"{sura:03d}.mp3") + if not os.path.exists(path): + print(f"sura {sura}: no audio, skipped") + continue + t0 = time.time() + audio = load_audio(path) + symbols = recognize(a.model_dir, audio) + qdc = fetch_qdc(a.qdc_reciter, sura, a.cache_dir) if a.qdc_reciter else None + seq = expected_sequence(con, sura, qdc) + spans = align(symbols, seq) + + # last occurrence of every word + last = {} + for k, (ayah, word, _) in enumerate(seq): + if spans[k] is not None: + last[(ayah, word)] = k + starts = {k: symbols[spans[k][0]][1] for k in range(len(seq)) if spans[k] is not None} + rows = {} + missing = 0 + for (ayah, word) in sorted({(x[0], x[1]) for x in seq}): + k = last.get((ayah, word)) + if k is None: + missing += 1 + continue + first_ms = symbols[spans[k][0]][1] + last_ms = symbols[spans[k][1]][1] + nxt = next((starts[j] for j in range(k + 1, len(seq)) if j in starts), None) + if nxt is not None and nxt - last_ms <= MAX_GAP_MS: + end = nxt - LEAD_MS // 2 + else: + end = last_ms + TAIL_MS + start = max(0, first_ms - LEAD_MS) + rows.setdefault(ayah, []).append(f"{word}:{start}:{max(end, start + 150)}") + for ayah, words in rows.items(): + first = int(words[0].split(":")[1]) + db.execute("insert or replace into timings values (?, ?, ?, ?)", (sura, ayah, first, ",".join(words))) + digest = hashlib.md5(open(path, "rb").read()).hexdigest() + db.execute("insert or replace into audio_files values (?, ?, ?)", (sura, os.path.getsize(path), digest)) + db.commit() + print(f"sura {sura}: {len(seq)} recited words, {missing} unaligned, {time.time() - t0:.0f}s", flush=True) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/memorize/build_glyph_types.py b/tools/memorize/build_glyph_types.py new file mode 100644 index 0000000000..4eeea0795e --- /dev/null +++ b/tools/memorize/build_glyph_types.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Derive per-ayah glyph types for the madani page images. + +The madani ayahinfo databases store one bounding box per glyph but no glyph type. The memorize +feature needs to know which glyphs are words (to hide/reveal them one by one) and which are waqf +marks, sajdah/hizb markers or the ayah-end marker. + +Rules (validated against every ayah): + * the last glyph of an ayah is the ayah-end marker, + * an ayah whose text starts with ۞ starts with a hizb marker glyph, + * an ayah whose text contains ۩ has a sajdah marker glyph just before the end marker, + * of the remaining glyphs, the number of words is known from word_alignment.db (the same + glyph-word numbering the app already uses); the leftovers are waqf marks, which are always the + shortest glyphs (they float above the line; some are wide, e.g. the ج in 38:26). + +Output: one line per ayah, "sura ayah types", where types has one character per glyph position: + w = word, p = pause (waqf mark), s = sajdah marker, h = hizb marker, e = ayah end. + +Usage: + python3 -I tools/memorize/build_glyph_types.py --ayahinfo ayahinfo_1024.db \ + --arabic quran.ar.uthmani.v2.db --word-alignment app/src/madani/assets/word_alignment.db \ + --out glyph_types_madani_v1.txt [--verify ayahinfo_1260.db ...] +""" +import argparse +import collections +import sqlite3 +import sys + + +def glyph_widths(ayahinfo_path): + con = sqlite3.connect(ayahinfo_path) + rows = collections.defaultdict(list) + query = ("select sura_number, ayah_number, position, max_y - min_y, max_x - min_x from glyphs " + "order by sura_number, ayah_number, position") + for sura, ayah, position, height, width in con.execute(query): + rows[(sura, ayah)].append((position, height, width)) + return rows + + +def glyph_word_counts(word_alignment_path): + con = sqlite3.connect(word_alignment_path) + counts = {} + for sura, ayah, numbers in con.execute("select sura, ayah, glyph_word_numbers from word_alignment"): + highest = max(int(n) for n in numbers.split(",")) + counts[(sura, ayah)] = max(counts.get((sura, ayah), 0), highest) + return counts + + +def ayah_texts(arabic_path): + con = sqlite3.connect(arabic_path) + return {(s, a): t for s, a, t in con.execute("select sura, ayah, text from arabic_text")} + + +def derive_types(sizes, text, word_count): + """Returns the type string for one ayah, or raises ValueError if the rules don't fit. + + sizes holds (height, width) per glyph position. + """ + count = len(sizes) + types = [None] * count + types[-1] = "e" + start = 0 + if text.startswith("۞"): + types[0] = "h" + start = 1 + end = count - 1 + if "۩" in text: + types[end - 1] = "s" + end -= 1 + body = list(range(start, end)) + pauses = len(body) - word_count + if pauses < 0: + raise ValueError(f"{len(body)} glyphs but {word_count} words") + smallest = set(sorted(body, key=lambda i: (sizes[i][0], sizes[i][1], i))[:pauses]) + for i in body: + types[i] = "p" if i in smallest else "w" + return "".join(types) + + +def build(ayahinfo, texts, word_counts): + rows = glyph_widths(ayahinfo) + result = {} + for key in sorted(texts): + positions = rows.get(key) + if not positions: + raise ValueError(f"{key}: no glyphs") + if [p for p, _, _ in positions] != list(range(1, len(positions) + 1)): + raise ValueError(f"{key}: glyph positions are not contiguous") + result[key] = derive_types([(h, w) for _, h, w in positions], texts[key], word_counts[key]) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--ayahinfo", required=True) + parser.add_argument("--arabic", required=True) + parser.add_argument("--word-alignment", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--verify", nargs="*", default=[], + help="other ayahinfo widths that must yield identical types") + args = parser.parse_args() + + texts = ayah_texts(args.arabic) + word_counts = glyph_word_counts(args.word_alignment) + types = build(args.ayahinfo, texts, word_counts) + + pause_wider_than_word = [k for k, t in types.items() if "p" in t and t.count("w") != word_counts[k]] + if pause_wider_than_word: + sys.exit(f"word count mismatch in {pause_wider_than_word[:5]}") + + for other in args.verify: + other_types = build(other, texts, word_counts) + diffs = [k for k in types if types[k] != other_types[k]] + print(f"{other}: {len(diffs)} ayahs differ {diffs[:10]}") + if diffs: + sys.exit(1) + + with open(args.out, "w", encoding="utf-8") as out: + for (sura, ayah), t in sorted(types.items()): + out.write(f"{sura} {ayah} {t}\n") + totals = collections.Counter("".join(types.values())) + print(f"wrote {len(types)} ayahs: {dict(totals)}") + + +if __name__ == "__main__": + main() diff --git a/tools/memorize/build_lexicon.py b/tools/memorize/build_lexicon.py new file mode 100644 index 0000000000..8d1a5183ac --- /dev/null +++ b/tools/memorize/build_lexicon.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""Build the phoneme lexicon used by the memorize tracker. + +For every word of the Quran (Hafs, glyph-word numbering of the madani pages) the lexicon stores the +word's phonemes in the quran-transcript phonetic script (the alphabet the speech model emits): + * wasl: as pronounced inside its ayah (assimilation with neighbours, hamzat al-wasl dropped), + * iso: as pronounced alone (what a reciter says when starting or stopping on this word). +It also stores the phrases a person says during salah that are not part of the passage being +recited (Al-Fatiha is tracked from the words table itself), so the tracker can ignore them. + +Requires `quran-transcript` (pip install quran-transcript; MIT). + +Usage: + python -I tools/memorize/build_lexicon.py --glyph-types glyph_types_madani_v1.txt --out lexicon_v1.db +""" +import argparse +import os +import sqlite3 +import sys + +from quran_transcript import Aya, MoshafAttributes, quran_phonetizer + +# Said during salah, never part of the passage. Written in Uthmani-style orthography so the +# phonetizer treats them like Quranic text. +SALAH_PHRASES = { + "takbir": ["ٱللَّهُ أَكْبَرُ"], + "tasmi": ["سَمِعَ ٱللَّهُ لِمَنْ حَمِدَهُۥ"], + "tahmid": ["رَبَّنَا وَلَكَ ٱلْحَمْدُ", "رَبَّنَا لَكَ ٱلْحَمْدُ", "ٱللَّهُمَّ رَبَّنَا لَكَ ٱلْحَمْدُ"], + "ruku": ["سُبْحَـٰنَ رَبِّىَ ٱلْعَظِيمِ"], + "sujud": ["سُبْحَـٰنَ رَبِّىَ ٱلْأَعْلَىٰ"], + "ameen": ["ءَامِينَ"], + "isti'adha": ["أَعُوذُ بِٱللَّهِ مِنَ ٱلشَّيْطَـٰنِ ٱلرَّجِيمِ"], + "basmala": ["بِسْمِ ٱللَّهِ ٱلرَّحْمَـٰنِ ٱلرَّحِيمِ"], + "istiftah": ["سُبْحَـٰنَكَ ٱللَّهُمَّ وَبِحَمْدِكَ وَتَبَارَكَ ٱسْمُكَ وَتَعَـٰلَىٰ جَدُّكَ وَلَآ إِلَـٰهَ غَيْرُكَ"], + "tasleem": ["ٱلسَّلَـٰمُ عَلَيْكُمْ وَرَحْمَةُ ٱللَّهِ"], +} + + +SHADDA = "\u0651" +HARAKAT = set("\u064b\u064c\u064d\u064e\u064f\u0650") + + +def canonical_marks(text): + """Puts shadda before the vowel mark on the same letter, the order the Tanzil text (and therefore + the phonetizer) uses.""" + chars = list(text) + for i in range(len(chars) - 1): + if chars[i] in HARAKAT and chars[i + 1] == SHADDA: + chars[i], chars[i + 1] = chars[i + 1], chars[i] + return "".join(chars) + + +def moshaf(): + return MoshafAttributes(rewaya="hafs", madd_monfasel_len=4, madd_mottasel_len=4, + madd_mottasel_waqf=4, madd_aared_len=4) + + +def word_spans(words, out): + """Splits the phonetized ayah into per-word phoneme strings using the character mappings.""" + result = [] + pos = 0 + for word in words: + starts, ends = [], [] + for _ in word: + mapping = out.mappings[pos] + if not mapping.deleted: + starts.append(mapping.pos[0]) + ends.append(mapping.pos[1]) + pos += 1 + pos += 1 # the space between words + result.append(out.phonemes[min(starts):max(ends)].strip() if starts else "") + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--glyph-types", required=True, help="output of build_glyph_types.py") + parser.add_argument("--out", required=True) + parser.add_argument("--compact", action="store_true", help="omit the Uthmani text (app asset)") + args = parser.parse_args() + + word_counts = {} + with open(args.glyph_types, encoding="utf-8") as f: + for line in f: + sura, ayah, types = line.split() + word_counts[(int(sura), int(ayah))] = types.count("w") + + m = moshaf() + rows = [] + aya = Aya(1, 1) + while True: + info = aya.get() + key = (info.sura_idx, info.aya_idx) + words = info.uthmani_words + if len(words) != word_counts[key]: + sys.exit(f"{key}: {len(words)} words in quran-transcript, {word_counts[key]} glyph words") + wasl = word_spans(words, quran_phonetizer(" ".join(words), m, sura_idx=info.sura_idx)) + for index, (word, in_context) in enumerate(zip(words, wasl), start=1): + alone = quran_phonetizer(word, m, sura_idx=info.sura_idx).phonemes.strip() + if not in_context: + in_context = alone + rows.append((info.sura_idx, info.aya_idx, index, word, in_context, alone)) + if key == (114, 6): + break + aya = aya.step(1) + + phrases = [] + for kind, texts in SALAH_PHRASES.items(): + for text in texts: + text = canonical_marks(text) + phrases.append((kind, text, quran_phonetizer(text, m).phonemes.strip())) + + if os.path.exists(args.out): + os.remove(args.out) + con = sqlite3.connect(args.out) + con.execute("create table properties(property text primary key, value text)") + con.execute("create table words(sura integer not null, ayah integer not null, word integer not null, " + + ("" if args.compact else "uthmani text not null, ") + + "wasl text not null, iso text not null, primary key(sura, ayah, word)) without rowid") + con.execute("create table phrases(kind text not null, text text not null, phonemes text not null)") + con.executemany("insert into properties values (?, ?)", [ + ("version", "1"), ("riwayah", "hafs"), ("word_numbering", "glyph"), ("alphabet", "quran-transcript"), + ]) + if args.compact: + rows = [(s, a, w, wasl, iso) for s, a, w, _, wasl, iso in rows] + con.executemany("insert into words values (?, ?, ?, ?, ?)", rows) + else: + con.executemany("insert into words values (?, ?, ?, ?, ?, ?)", rows) + con.executemany("insert into phrases values (?, ?, ?)", phrases) + con.commit() + con.execute("vacuum") + print(f"{len(rows)} words, {len(phrases)} phrases -> {args.out} ({os.path.getsize(args.out) / 1e6:.1f} MB)") + + +if __name__ == "__main__": + main() diff --git a/tools/memorize/build_timing_pack.py b/tools/memorize/build_timing_pack.py new file mode 100644 index 0000000000..2a01d8d53d --- /dev/null +++ b/tools/memorize/build_timing_pack.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +"""Build a word-timing pack for a gapless qari, used by the prayer corrector to play single words. + +Word segments come from the quran.com (QDC) audio API. They are timed against QDC's own copy of the +recording, which can be trimmed/resampled differently from the file the app downloads. For each sura +we therefore fit a linear map app_ms = a + b * qdc_ms using the ayah start times that both sides +know (the qari's ayah timing database vs. QDC's verse timestamps), reject outliers, and report the +residuals so a bad fit is visible instead of silently shipping wrong timings. + +Output (SQLite): + properties(property, value) version, voice, source, word_numbering=glyph + timings(sura, ayah, time, words) time = ayah start in ms; words = "word:start:end,..." where word is + the 1-based glyph word number on the madani page (WordGlyph.wordPosition) + audio_files(sura, size, md5) the exact files the timings were fitted for (optional, --audio-dir) + +Usage: + python3 -I tools/memorize/build_timing_pack.py --qdc-reciter 6 --ayah-db husary.db \ + --glyph-types glyph_types_madani_v1.txt --voice husary_murattal --out husary_murattal_wbw.db \ + [--audio-dir ] [--cache-dir ] [--identity] + +--identity skips the fit (for qaris whose audio *is* QDC's audio, e.g. Husary Muallim). +""" +import argparse +import hashlib +import json +import os +import sqlite3 +import statistics +import sys +import time +import urllib.request + +QDC_URL = "https://api.qurancdn.com/api/qdc/audio/reciters/{reciter}/audio_files?chapter={sura}&segments=true" + + +def fetch_json(url, cache_path): + if cache_path and os.path.exists(cache_path): + with open(cache_path, encoding="utf-8") as f: + return json.load(f) + for attempt in range(5): + try: + req = urllib.request.Request(url, headers={"User-Agent": "quran-android-tools"}) + data = json.load(urllib.request.urlopen(req, timeout=60)) + break + except OSError: + if attempt == 4: + raise + time.sleep(2 ** attempt) + if cache_path: + os.makedirs(os.path.dirname(cache_path), exist_ok=True) + with open(cache_path, "w", encoding="utf-8") as f: + json.dump(data, f) + return data + + +def glyph_word_counts(path): + counts = {} + with open(path, encoding="utf-8") as f: + for line in f: + sura, ayah, types = line.split() + counts[(int(sura), int(ayah))] = types.count("w") + return counts + + +def ayah_starts(ayah_db): + con = sqlite3.connect(ayah_db) + starts = {} + for sura, ayah, ms in con.execute("select sura, ayah, time from timings"): + starts[(sura, ayah)] = ms + return starts + + +def fit_linear(pairs): + """Least squares fit y = a + b x with one round of outlier rejection. Returns a, b, residuals.""" + def solve(points): + n = len(points) + if n == 1: + x, y = points[0] + return y - x, 1.0 + mx = sum(p[0] for p in points) / n + my = sum(p[1] for p in points) / n + sxx = sum((p[0] - mx) ** 2 for p in points) + if sxx == 0: + return my - mx, 1.0 + b = sum((p[0] - mx) * (p[1] - my) for p in points) / sxx + return my - b * mx, b + + a, b = solve(pairs) + residuals = [y - (a + b * x) for x, y in pairs] + if len(pairs) > 4: + cutoff = max(300.0, 3 * statistics.pstdev(residuals)) + kept = [p for p, r in zip(pairs, residuals) if abs(r) <= cutoff] + if len(kept) >= 2: + a, b = solve(kept) + residuals = [y - (a + b * x) for x, y in pairs] + return a, b, residuals + + +def md5_of(path): + digest = hashlib.md5() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--qdc-reciter", type=int, required=True) + parser.add_argument("--ayah-db", help="qari ayah timing db (timings(sura, ayah, time)); required unless --identity") + parser.add_argument("--glyph-types", required=True) + parser.add_argument("--voice", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--audio-dir") + parser.add_argument("--cache-dir", default=os.path.expanduser("~/quran-asr-lab/cache/qdc")) + parser.add_argument("--identity", action="store_true") + parser.add_argument("--anchor", choices=["sura", "ayah"], default="ayah", + help="ayah: re-anchor every ayah on the qari's own ayah start (default)") + parser.add_argument("--max-residual-ms", type=float, default=250.0) + args = parser.parse_args() + if not args.identity and not args.ayah_db: + parser.error("--ayah-db is required unless --identity") + + word_counts = glyph_word_counts(args.glyph_types) + starts = ayah_starts(args.ayah_db) if args.ayah_db else {} + + rows = [] + report = [] + problems = [] + for sura in range(1, 115): + url = QDC_URL.format(reciter=args.qdc_reciter, sura=sura) + cache = os.path.join(args.cache_dir, str(args.qdc_reciter), f"{sura}.json") + data = fetch_json(url, cache) + verses = data["audio_files"][0]["verse_timings"] + + if args.identity: + a, b, residuals = 0.0, 1.0, [0.0] + else: + pairs = [] + for v in verses: + s, ay = (int(x) for x in v["verse_key"].split(":")) + if (s, ay) in starts: + pairs.append((float(v["timestamp_from"]), float(starts[(s, ay)]))) + a, b, residuals = fit_linear(pairs) + worst = max(abs(r) for r in residuals) + report.append((sura, a, b, statistics.median(abs(r) for r in residuals), worst)) + if worst > args.max_residual_ms: + bad = sorted(range(len(residuals)), key=lambda i: -abs(residuals[i]))[:3] + problems.append(f"sura {sura}: worst ayah-start residual {worst:.0f} ms " + f"(ayah indexes {bad}, scale {b:.5f}, offset {a:.0f})") + + for v in verses: + s, ay = (int(x) for x in v["verse_key"].split(":")) + segments = [seg for seg in (v.get("segments") or []) if len(seg) >= 3] + expected = word_counts[(s, ay)] + # Reciters stop and restart a few words back (waqf/ibtida), so a word can have several + # segments. Keep the last one: it belongs to the run that continues to the ayah's end, + # which is what a prompt for "the next word" should play. + last = {} + for seg in segments: + word = int(seg[0]) + if 1 <= word <= expected: + last[word] = seg + missing = [w for w in range(1, expected + 1) if w not in last] + if missing: + problems.append(f"{s}:{ay}: no segment for glyph words {missing[:5]} of {expected}") + if not args.identity and args.anchor == "ayah" and (s, ay) in starts: + # the qari's own ayah start, with QDC's timing of the words relative to the ayah + offset = starts[(s, ay)] - b * float(v["timestamp_from"]) + else: + offset = a + words = [] + for word in sorted(last): + seg = last[word] + start = round(offset + b * float(seg[1])) + end = round(offset + b * float(seg[2])) + words.append(f"{word}:{start}:{max(end, start)}") + ayah_start = round(offset + b * float(v["timestamp_from"])) + rows.append((s, ay, starts.get((s, ay), ayah_start) if not args.identity else ayah_start, + ",".join(words))) + + if os.path.exists(args.out): + os.remove(args.out) + con = sqlite3.connect(args.out) + con.execute("create table properties(property text primary key, value text)") + con.execute("create table timings(sura integer not null, ayah integer not null, time integer not null, " + "words text not null, primary key(sura, ayah))") + con.execute("create table audio_files(sura integer primary key, size integer not null, md5 text not null)") + con.executemany("insert into properties values (?, ?)", [ + ("version", "1"), ("schema_version", "2"), ("wbw", "1"), ("word_numbering", "glyph"), + ("voice", args.voice), ("source", f"qdc reciter {args.qdc_reciter}" + ("" if args.identity else " (refitted)")), + ]) + con.executemany("insert into timings values (?, ?, ?, ?)", rows) + if args.audio_dir: + for sura in range(1, 115): + path = os.path.join(args.audio_dir, f"{sura:03d}.mp3") + if os.path.exists(path): + con.execute("insert into audio_files values (?, ?, ?)", (sura, os.path.getsize(path), md5_of(path))) + con.commit() + + medians = [r[3] for r in report] + worsts = [r[4] for r in report] + scales = [r[2] for r in report] + print(f"{len(rows)} ayahs written to {args.out}") + print(f"fit: median |residual| per sura {statistics.median(medians):.0f} ms, worst {max(worsts):.0f} ms, " + f"scale range {min(scales):.5f}..{max(scales):.5f}") + for line in problems[:40]: + print("WARN", line) + if len(problems) > 40: + print(f"... {len(problems) - 40} more warnings") + return 0 if not problems else 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/memorize/convert_wbw_db.py b/tools/memorize/convert_wbw_db.py new file mode 100644 index 0000000000..691c4f7e5f --- /dev/null +++ b/tools/memorize/convert_wbw_db.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Converts a gapless qari timing database that already has word-by-word timings (schema v2, +`words` = "audioWord:start:end,..." in audio/imlaei word numbering) into a memorize timing pack +(glyph word numbering, see build_timing_pack.py), using the app's word_alignment.db. + +The sizes of the sura files the timings belong to are needed so the app only plays a file that +matches; give either --audio-dir (local copies) or --sizes (a "sura size" list, e.g. from HTTP +Content-Length). + +Usage: + python3 -I tools/memorize/convert_wbw_db.py --db husary_muallim.db \ + --word-alignment app/src/madani/assets/word_alignment.db --glyph-types glyph_types_madani_v1.txt \ + --voice husary_muallim --sizes sizes.txt --out husary_muallim_wbw.db +""" +import argparse +import os +import sqlite3 +import sys + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--db", required=True) + ap.add_argument("--word-alignment", required=True) + ap.add_argument("--glyph-types", required=True) + ap.add_argument("--voice", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--sizes") + ap.add_argument("--audio-dir") + a = ap.parse_args() + + glyph_words = {} + with open(a.glyph_types, encoding="utf-8") as f: + for line in f: + s, ay, t = line.split() + glyph_words[(int(s), int(ay))] = t.count("w") + mapping = {} + for s, ay, audio_word, glyphs in sqlite3.connect(a.word_alignment).execute( + "select sura, ayah, audio_word_number, glyph_word_numbers from word_alignment"): + mapping[(s, ay, audio_word)] = [int(g) for g in glyphs.split(",")] + + src = sqlite3.connect(a.db) + rows = [] + incomplete = 0 + for sura, ayah, time, words in src.execute("select sura, ayah, time, words from timings where ayah > 0 and ayah < 999"): + spans = {} + for part in filter(None, (words or "").split(",")): + n, start, end = (int(x) for x in part.split(":")) + for g in mapping.get((sura, ayah, n), []): + old = spans.get(g) + spans[g] = (min(start, old[0]), max(end, old[1])) if old else (start, end) + if len(spans) != glyph_words.get((sura, ayah), -1): + incomplete += 1 + rows.append((sura, ayah, time, ",".join(f"{g}:{s}:{e}" for g, (s, e) in sorted(spans.items())))) + + sizes = {} + if a.sizes: + for line in open(a.sizes): + s, size = line.split() + sizes[int(s)] = int(size) + elif a.audio_dir: + for s in range(1, 115): + path = os.path.join(a.audio_dir, f"{s:03d}.mp3") + if os.path.exists(path): + sizes[s] = os.path.getsize(path) + + if os.path.exists(a.out): + os.remove(a.out) + out = sqlite3.connect(a.out) + out.execute("create table properties(property text primary key, value text)") + out.execute("create table timings(sura integer not null, ayah integer not null, time integer not null, " + "words text not null, primary key(sura, ayah))") + out.execute("create table audio_files(sura integer primary key, size integer not null, md5 text not null)") + out.executemany("insert into properties values (?, ?)", [ + ("version", "1"), ("schema_version", "2"), ("wbw", "1"), ("word_numbering", "glyph"), + ("voice", a.voice), ("source", f"converted from {os.path.basename(a.db)}"), + ]) + out.executemany("insert into timings values (?, ?, ?, ?)", rows) + out.executemany("insert into audio_files values (?, ?, '')", sorted(sizes.items())) + out.commit() + out.execute("vacuum") + print(f"{len(rows)} ayahs ({incomplete} without a timing for every glyph word), {len(sizes)} sura files -> {a.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/memorize/fetch_sherpa_onnx.sh b/tools/memorize/fetch_sherpa_onnx.sh new file mode 100755 index 0000000000..a49b8f3b6b --- /dev/null +++ b/tools/memorize/fetch_sherpa_onnx.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Fetches the sherpa-onnx Android AAR (Apache-2.0, https://github.com/k2-fsa/sherpa-onnx) into a +# local Maven repository under third_party/maven, verifying it against the SHA-256 published with +# the release. The memorize feature's speech engine depends on it; it isn't on Maven Central. +# +# tools/memorize/fetch_sherpa_onnx.sh +set -euo pipefail + +VERSION=1.13.8 +FILE=sherpa-onnx-static-link-onnxruntime-${VERSION}.aar +SHA256=b22c3fc1b6a45666d28892bb2f7694beeb77a8362d7ebd77c1a5431ec9435471 +URL=https://github.com/k2-fsa/sherpa-onnx/releases/download/v${VERSION}/${FILE} + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +DEST=$ROOT/third_party/maven/com/k2fsa/sherpa/onnx/sherpa-onnx/$VERSION +AAR=$DEST/sherpa-onnx-$VERSION.aar + +if [ -f "$AAR" ] && echo "$SHA256 $AAR" | sha256sum -c --status -; then + echo "sherpa-onnx $VERSION already present" + exit 0 +fi + +mkdir -p "$DEST" +curl -fL --retry 5 -o "$AAR.part" "$URL" +echo "$SHA256 $AAR.part" | sha256sum -c - +mv "$AAR.part" "$AAR" +cat > "$DEST/sherpa-onnx-$VERSION.pom" < + + 4.0.0 + com.k2fsa.sherpa.onnx + sherpa-onnx + $VERSION + aar + + Apache-2.0 + + +EOF +echo "sherpa-onnx $VERSION installed in $DEST" diff --git a/tools/memorize/merge_timing_packs.py b/tools/memorize/merge_timing_packs.py new file mode 100644 index 0000000000..b137b1b3b2 --- /dev/null +++ b/tools/memorize/merge_timing_packs.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Merges timing packs of one voice made in parallel (align_timing_pack.py --suras ...) into a new, +complete pack for the app, and checks that it covers the whole Quran. + +Some upstream sura files stop early (e.g. husary_muallim/004.mp3 on download.quranicaudio.com ends +in 4:34, while the recording continues to 4:176): --truncated SURA:LAST_AYAH keeps that sura's file +(so its size still matches what users download) but drops the ayat after LAST_AYAH, whose +alignment is meaningless. Hints for them are then shown without audio. + +Usage: + python -I tools/memorize/merge_timing_packs.py --voice husary_mujawwad --out husary_mujawwad_wbw_v1.db \ + [--truncated 4:33] part0.db part1.db ... +""" +import argparse +import os +import sqlite3 +import sys + +SURA_AYAHS = [ + 7, 286, 200, 176, 120, 165, 206, 75, 129, 109, 123, 111, 43, 52, 99, 128, 111, 110, 98, 135, 112, 78, + 118, 64, 77, 227, 93, 88, 69, 60, 34, 30, 73, 54, 45, 83, 182, 88, 75, 85, 54, 53, 89, 59, 37, 35, 38, + 29, 18, 45, 60, 49, 62, 55, 78, 96, 29, 22, 24, 13, 14, 11, 11, 18, 12, 12, 30, 52, 52, 44, 28, 28, 20, + 56, 40, 31, 50, 40, 46, 42, 29, 19, 36, 25, 22, 17, 19, 26, 30, 20, 15, 21, 11, 8, 8, 19, 5, 8, 8, 11, + 11, 8, 3, 9, 5, 4, 7, 3, 6, 3, 5, 4, 5, 6, +] +AYAH_COUNT = sum(SURA_AYAHS) +SURA_COUNT = len(SURA_AYAHS) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--voice", required=True) + ap.add_argument("--source", default="forced alignment of the qari's own audio") + ap.add_argument("--out", required=True) + ap.add_argument("--truncated", action="append", default=[], metavar="SURA:LAST_AYAH") + ap.add_argument("parts", nargs="+") + a = ap.parse_args() + + if os.path.exists(a.out): + sys.exit(f"{a.out} exists; refusing to overwrite it") + db = sqlite3.connect(a.out) + db.execute("create table properties(property text primary key, value text)") + db.execute("create table timings(sura integer not null, ayah integer not null, time integer not null, " + "words text not null, primary key(sura, ayah))") + db.execute("create table audio_files(sura integer primary key, size integer not null, md5 text not null)") + db.executemany("insert into properties values (?, ?)", [ + ("version", "1"), ("schema_version", "2"), ("wbw", "1"), ("word_numbering", "glyph"), + ("voice", a.voice), ("source", a.source), + ]) + for part in a.parts: + voice = sqlite3.connect(part).execute("select value from properties where property = 'voice'").fetchone() + if not voice or voice[0] != a.voice: + sys.exit(f"{part} is for voice {voice[0] if voice else None}, not {a.voice}") + db.execute("attach database ? as part", (part,)) + db.execute("insert or replace into timings select sura, ayah, time, words from part.timings") + db.execute("insert or replace into audio_files select sura, size, md5 from part.audio_files") + db.commit() + db.execute("detach database part") + + expected = list(SURA_AYAHS) + for spec in a.truncated: + sura, last = (int(x) for x in spec.split(":")) + dropped = db.execute("delete from timings where sura = ? and ayah > ?", (sura, last)).rowcount + expected[sura - 1] = last + print(f"sura {sura}: dropped {dropped} ayat after {last} (truncated upstream file)") + have = dict(db.execute("select sura, count(*) from timings group by sura")) + missing = [f"{sura}: {have.get(sura, 0)}/{n}" for sura, n in enumerate(expected, 1) if have.get(sura, 0) != n] + ayahs = db.execute("select count(*) from timings").fetchone()[0] + suras = db.execute("select count(*) from audio_files").fetchone()[0] + empty = db.execute("select count(*) from timings where words = ''").fetchone()[0] + db.commit() + db.execute("vacuum") + db.close() + print(f"{a.out}: {ayahs}/{AYAH_COUNT} ayat, {suras}/{SURA_COUNT} sura files, {empty} ayat without words") + if missing or suras != SURA_COUNT: + sys.exit("incomplete: " + ", ".join(missing)) + + +if __name__ == "__main__": + main() diff --git a/tools/memorize/run_device_benchmark.sh b/tools/memorize/run_device_benchmark.sh new file mode 100755 index 0000000000..70664e2e0d --- /dev/null +++ b/tools/memorize/run_device_benchmark.sh @@ -0,0 +1,120 @@ +#!/usr/bin/env bash +# Runs the memorize on-device tests on real phones in Firebase Test Lab (free Spark plan: 5 +# physical-device runs per day), or on a USB-connected phone. +# +# tools/memorize/run_device_benchmark.sh testlab [engine|session] [MODEL,VERSION ...] +# tools/memorize/run_device_benchmark.sh adb [engine|session] +# +# engine SherpaEngineBenchmarkTest: real-time factor, load time, worst chunk, native memory at +# 1, 2 and 4 threads ("threads=N rtf=… …", logcat tag MemorizeBenchmark) +# session MemorizeSessionOnDeviceTest: whole memorization sessions fed different reciters, +# non-professional and non-native readers in real time ("clip=… revealed=… …" and +# "group=… …", logcat tag MemorizeSession) +# +# The speech model and the test audio are bundled into the test APKs (build/memorize-testlab, not in +# git) so the phones don't have to download anything. The audio is staged by stage_test_clips.py from +# the datasets in $MEMORIZE_TEST_DATA (default ~/quran-asr-lab/data), with $MEMORIZE_TEST_PYTHON (an +# environment with numpy, soundfile and pyarrow; default ~/quran-asr-lab/.venv/bin/python). +set -euo pipefail +cd "$(dirname "$0")/../.." + +# the build needs the JDK CI uses (see .java-version); gcloud may live outside PATH +TOOLCHAIN="$HOME/.quran-android-toolchain" +if [ -z "${JAVA_HOME:-}" ] && [ -d "$TOOLCHAIN/jdk27" ]; then export JAVA_HOME="$TOOLCHAIN/jdk27"; fi +GCLOUD=$(command -v gcloud || echo "$HOME/.local/opt/google-cloud-sdk/bin/gcloud") + +TARGET="${1:-}" +shift || true +SUITE="engine" +if [ "${1:-}" = "engine" ] || [ "${1:-}" = "session" ]; then SUITE="$1"; shift; fi + +# the same pinned files as SpeechModelSpec.DEFAULT +MODEL_BASE="https://huggingface.co/Saboorhsn/quran-stt-onnx/resolve/51ec9bcddeaf1c480bbe39064a2a3b88bc2ff224" +stage_model() { + local dir=build/memorize-testlab + mkdir -p "$dir" + while read -r name sha; do + if [ ! -f "$dir/$name" ] || ! echo "$sha $dir/$name" | sha256sum -c --quiet - 2>/dev/null; then + curl -fsSL -o "$dir/$name.part" "$MODEL_BASE/$name" + echo "$sha $dir/$name.part" | sha256sum -c --quiet - + mv "$dir/$name.part" "$dir/$name" + fi + done <<'EOF' +quran-stt-int8.onnx 31755836528da336a6192121cd7bc82cb41752dddb65566fd000b89c8686da6b +tokens.txt 252c10687e442aa9291973065fae19fa39bcd681c4f5612ec496a647e20b43a1 +EOF +} + +stage_clips() { + [ -f build/memorize-testlab/clips/manifest.json ] && return + local data="${MEMORIZE_TEST_DATA:-$HOME/quran-asr-lab/data}" + "${MEMORIZE_TEST_PYTHON:-$HOME/quran-asr-lab/.venv/bin/python}" tools/memorize/stage_test_clips.py \ + --data "$data" --husary-audio "${MEMORIZE_HUSARY_AUDIO:-$data/../audio/husary_murattal}" \ + --text-lexicon "${MEMORIZE_TEXT_LEXICON:-$data/../cache/lexicon_v1.db}" +} + +tools/memorize/fetch_sherpa_onnx.sh +stage_model +stage_clips +if [ "$SUITE" = "engine" ]; then + ./gradlew :feature:memorize:engine-sherpa:assembleReleaseAndroidTest + APK=feature/memorize/engine-sherpa/build/outputs/apk/androidTest/release/engine-sherpa-release-androidTest.apk + PACKAGE=com.quran.mobile.feature.memorize.engine.sherpa.test + TAG=MemorizeBenchmark +else + ./gradlew :feature:memorize:assembleReleaseAndroidTest + APK=feature/memorize/build/outputs/apk/androidTest/release/memorize-release-androidTest.apk + PACKAGE=com.quran.mobile.feature.memorize.test + TAG=MemorizeSession +fi + +# The test APK instruments itself (it's a library's test), but Test Lab wants an app to install, +# with some code in it: a placeholder with one empty class. +host_apk() { + local sdk build_tools platform out=build/memorize-testlab-host + sdk=$(sed -n 's/^sdk.dir=//p' local.properties) + build_tools=$(ls -d "$sdk"/build-tools/*/ | sort -V | tail -1) + platform=$(ls -d "$sdk"/platforms/*/ | sort -V | tail -1) + mkdir -p "$out/src/host" "$out/classes" "$out/dex" + cat > "$out/AndroidManifest.xml" <<'EOF' + + + +EOF + echo 'package host; public final class Host {}' > "$out/src/host/Host.java" + "${JAVA_HOME:+$JAVA_HOME/bin/}javac" --release 11 -d "$out/classes" "$out/src/host/Host.java" + "$build_tools/d8" --min-api 24 --output "$out/dex" "$out/classes/host/Host.class" + "$build_tools/aapt2" link -o "$out/host-unsigned.apk" -I "$platform/android.jar" \ + --manifest "$out/AndroidManifest.xml" --min-sdk-version 24 --target-sdk-version 35 + (cd "$out/dex" && zip -q ../host-unsigned.apk classes.dex) + "$build_tools/zipalign" -f 4 "$out/host-unsigned.apk" "$out/host-aligned.apk" + "$build_tools/apksigner" sign --ks "$HOME/.android/debug.keystore" --ks-pass pass:android \ + --out "$out/host.apk" "$out/host-aligned.apk" + echo "$out/host.apk" +} + +case "$TARGET" in + testlab) + # low end (Galaxy A10), mid range (A54) and the Mi 11's Snapdragon 888 (Galaxy S21) by default; + # list devices with: gcloud firebase test android models list + if [ $# -gt 0 ]; then DEVICES=("$@"); else DEVICES=(a10,29 a54x,34 o1q,34); fi + ARGS=() + for d in "${DEVICES[@]}"; do + ARGS+=(--device "model=${d%%,*},version=${d##*,}") + done + HOST=$(host_apk | tail -1) + "$GCLOUD" firebase test android run --type instrumentation --app "$HOST" --test "$APK" \ + --test-runner-class androidx.test.runner.AndroidJUnitRunner \ + "${ARGS[@]}" --timeout 20m --no-use-orchestrator --results-history-name "memorize-$SUITE" + ;; + adb) + adb install -r -t "$APK" + adb shell am instrument -w -r "$PACKAGE/androidx.test.runner.AndroidJUnitRunner" + adb logcat -d -s "$TAG" + ;; + *) + echo "usage: $0 testlab [engine|session] [MODEL,VERSION ...] | adb [engine|session]" >&2 + exit 2 + ;; +esac diff --git a/tools/memorize/stage_test_clips.py b/tools/memorize/stage_test_clips.py new file mode 100644 index 0000000000..0462db4cab --- /dev/null +++ b/tools/memorize/stage_test_clips.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +"""Stages the audio of the on-device memorize tests into build/memorize-testlab/ (not in git): clips of +different professional reciters and styles, non-professional readers and non-native readers, and a +manifest saying where each clip starts in the Quran, how many words it covers, when each word ends +(when known) and what a session should make of it. + + professional QUD-Technologies/quran-alignment-benchmark (CC-BY-4.0), ~35 s segments with word times, + plus Husary (the app's own sura files) + reader sobolev210/quran-recitation-errors (MIT): non-professional readers, incl. real + wording mistakes + non_native RetaSy/quranic_audio_dataset (crowdsourced, non-Arabic speakers): correct recitations + of different countries, genders and ages, a different ayah, an unfinished ayah + +The audio stays local (and in private test runs); it is never committed. + +Needs numpy, soundfile and pyarrow, and ffmpeg on PATH: + python tools/memorize/stage_test_clips.py --data ~/quran-asr-lab/data \ + --husary-audio ~/quran-asr-lab/audio/husary_murattal --text-lexicon ~/quran-asr-lab/cache/lexicon_v1.db +""" +import argparse +import glob +import io +import json +import os +import re +import sqlite3 +import subprocess + +import numpy as np +import pyarrow.parquet as pq +import soundfile as sf + +ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..") +OUT = os.path.join(ROOT, "build", "memorize-testlab") +ASSETS = os.path.join(ROOT, "feature", "memorize", "src", "main", "assets", "memorize") +SR = 16_000 + +# QUD recordings: (id, label, seconds into the recording to look for an ayah start) +QUD = [ + ("afasy-baqarah", "Mishary Al-Afasy, murattal", 600), + ("abdulbasit-raad", "Abdul Basit, mujawwad", 120), + ("badri-juz-tabarak", "Abdul Qadir Badri, fast hadr", 60), + ("jaber-inshiqaq", "Ali Jaber, murattal", 0), + ("ayyub-juz-amma", "Muhammad Ayyub, murattal", 300), + ("mandour-taha", "Mandour, live recording with background noise", 120), + ("luhaidan-fatir", "Muhammad Al-Luhaidan, live, crushed and reverberant", 120), + ("minshawi-luqman", "Minshawi teaching class, children repeat each ayah", 60), +] +RETASY_SURAS = {"Al-Faatihah": 1, "Al-Ikhlas": 112, "An-Nas": 114, "Ayat al-Kursi": 2, "Al-Kafiroon": 109, + "Al-Falaq": 113, "Al-Kauthar": 108, "Al-Asr": 103, "Al-Masad": 111, "Al-Humazah": 104, + "Quraish": 106, "Al-Feel": 105, "Al-Maun": 107, "An-Nasr": 110, "At-Takathur": 102, + "Al-Qariah": 101} + +# written as escapes: typed in Arabic, the ranges are easily reversed by the editor's bidi +DIACRITICS = re.compile(r"[\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06ED\u0640\u08D3-\u08FF]") +UNIFY = str.maketrans({"أ": "ء", "إ": "ء", "ؤ": "ء", "ئ": "ء", "آ": "ءا", "ٱ": "ا", "ى": "ي", "ة": "ه", + "ٰ": "ا", "ۥ": "و", "ۦ": "ي", "\u0654": "ء", + "ی": "ي", "ک": "ك"}) + + +def skeleton(text): + """Letters only, spelling variants unified (Uthmani and standard spelling compare equal).""" + text = DIACRITICS.sub("", text.translate(UNIFY)) + return re.sub(r"(.)\1+", r"\1", re.sub(r"[^\u0621-\u064A]", "", text)) + + +def decode(data=None, path=None, start=0.0, duration=None): + # -nostdin would also stop ffmpeg reading audio given on stdin (it then outputs nothing) + cmd = ["ffmpeg", "-v", "error"] + ([] if data is not None else ["-nostdin"]) + if start: + cmd += ["-ss", f"{start:.3f}"] + if duration: + cmd += ["-t", f"{duration:.3f}"] + cmd += ["-i", path or "pipe:0", "-ac", "1", "-ar", str(SR), "-f", "s16le", "-"] + out = subprocess.run(cmd, input=data, check=True, capture_output=True).stdout + if not out: + raise ValueError(f"no audio decoded from {path or 'the given bytes'}") + return np.frombuffer(out, dtype=np.int16) + + +def write(name, pcm): + path = os.path.join(OUT, name) + os.makedirs(os.path.dirname(path), exist_ok=True) + sf.write(path, pcm, SR, subtype="PCM_16") + return name + + +class Lexicon: + def __init__(self, text_db): + con = sqlite3.connect(os.path.join(ASSETS, "lexicon_v1.db")) + self.count = dict(((s, a), n) for s, a, n in + con.execute("select sura, ayah, count(*) from words group by sura, ayah")) + # the app bundles a compact lexicon without the text; the full one has it + text = sqlite3.connect(text_db) + self.text = {(s, a): skeleton(t) for s, a, t in + text.execute("select sura, ayah, group_concat(uthmani, ' ') from words group by sura, ayah")} + + def find(self, sura, text): + """The ayah of `sura` whose text the clip's text is (or is part of). Standard spelling differs + from the Uthmani in a few letters (الرحمن / ٱلرَّحْمَـٰنِ): failing an exact match, the closest + within 1 letter in 8.""" + sk = skeleton(text) + if not sk: + return None + ayat = [(a, t) for (s, a), t in self.text.items() if s == sura] + for a, t in ayat: + if t == sk or (len(sk) >= 8 and sk in t): + return a + best = min(ayat, key=lambda at: (part_distance(sk, at[1]) + abs(len(at[1]) - len(sk)) * (len(sk) < 8), at[0])) + if part_distance(sk, best[1]) <= len(sk) / 8 and (len(sk) >= 8 or len(best[1]) == len(sk)): + return best[0] + return None + + +def part_distance(a, b): + """Edit distance from `a` to the closest part of `b`.""" + prev = [0] * (len(b) + 1) + for i, x in enumerate(a, 1): + cur = [i] + [0] * len(b) + for j, y in enumerate(b, 1): + cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y)) + prev = cur + return min(prev) + + +def qud_clips(data, lex): + path = glob.glob(os.path.join(data, "QUD-Technologies__quran-alignment-benchmark", "**", "*.parquet"), + recursive=True)[0] + clips = [] + for row in pq.read_table(path, columns=["id", "audio", "truth"]).to_pylist(): + spec = next((q for q in QUD if q[0] == row["id"]), None) + if spec is None: + continue + _, label, offset = spec + words = [(tuple(int(x) for x in w["word"].split(":")), w["start_s"], w["end_s"]) + for w in row["truth"]["words"] if re.fullmatch(r"\d+:\d+:\d+", w["word"])] + # the first ayah start after the offset; then the words in mushaf order for ~35 s, ending + # with an ayah (repeats in between, e.g. a class repeating the teacher, are part of it) + start = next(i for i, (k, s, _) in enumerate(words) if k[2] == 1 and s >= offset and k[0] != 1) + (sura, ayah, _), t0, _ = words[start] + # ~35 s, longer when a single (mujawwad) ayah takes more than that + for window in (35, 50, 70, 90): + first_end, expected = {}, [(sura, ayah, 1)] + for k, s, e in words[start:]: + first_end.setdefault(k, e) + if s - t0 > window: + break + while True: + s_, a_, w_ = expected[-1] + nxt = (s_, a_, w_ + 1) if w_ < lex.count[(s_, a_)] else (s_, a_ + 1, 1) + if nxt not in first_end: + break + expected.append(nxt) + # end with a complete ayah + while expected and expected[-1][2] != lex.count[expected[-1][:2]]: + expected.pop() + if expected: + break + if not expected: + print(f"{row['id']}: no complete ayah near {offset} s, skipped") + continue + end = max(first_end[k] for k in expected) + begin = max(0.0, t0 - 0.3) + pcm = decode(row["audio"]["bytes"], start=begin, duration=end + 0.6 - begin) + clips.append({ + "file": write(f"clips/qud_{row['id']}.wav", pcm), "group": "professional", "label": label, + "source": "QUD-Technologies/quran-alignment-benchmark (CC-BY-4.0)", "sura": sura, "ayah": ayah, + "words": len(expected), "word_ends_ms": [round((first_end[k] - begin) * 1000) for k in expected], + "expect": "complete", + }) + return clips + + +def husary_clips(husary_audio, lex): + timings = sqlite3.connect(os.path.join(ASSETS, "timings", "husary_murattal_wbw_v1.db")) + # Al-Mulk 1-5, from just before 67:1 to just after 67:5 (67:6 starts 1.4 s later) + begin, end = 8.699, 126.0 + ends = [] + for ayah in range(1, 6): + (words,) = timings.execute("select words from timings where sura=67 and ayah=?", (ayah,)).fetchone() + ends += [int(w.split(":")[2]) - round(begin * 1000) for w in words.split(",")] + write("mulk_1_5_husary.wav", decode(path=os.path.join(husary_audio, "067.mp3"), start=begin, duration=end - begin)) + # the speech engine benchmark: the first 30 s of Al-Fatiha (isti'adha, basmala, 1:2...) + write("fatiha_husary_30s.wav", decode(path=os.path.join(husary_audio, "001.mp3"), duration=30.0)) + # continuous recitation into the next suras (as in taraweeh): Al-Ikhlas, Al-Falaq and An-Nas + # one after the other, each sura file with its basmala + pcm, ends_all, words = [], [], 0 + for sura in (112, 113, 114): + offset = sum(len(p) for p in pcm) * 1000 // SR + audio = decode(path=os.path.join(husary_audio, f"{sura:03d}.mp3")) + for (words_text,) in timings.execute("select words from timings where sura=? order by ayah", (sura,)): + ends_all += [int(w.split(":")[2]) + offset for w in words_text.split(",")] + words += sum(n for (s, _), n in lex.count.items() if s == sura) + pcm.append(audio) + write("ikhlas_to_nas_husary.wav", np.concatenate(pcm)) + return [{ + "file": "mulk_1_5_husary.wav", "group": "professional", "label": "Mahmoud Khalil Al-Husary, murattal", + "source": "Husary murattal sura files (the app's own audio)", "sura": 67, "ayah": 1, + "words": sum(lex.count[(67, a)] for a in range(1, 6)), "word_ends_ms": ends, "expect": "complete", + }, { + "file": "ikhlas_to_nas_husary.wav", "group": "continuous", "label": "Al-Husary, Al-Ikhlas to An-Nas in a row", + "source": "Husary murattal sura files (the app's own audio)", "sura": 112, "ayah": 1, + "words": words, "word_ends_ms": ends_all, "expect": "complete", + }] + + +def reader_clips(data, lex): + base = os.path.join(data, "sobolev210__quran-recitation-errors") + rows = [json.loads(l) for l in open(os.path.join(base, "metadata.jsonl"), encoding="utf-8")] + rows = [r for r in rows if r["riwayah"] == "Hafs"] + clips, seen = [], set() + + def ayah_of(r): + return lex.find(int(r["surah"]), r["text"]) or int(r["ayah"]) + + def add(r, expect, label): + sura = int(r["surah"]) + ayah = ayah_of(r) + pcm = decode(path=os.path.join(base, r["file_name"])) + clips.append({ + "file": write(f"clips/reader_{len(clips) + 1}.wav", pcm), "group": "reader", "label": label, + "source": "sobolev210/quran-recitation-errors (MIT)", "sura": sura, "ayah": ayah, + "words": lex.count[(sura, ayah)], "word_ends_ms": None, "expect": expect, + }) + + correct = sorted((r for r in rows if not r["errors"] and 3 <= sf.info(os.path.join(base, r["file_name"])).duration <= 15), + key=lambda r: (r["surah"], r["recording_id"])) + suras = set() + for r in correct: + if r["recording_id"] in seen or r["surah"] in suras or lex.count[(int(r["surah"]), ayah_of(r))] < 4: + continue + seen.add(r["recording_id"]) + suras.add(r["surah"]) + add(r, "complete", "non-professional reader, correct") + if len(clips) == 4: + break + for r in rows: + if any("Wording" in v for v in r["errors"].values()): + add(r, "mistake", "non-professional reader, wrong word") + return clips + + +def non_native_clips(data, lex): + rows = [] + for f in sorted(glob.glob(os.path.join(data, "RetaSy__quranic_audio_dataset", "**", "*.parquet"), recursive=True)): + rows += pq.read_table(f, columns=["audio", "Surah", "Aya", "final_label", "reciter_id", "reciter_country", + "reciter_gender", "reciter_age", "reciter_qiraah", "duration_ms"]).to_pylist() + # "Aya" is the text of the ayah the reciter was asked for + rows = [r for r in rows if r["Surah"] in RETASY_SURAS and r["Aya"] + and 2_000 <= (r["duration_ms"] or 0) <= 20_000 and r["reciter_qiraah"] in ("hafs", None)] + clips = [] + + def add(r, expect, what): + sura = RETASY_SURAS[r["Surah"]] + # Ayat al-Kursi's phrases recur nearby (2:284 opens like a phrase of it) + ayah = 255 if r["Surah"] == "Ayat al-Kursi" else lex.find(sura, r["Aya"]) + if ayah is None: # e.g. the isti'adha + return False + who = ", ".join(x for x in (r["reciter_country"], r["reciter_gender"], r["reciter_age"]) + if x and x != "Unknown") or "unknown speaker" + pcm = decode(r["audio"]["bytes"]) + clips.append({ + "file": write(f"clips/non_native_{len(clips) + 1}.wav", pcm), "group": "non_native", + "label": f"non-native reader ({who}), {what}", + "source": "RetaSy/quranic_audio_dataset (local use only)", "sura": sura, "ayah": ayah, + "words": lex.count[(sura, ayah)], "word_ends_ms": None, "expect": expect, + }) + return True + + # correct recitations: the youngest first, then as many countries and both genders as possible + correct = [r for r in rows if r["final_label"] == "correct" and r["reciter_qiraah"] == "hafs"] + correct.sort(key=lambda r: (r["reciter_age"] != "14-18", r["reciter_country"] or "", r["reciter_id"])) + reciters, countries, genders = set(), {}, {} + for r in correct: + country, gender = r["reciter_country"], r["reciter_gender"] + if r["reciter_id"] in reciters or countries.get(country, 0) >= 1 or genders.get(gender, 0) >= 4: + continue + if add(r, "complete", "correct"): + reciters.add(r["reciter_id"]) + countries[country] = countries.get(country, 0) + 1 + genders[gender] = genders.get(gender, 0) + 1 + if len(clips) == 8: + break + for label, expect, what, n in (("not_match_aya", "mistake", "recited a different ayah", 2), + ("in_complete", "incomplete", "stopped before the end", 1)): + for r in [r for r in rows if r["final_label"] == label][:n]: + add(r, expect, what) + return clips + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--data", required=True, help="directory with the downloaded datasets") + ap.add_argument("--husary-audio", required=True, help="directory with Husary murattal 001.mp3 ... 114.mp3") + ap.add_argument("--text-lexicon", required=True, + help="lexicon built without --compact (tools/memorize/build_lexicon.py), for the Uthmani text") + a = ap.parse_args() + lex = Lexicon(a.text_lexicon) + clips = husary_clips(a.husary_audio, lex) + qud_clips(a.data, lex) + reader_clips(a.data, lex) \ + + non_native_clips(a.data, lex) + os.makedirs(os.path.join(OUT, "clips"), exist_ok=True) + with open(os.path.join(OUT, "clips", "manifest.json"), "w", encoding="utf-8") as f: + json.dump({"clips": clips}, f, ensure_ascii=False, indent=1) + total = sum(sf.info(os.path.join(OUT, c["file"])).duration for c in clips) + for c in clips: + print(f"{c['group']:12s} {c['sura']:3d}:{c['ayah']:<3d} {c['words']:3d} words {c['expect']:10s} {c['label']}") + print(f"{len(clips)} clips, {total / 60:.1f} min of audio in {OUT}") + + +if __name__ == "__main__": + main()