diff --git a/lib/screens/lyrics_share_screen.dart b/lib/screens/lyrics_share_screen.dart index 227f98029..fb0d6433c 100644 --- a/lib/screens/lyrics_share_screen.dart +++ b/lib/screens/lyrics_share_screen.dart @@ -10,8 +10,8 @@ import 'package:mornye/theme/app_tokens.dart'; import 'package:mornye/theme/cover_palette.dart'; import 'package:mornye/utils/lyrics_parser.dart'; import 'package:mornye/utils/lyrics_timeline.dart'; +import 'package:mornye/utils/text_direction.dart'; import 'package:mornye/utils/widget_capture.dart'; -import 'package:mornye/widgets/aligned_lyric_pronunciation.dart'; import 'package:mornye/widgets/app_icon.dart'; import 'package:mornye/widgets/app_icon_button.dart'; import 'package:mornye/widgets/app_shape.dart'; @@ -621,10 +621,7 @@ class _LineChoice extends StatelessWidget { Expanded( child: Text( line.text, - textDirection: lyricTextDirection( - line.text, - Directionality.of(context), - ), + textDirection: strongTextDirection(line.text), style: (line.background ? theme.textTheme.bodyMedium @@ -692,10 +689,14 @@ class LyricsShareCard extends StatelessWidget { final secondary = foreground.withValues(alpha: 0.7); final fontSize = fontSizeFor(lines); final scheme = Theme.of(context).colorScheme; - final ambientDirection = Directionality.of(context); - final cardDirection = lines.any((line) => isRtlLyricText(line.text)) - ? TextDirection.rtl - : ambientDirection; + // A card shrunk to fit keeps the side its first line reads from. Each + // line reads in its own direction. + final cardDirection = + lines + .map((line) => strongTextDirection(line.text)) + .nonNulls + .firstOrNull ?? + Directionality.of(context); return MediaQuery.withNoTextScaling( child: SizedBox.fromSize( size: lyricsShareCardSize, @@ -797,10 +798,11 @@ class LyricsShareCard extends StatelessWidget { ), child: Text( line.text, - textDirection: lyricTextDirection( - line.text, - ambientDirection, - ), + textDirection: + strongTextDirection( + line.text, + ) ?? + cardDirection, style: TextStyle( color: line.background ? secondary diff --git a/lib/utils/text_direction.dart b/lib/utils/text_direction.dart new file mode 100644 index 000000000..93edc4cc6 --- /dev/null +++ b/lib/utils/text_direction.dart @@ -0,0 +1,146 @@ +import 'package:flutter/painting.dart' show TextDirection; + +/// The direction of [text]'s first strong character, the rule the Unicode +/// bidirectional algorithm uses for a paragraph: right to left for a +/// Hebrew, Arabic or other right-to-left letter, left to right for any +/// other letter. Digits, punctuation, symbols, spaces, marks and a byte +/// order mark decide nothing, so text of only those returns null and the +/// caller chooses. +TextDirection? strongTextDirection(String text) { + for (final rune in text.runes) { + if (rune < 0x80) { + // Latin letters, the usual first character, decide at once. + if ((rune | 0x20) >= 0x61 && (rune | 0x20) <= 0x7A) { + return TextDirection.ltr; + } + continue; + } + if (_within(_weak, rune)) continue; + return _within(_rightToLeft, rune) ? TextDirection.rtl : TextDirection.ltr; + } + return null; +} + +/// [strongTextDirection] of each of [lines]. A line without a strong +/// character, such as an instrumental break or "...", takes the direction +/// of the line before it, else of the first one after it with one, so it +/// sits beside its neighbours. All null when no line has a strong +/// character. +List lyricLineDirections(Iterable lines) { + final directions = [for (final line in lines) strongTextDirection(line)]; + TextDirection? previous; + for (var index = 0; index < directions.length; index++) { + previous = directions[index] ??= previous; + } + TextDirection? next; + for (var index = directions.length - 1; index >= 0; index--) { + next = directions[index] ??= next; + } + return directions; +} + +/// Whether [rune] falls in one of the sorted, inclusive [ranges]. +bool _within(List ranges, int rune) { + var low = 0; + var high = ranges.length ~/ 2 - 1; + while (low <= high) { + final middle = (low + high) >> 1; + if (rune < ranges[middle * 2]) { + high = middle - 1; + } else if (rune > ranges[middle * 2 + 1]) { + low = middle + 1; + } else { + return true; + } + } + return false; +} + +/// Characters past ASCII that are not strong: combining marks, digits and +/// number signs, punctuation, symbols, spaces and format characters, +/// including those inside the right-to-left blocks below. +const _weak = [ + 0x0080, 0x00BF, // Latin-1 controls, punctuation and signs + 0x00D7, 0x00D7, // multiplication sign + 0x00F7, 0x00F7, // division sign + 0x02B9, 0x02BA, // modifier primes + 0x02C2, 0x02CF, // modifier symbols + 0x02D2, 0x02DF, + 0x02E5, 0x02ED, + 0x02EF, 0x02FF, + 0x0300, 0x036F, // combining diacritics + 0x0374, 0x0375, // Greek numeral signs + 0x037E, 0x037E, // Greek question mark + 0x0384, 0x0385, // Greek tonos + 0x0387, 0x0387, // Greek ano teleia + 0x0483, 0x0489, // Cyrillic combining marks + 0x0591, 0x05BD, // Hebrew points and accents + 0x05BF, 0x05BF, + 0x05C1, 0x05C2, + 0x05C4, 0x05C5, + 0x05C7, 0x05C7, + 0x0600, 0x0607, // Arabic number signs + 0x0609, 0x060A, // Arabic per mille and per ten thousand + 0x060C, 0x060C, // Arabic comma + 0x060E, 0x061A, // Arabic poetic signs and marks + 0x064B, 0x065F, // Arabic vowel marks + 0x0660, 0x066C, // Arabic-Indic digits and separators + 0x0670, 0x0670, // Arabic superscript alef + 0x06D6, 0x06E4, // Quranic marks + 0x06E7, 0x06ED, + 0x06F0, 0x06F9, // extended Arabic-Indic digits + 0x0711, 0x0711, // Syriac superscript alaph + 0x0730, 0x074A, // Syriac marks + 0x07A6, 0x07B0, // Thaana vowels + 0x07EB, 0x07F3, // NKo tone marks + 0x07F6, 0x07F9, // NKo symbols + 0x07FD, 0x07FD, + 0x0816, 0x0819, // Samaritan marks + 0x081B, 0x0823, + 0x0825, 0x0827, + 0x0829, 0x082D, + 0x0859, 0x085B, // Mandaic marks + 0x0890, 0x0891, // Arabic pound and piastre marks + 0x0897, 0x089F, // Arabic marks + 0x08CA, 0x08FF, + 0x2000, 0x200D, // spaces, zero-width space and joiners + 0x2010, 0x2BFF, // punctuation, symbols, arrows and shapes + 0x2E00, 0x2FFF, // supplemental punctuation, CJK radicals + 0x3000, 0x3004, // CJK space and punctuation + 0x3008, 0x3020, + 0x302A, 0x3030, + 0x3036, 0x3037, + 0x303D, 0x303F, + 0x3099, 0x309C, // kana voicing marks + 0x30A0, 0x30A0, + 0x30FB, 0x30FB, // katakana middle dot + 0xFB1E, 0xFB1E, // Hebrew point judeo-spanish varika + 0xFB29, 0xFB29, // Hebrew alternative plus sign + 0xFD3E, 0xFD3F, // ornate parentheses + 0xFDCF, 0xFDCF, + 0xFDFD, 0xFDFF, + 0xFE00, 0xFE6F, // variation selectors, small and vertical forms + 0xFEFF, 0xFEFF, // byte order mark + 0xFF00, 0xFF20, // fullwidth punctuation and digits + 0xFF3B, 0xFF40, + 0xFF5B, 0xFF65, + 0xFFE0, 0xFFFF, + 0x10E60, 0x10E7E, // Rumi numerals + 0x1E8D0, 0x1E8D6, // Mende Kikakui marks + 0x1E944, 0x1E94A, // Adlam marks + 0x1EEF0, 0x1EEF1, + 0x1F000, 0x1FBFF, // emoji, game and legacy symbols + 0xE0000, 0xE0FFF, // tags and variation selectors +]; + +/// The right-to-left blocks: Hebrew through Arabic Extended-A, their +/// presentation forms, and the historic and African right-to-left scripts. +/// The right-to-left mark counts too. +const _rightToLeft = [ + 0x0590, 0x08FF, // Hebrew, Arabic, Syriac, Thaana, NKo and their kin + 0x200F, 0x200F, // right-to-left mark + 0xFB1D, 0xFDFF, // Hebrew and Arabic presentation forms + 0xFE70, 0xFEFC, // Arabic presentation forms B + 0x10800, 0x10FFF, // historic right-to-left scripts + 0x1E800, 0x1EFFF, // Mende Kikakui, Adlam and Arabic mathematical letters +]; diff --git a/lib/widgets/aligned_lyric_pronunciation.dart b/lib/widgets/aligned_lyric_pronunciation.dart index b98ed14f7..85765bea2 100644 --- a/lib/widgets/aligned_lyric_pronunciation.dart +++ b/lib/widgets/aligned_lyric_pronunciation.dart @@ -3,34 +3,15 @@ import 'dart:math' as math; import 'package:material_ui/material_ui.dart'; import 'package:mornye/widgets/lyric_supplement_transition.dart'; import 'package:mornye/utils/lyrics_parser.dart'; - -final _rtlLyricCharacter = RegExp( - r'[\u0590-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF\u{10800}-\u{10FFF}\u{1EE00}-\u{1EEFF}]', - unicode: true, -); - -/// Whether [text] contains right-to-left script characters (such as Arabic or -/// Hebrew). -bool isRtlLyricText(String text) => _rtlLyricCharacter.hasMatch(text); - -/// Resolves the paragraph direction for [text], falling back to [ambient] -/// when the line does not use a right-to-left script. -TextDirection lyricTextDirection( - String text, [ - TextDirection ambient = TextDirection.ltr, -]) => isRtlLyricText(text) ? TextDirection.rtl : ambient; +import 'package:mornye/utils/text_direction.dart'; /// Keeps each pronunciation phrase under the lyric with the same start time. /// Only shared word boundaries are used; line-only timing cannot identify /// which original characters a pronunciation belongs to. class LyricPronunciationLayout { final List<_PronunciationRow> _rows; - final TextDirection textDirection; - const LyricPronunciationLayout._( - this._rows, [ - this.textDirection = TextDirection.ltr, - ]); + const LyricPronunciationLayout._(this._rows); static const _phraseGap = 4.0; static const _pronunciationGap = 2.0; @@ -59,12 +40,14 @@ class LyricPronunciationLayout { }) { final original = line.words; final pronunciation = line.romanizationWords; + // Phrase columns run left to right. A right-to-left line keeps its + // pronunciation as a row of its own under it. if (original.isEmpty || pronunciation.isEmpty || !maxWidth.isFinite || maxWidth <= 0 || - isRtlLyricText(line.text) || - isRtlLyricText(line.romanization ?? '')) { + strongTextDirection(line.text) == TextDirection.rtl || + strongTextDirection(line.romanization ?? '') == TextDirection.rtl) { return null; } String normalize(String text) => text.replaceAll(_whitespaceRun, ''); @@ -149,7 +132,7 @@ class LyricPronunciationLayout { } rows.add(_PronunciationRow(groups, primaryHeight, pronunciationHeight)); painter.dispose(); - return LyricPronunciationLayout._(rows, textDirection); + return LyricPronunciationLayout._(rows); } static List _sliceWords( diff --git a/lib/widgets/desktop/desktop_mini_player.dart b/lib/widgets/desktop/desktop_mini_player.dart index 10a02cc7e..ed0c52df1 100644 --- a/lib/widgets/desktop/desktop_mini_player.dart +++ b/lib/widgets/desktop/desktop_mini_player.dart @@ -435,9 +435,10 @@ class _MiniPlayerLyricsState extends ConsumerState<_MiniPlayerLyrics> else Text( lines[current].text, - textDirection: lyricTextDirection( + // Each line reads, and aligns, in its own + // direction. + textDirection: strongTextDirection( lines[current].text, - Directionality.of(context), ), style: textTheme.titleLarge?.copyWith( fontWeight: FontWeight.w700, @@ -449,10 +450,7 @@ class _MiniPlayerLyricsState extends ConsumerState<_MiniPlayerLyrics> if (next >= 0) Text( lines[next].text, - textDirection: lyricTextDirection( - lines[next].text, - Directionality.of(context), - ), + textDirection: strongTextDirection(lines[next].text), style: textTheme.bodyLarge?.copyWith( color: colorScheme.onSurfaceVariant, ), diff --git a/lib/widgets/desktop/desktop_player_bar.dart b/lib/widgets/desktop/desktop_player_bar.dart index 10a12ea89..3f118ef7d 100644 --- a/lib/widgets/desktop/desktop_player_bar.dart +++ b/lib/widgets/desktop/desktop_player_bar.dart @@ -17,6 +17,7 @@ import 'package:mornye/services/cast_output.dart'; import 'package:mornye/utils/lyrics_parser.dart'; import 'package:mornye/utils/lyrics_timeline.dart'; import 'package:mornye/utils/string_utils.dart'; +import 'package:mornye/utils/text_direction.dart'; import 'package:mornye/widgets/app_icon.dart'; import 'package:mornye/widgets/app_icon_button.dart'; import 'package:mornye/widgets/app_loading_indicator.dart'; diff --git a/lib/widgets/lyrics_editor_sheet.dart b/lib/widgets/lyrics_editor_sheet.dart index fc210cf20..76b071b5b 100644 --- a/lib/widgets/lyrics_editor_sheet.dart +++ b/lib/widgets/lyrics_editor_sheet.dart @@ -15,7 +15,7 @@ import 'package:mornye/utils/desktop_platform.dart'; import 'package:mornye/utils/logger.dart'; import 'package:mornye/utils/lyrics_draft.dart'; import 'package:mornye/utils/string_utils.dart'; -import 'package:mornye/widgets/aligned_lyric_pronunciation.dart'; +import 'package:mornye/utils/text_direction.dart'; import 'package:mornye/widgets/app_action_button.dart'; import 'package:mornye/widgets/app_bottom_sheet.dart'; import 'package:mornye/widgets/app_icon.dart'; @@ -97,6 +97,8 @@ class LyricsEditorSheet extends ConsumerStatefulWidget { class _EditorLine { _EditorLine(this.base) : time = base.time { text.text = base.text; + direction.value = strongTextDirection(base.text); + text.addListener(_updateDirection); } final LyricsDraftLine base; @@ -105,11 +107,19 @@ class _EditorLine { final key = GlobalKey(); Duration? time; + /// The line's own direction, by its first letter; null follows the + /// editor's. It changes only when that letter's script does, so typing + /// does not rebuild the field. + final direction = ValueNotifier(null); + + void _updateDirection() => direction.value = strongTextDirection(text.text); + LyricsDraftLine get draft => base.copyWith(time: time, clearTime: time == null, text: text.text); void dispose() { text.dispose(); + direction.dispose(); focus.dispose(); } } @@ -728,15 +738,12 @@ class _LyricsEditorRow extends StatelessWidget { timeChip, const SizedBox(width: 4), Expanded( - child: ValueListenableBuilder( - valueListenable: line.text, - builder: (context, value, _) => TextField( + child: ValueListenableBuilder( + valueListenable: line.direction, + builder: (context, direction, _) => TextField( controller: line.text, focusNode: line.focus, - textDirection: lyricTextDirection( - value.text, - Directionality.of(context), - ), + textDirection: direction, minLines: 1, maxLines: null, // The field grows with its text, so it never needs to diff --git a/lib/widgets/player_lyric_preview.dart b/lib/widgets/player_lyric_preview.dart index 3353ecbba..b3ed95bf6 100644 --- a/lib/widgets/player_lyric_preview.dart +++ b/lib/widgets/player_lyric_preview.dart @@ -17,6 +17,7 @@ import 'package:mornye/theme/mornye_theme.dart'; import 'package:mornye/utils/lyrics_parser.dart'; import 'package:mornye/utils/lyrics_timeline.dart'; import 'package:mornye/utils/synced_lyrics_scroll.dart'; +import 'package:mornye/utils/text_direction.dart'; import 'package:mornye/widgets/lyric_line_scroller.dart'; import 'package:mornye/widgets/player_lyrics.dart'; @@ -356,11 +357,38 @@ class _LyricPreviewLineState extends ConsumerState<_LyricPreviewLine> { ); } else if (text == line.text.trim() && line.hasWordTiming) { // A long line slides to keep the sung words in view. - child = ClipRect( + child = Directionality( key: ValueKey('word-${line.time.inMilliseconds}'), + textDirection: strongTextDirection(text) ?? Directionality.of(context), + child: ClipRect( + child: LyricLineScroller( + text: line.words.map((word) => word.text).join(), + words: line.words, + style: style, + start: line.time, + end: line.end, + nextStart: nextStart, + position: position, + advancing: advancing, + speed: speed, + child: WordTimedLyricLine( + line: line, + initialPosition: position, + seekPreview: widget.seekPreview, + style: style, + maxLines: 1, + ), + ), + ), + ); + } else { + // The line reads, and a long one slides, in its own direction: a + // right-to-left line starts at its right edge and moves rightwards. + child = Directionality( + key: ValueKey('line-${line.time.inMilliseconds}-$text'), + textDirection: strongTextDirection(text) ?? Directionality.of(context), child: LyricLineScroller( - text: line.words.map((word) => word.text).join(), - words: line.words, + text: text, style: style, start: line.time, end: line.end, @@ -368,34 +396,15 @@ class _LyricPreviewLineState extends ConsumerState<_LyricPreviewLine> { position: position, advancing: advancing, speed: speed, - child: WordTimedLyricLine( - line: line, - initialPosition: position, - seekPreview: widget.seekPreview, - style: style, + child: Text( + text, maxLines: 1, + softWrap: false, + overflow: TextOverflow.ellipsis, + style: style, ), ), ); - } else { - child = LyricLineScroller( - key: ValueKey('line-${line.time.inMilliseconds}-$text'), - text: text, - style: style, - start: line.time, - end: line.end, - nextStart: nextStart, - position: position, - advancing: advancing, - speed: speed, - child: Text( - text, - maxLines: 1, - softWrap: false, - overflow: TextOverflow.ellipsis, - style: style, - ), - ); } final onTap = blank ? null : widget.onTap; diff --git a/lib/widgets/player_lyrics.dart b/lib/widgets/player_lyrics.dart index 0957c46b7..ab714e031 100644 --- a/lib/widgets/player_lyrics.dart +++ b/lib/widgets/player_lyrics.dart @@ -23,9 +23,8 @@ import 'package:mornye/utils/desktop_platform.dart'; import 'package:mornye/utils/lyrics_parser.dart'; import 'package:mornye/utils/lyrics_timeline.dart'; import 'package:mornye/utils/synced_lyrics_scroll.dart'; +import 'package:mornye/utils/text_direction.dart'; import 'package:mornye/widgets/aligned_lyric_pronunciation.dart'; -export 'package:mornye/widgets/aligned_lyric_pronunciation.dart' - show isRtlLyricText, lyricTextDirection; import 'package:mornye/widgets/lyric_blur.dart'; import 'package:mornye/widgets/lyric_supplement_transition.dart'; import 'package:mornye/widgets/lyric_scroll_motion.dart'; @@ -207,6 +206,10 @@ class _SyncedLyricsViewState extends ConsumerState _ => false, }; static const double _estimatedLyricExtent = 64; + + /// Each line's own direction, worked out once for these lyrics; null + /// follows the app's. + List _lineDirections = const []; _LyricExtentSnapshot? _lineExtents; List<(double, double, double)> _lineMeasurements = []; List _pronunciationLayouts = []; @@ -406,6 +409,7 @@ class _SyncedLyricsViewState extends ConsumerState _lines = lyricsWithDisplayEnds( lyricsTimelineWithGaps(lyricsShiftedBy(widget.lyrics.lines, _offset)), ); + _lineDirections = lyricLineDirections(_lines.map((line) => line.text)); _timeline = LyricTimelineIndex(_lines); _rowReveal.stop(); _revealFrom = _revealTo = [ @@ -734,6 +738,8 @@ class _SyncedLyricsViewState extends ConsumerState _measurementRevision++; return; } + final lineDirection = _lineDirections[index] ?? direction; + painter.textDirection = lineDirection; painter.text = TextSpan( text: line.text, style: _primaryLyricStyle(context, background: line.isBackground), @@ -748,6 +754,7 @@ class _SyncedLyricsViewState extends ConsumerState context, line, )) { + painter.textDirection = strongTextDirection(text) ?? lineDirection; painter.text = TextSpan(text: text, style: style); painter.layout(maxWidth: width); if (translation) { @@ -763,7 +770,7 @@ class _SyncedLyricsViewState extends ConsumerState pronunciationStyle: style, maxWidth: width, textScaler: scaler, - textDirection: direction, + textDirection: lineDirection, locale: locale, ); if (aligned != null) { @@ -1193,6 +1200,7 @@ class _SyncedLyricsViewState extends ConsumerState _rowInputs = rowInputs; _rowsRevision++; } + final ambientDirection = Directionality.of(context); final list = _lyricList( revision: _rowsRevision, controller: _scroll, @@ -1214,6 +1222,9 @@ class _SyncedLyricsViewState extends ConsumerState final line = lines[index]; final leadIndex = _displayLayout.leadForLine[index]; final textAlign = _lyricTextAlign(context, lines[leadIndex]); + // Each line reads in its own direction: a Latin line in an + // Arabic song stays left to right, and the reverse. + final lineDirection = _lineDirections[index] ?? ambientDirection; // A row about to open is built now: no later frame of its // reveal rebuilds it. if (rowVisibility[index] == 0 && @@ -1235,6 +1246,7 @@ class _SyncedLyricsViewState extends ConsumerState return _revealRow( index, textAlign, + lineDirection, Padding( padding: EdgeInsets.symmetric( vertical: context.tokens.lyricsLinePaddingV, @@ -1296,6 +1308,7 @@ class _SyncedLyricsViewState extends ConsumerState line, content, color, + direction: lineDirection, visibility: visibility, pronunciationLayout: mornye ? _pronunciationLayouts[index] @@ -1366,6 +1379,7 @@ class _SyncedLyricsViewState extends ConsumerState return _revealRow( index, textAlign, + lineDirection, Padding( padding: _linePadding(index), child: TvTapTarget( @@ -1391,7 +1405,7 @@ class _SyncedLyricsViewState extends ConsumerState (textAlign == TextAlign.end ? AlignmentDirectional.centerEnd : AlignmentDirectional.centerStart) - .resolve(Directionality.of(context)), + .resolve(lineDirection), duration: motion, curve: Curves.easeOutCubic, child: AnimatedOpacity( @@ -1419,7 +1433,13 @@ class _SyncedLyricsViewState extends ConsumerState ); } - Widget _revealRow(int index, TextAlign align, Widget child) { + /// [child] and its reveal, laid out in [direction], the line's own. + Widget _revealRow( + int index, + TextAlign align, + TextDirection direction, + Widget child, + ) { final AlignmentGeometry alignment = align == TextAlign.end ? AlignmentDirectional.topEnd : align == TextAlign.center @@ -1436,31 +1456,34 @@ class _SyncedLyricsViewState extends ConsumerState ); return KeyedSubtree( key: _lineKeys[index], - child: !_lines[index].isBackground && _lines[index].text.isNotEmpty - ? child - // Only these rows open and close. They follow the reveal clock - // themselves, so the other rows are not rebuilt on its frames. - : ListenableBuilder( - listenable: _rowReveal, - child: fullHeight, - builder: (context, fullHeight) { - final visibility = _rowVisibility[index]; - return IgnorePointer( - ignoring: visibility < 1, - child: _lines[index].isBackground - ? LyricBackingTransition( - visibility: visibility, - alignment: alignment, - child: fullHeight!, - ) - : LyricSupplementTransition( - visibility: visibility, - alignment: alignment, - child: fullHeight!, - ), - ); - }, - ), + child: Directionality( + textDirection: direction, + child: !_lines[index].isBackground && _lines[index].text.isNotEmpty + ? child + // Only these rows open and close. They follow the reveal clock + // themselves, so the other rows are not rebuilt on its frames. + : ListenableBuilder( + listenable: _rowReveal, + child: fullHeight, + builder: (context, fullHeight) { + final visibility = _rowVisibility[index]; + return IgnorePointer( + ignoring: visibility < 1, + child: _lines[index].isBackground + ? LyricBackingTransition( + visibility: visibility, + alignment: alignment, + child: fullHeight!, + ) + : LyricSupplementTransition( + visibility: visibility, + alignment: alignment, + child: fullHeight!, + ), + ); + }, + ), + ), ); } diff --git a/lib/widgets/player_lyrics_line_style.dart b/lib/widgets/player_lyrics_line_style.dart index 2f49ce6d3..7c5efadf8 100644 --- a/lib/widgets/player_lyrics_line_style.dart +++ b/lib/widgets/player_lyrics_line_style.dart @@ -62,6 +62,10 @@ TextAlign _lyricTextAlign(BuildContext context, LyricLine line) { return voice.index.isEven ? TextAlign.start : TextAlign.end; } +/// [textAlign] of a line in [lineDirection], for a translation or +/// pronunciation under it that reads in [supplementDirection]: it stays on +/// the line's side, so an English translation sits under the right edge of +/// an Arabic line. TextAlign _supplementTextAlign( TextAlign textAlign, TextDirection lineDirection, @@ -77,11 +81,31 @@ TextAlign _supplementTextAlign( }; } +/// A translation or pronunciation [text] in its own direction, on the side +/// of a line in [lineDirection]. +Widget _supplementText( + String text, + TextDirection lineDirection, + TextAlign textAlign, + TextStyle style, +) { + final direction = strongTextDirection(text) ?? lineDirection; + return Text( + text, + textDirection: direction, + textAlign: _supplementTextAlign(textAlign, lineDirection, direction), + style: style, + ); +} + +/// [primary] with the line's pronunciation and translation under it. +/// [direction] is the line's own, which the caller lays the row out in. Widget _withLyricSupplements( BuildContext context, LyricLine line, Widget primary, Color color, { + required TextDirection direction, required Offset visibility, required LyricPronunciationLayout? pronunciationLayout, required TextAlign textAlign, @@ -89,13 +113,11 @@ Widget _withLyricSupplements( Widget Function(String, List, TextStyle)? timedSupplementText, }) { if (line.romanization == null && line.translation == null) return primary; - final ambientDirection = Directionality.of(context); - final lineDirection = lyricTextDirection(line.text, ambientDirection); - final AlignmentGeometry alignment = (switch (textAlign) { + final AlignmentGeometry alignment = switch (textAlign) { TextAlign.end => AlignmentDirectional.topEnd, TextAlign.center => Alignment.topCenter, _ => AlignmentDirectional.topStart, - }).resolve(lineDirection); + }; final supplements = _lyricSupplements(context, line).toList(); Widget withSupplements(Widget primary, {bool aligned = false}) => Column( crossAxisAlignment: CrossAxisAlignment.stretch, @@ -111,15 +133,11 @@ Widget _withLyricSupplements( padding: const EdgeInsets.only(top: 6), child: words.isNotEmpty && timedSupplementText != null ? timedSupplementText(text, words, style) - : Text( + : _supplementText( text, - textDirection: lyricTextDirection(text, ambientDirection), - textAlign: _supplementTextAlign( - textAlign, - lineDirection, - lyricTextDirection(text, ambientDirection), - ), - style: style.copyWith( + direction, + textAlign, + style.copyWith( color: color.withValues(alpha: color.a * 0.8), ), ), diff --git a/lib/widgets/player_lyrics_section.dart b/lib/widgets/player_lyrics_section.dart index 1b107aeaa..4e2740092 100644 --- a/lib/widgets/player_lyrics_section.dart +++ b/lib/widgets/player_lyrics_section.dart @@ -8,6 +8,7 @@ import 'package:mornye/providers/settings_provider.dart'; import 'package:mornye/theme/mornye_theme.dart'; import 'package:mornye/utils/lyrics_parser.dart'; import 'package:mornye/utils/playback_seek_preview.dart'; +import 'package:mornye/utils/text_direction.dart'; import 'package:mornye/widgets/app_icon.dart'; import 'package:mornye/widgets/app_loading_indicator.dart'; import 'package:mornye/widgets/app_snack_bar.dart'; @@ -17,6 +18,10 @@ import 'package:mornye/widgets/lyrics_options_activity.dart'; import 'package:mornye/widgets/player_lyrics.dart'; import 'package:mornye/widgets/lyrics_text_scale.dart'; +/// The directions of plain lyrics' lines, worked out once for each lyrics. +final _plainLyricDirections = + Expando<({List text, List lines})>(); + class PlayerLyricsSection extends ConsumerWidget { const PlayerLyricsSection({ super.key, @@ -251,8 +256,35 @@ class PlayerLyricsSection extends ConsumerWidget { shown(line.romanization, visibility.$1) != null || shown(line.translation, visibility.$2) != null, ); + final ambientDirection = Directionality.of(context); + final directions = _plainLyricDirections[lyrics] ??= ( + text: lyricLineDirections(lyrics.plainText.split('\n')), + lines: lyricLineDirections(lyrics.lines.map((line) => line.text)), + ); if (!hasSupplements) { - return Text(lyrics.plainText, style: style, textAlign: TextAlign.center); + // Each line reads in its own direction. One text has one, so lyrics + // mixing both directions get a text a line, laid out the same. + final first = directions.text.firstOrNull; + if (directions.text.every((direction) => direction == first)) { + return Text( + lyrics.plainText, + textDirection: first ?? ambientDirection, + style: style, + textAlign: TextAlign.center, + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final (index, line) in lyrics.plainText.split('\n').indexed) + Text( + line, + textDirection: directions.text[index] ?? ambientDirection, + style: style, + textAlign: TextAlign.center, + ), + ], + ); } final supplementStyle = Theme.of(context).textTheme.bodyLarge?.copyWith( height: 1.4, @@ -261,13 +293,18 @@ class PlayerLyricsSection extends ConsumerWidget { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - for (final line in lyrics.lines) + for (final (index, line) in lyrics.lines.indexed) Padding( padding: const EdgeInsets.only(bottom: 12), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Text(line.text, style: style, textAlign: TextAlign.center), + Text( + line.text, + textDirection: directions.lines[index] ?? ambientDirection, + style: style, + textAlign: TextAlign.center, + ), for (final supplement in [ shown(line.romanization, visibility.$1), shown(line.translation, visibility.$2), @@ -275,6 +312,10 @@ class PlayerLyricsSection extends ConsumerWidget { if (supplement != null) Text( supplement, + textDirection: + strongTextDirection(supplement) ?? + directions.lines[index] ?? + ambientDirection, style: supplementStyle, textAlign: TextAlign.center, ), diff --git a/lib/widgets/player_lyrics_word_sweep.dart b/lib/widgets/player_lyrics_word_sweep.dart index 5f519a78e..a2f91e44b 100644 --- a/lib/widgets/player_lyrics_word_sweep.dart +++ b/lib/widgets/player_lyrics_word_sweep.dart @@ -18,18 +18,22 @@ class WordTimedLyricLine extends StatelessWidget { final TextStyle style; final int? maxLines; + /// The line reads and sweeps in its own direction. @override - Widget build(BuildContext context) => _WordHighlightedLyricLine( - line: line, - colorScheme: Theme.of(context).colorScheme, - animate: true, - initialPosition: initialPosition, - seekPreview: seekPreview, - supplementVisibility: Offset.zero, - pronunciationLayout: null, - textAlign: TextAlign.start, - textStyle: style, - maxLines: maxLines, + Widget build(BuildContext context) => Directionality( + textDirection: strongTextDirection(line.text) ?? Directionality.of(context), + child: _WordHighlightedLyricLine( + line: line, + colorScheme: Theme.of(context).colorScheme, + animate: true, + initialPosition: initialPosition, + seekPreview: seekPreview, + supplementVisibility: Offset.zero, + pronunciationLayout: null, + textAlign: TextAlign.start, + textStyle: style, + maxLines: maxLines, + ), ); } @@ -356,11 +360,8 @@ class _WordHighlightedLyricLineState @override Widget build(BuildContext context) { - final ambientDirection = Directionality.of(context); - final lineDirection = lyricTextDirection( - widget.line.text, - ambientDirection, - ); + // The line's own direction, which its row is laid out in. + final lineDirection = Directionality.of(context); final style = widget.textStyle ?? _primaryLyricStyle(context, background: widget.line.isBackground); @@ -368,7 +369,6 @@ class _WordHighlightedLyricLineState ? _buildTimedText(widget.line.text, widget.line.words, style) : Text( widget.line.text, - textDirection: lineDirection, textAlign: widget.textAlign, style: style.copyWith(color: widget.colorScheme.onSurface), maxLines: widget.maxLines, @@ -381,18 +381,23 @@ class _WordHighlightedLyricLineState widget.line, primary, widget.colorScheme.onSurface, + direction: lineDirection, timedText: _buildTimedText, - timedSupplementText: (text, words, style) => _buildTimedText( - text, - words, - style, - lift: false, - textAlign: _supplementTextAlign( - widget.textAlign, - lineDirection, - lyricTextDirection(text, ambientDirection), - ), - ), + timedSupplementText: (text, words, style) { + final direction = strongTextDirection(text) ?? lineDirection; + return _buildTimedText( + text, + words, + style, + lift: false, + textDirection: direction, + textAlign: _supplementTextAlign( + widget.textAlign, + lineDirection, + direction, + ), + ); + }, visibility: widget.supplementVisibility, pronunciationLayout: widget.pronunciationLayout, textAlign: widget.textAlign, @@ -404,6 +409,7 @@ class _WordHighlightedLyricLineState List words, TextStyle style, { bool lift = true, + TextDirection? textDirection, TextAlign? textAlign, }) { final highlightedColor = widget.colorScheme.onSurface; @@ -421,6 +427,7 @@ class _WordHighlightedLyricLineState currentPosition: _currentPosition, repaint: _animationClock, style: style, + textDirection: textDirection, textAlign: textAlign ?? widget.textAlign, pendingColor: pendingColor, highlightedColor: highlightedColor, @@ -447,6 +454,10 @@ class _SweepingTimedLyricText extends StatefulWidget { final Duration Function() currentPosition; final Listenable repaint; final TextStyle style; + + /// The text's direction when it differs from its row's: a translation + /// under a line in another script. + final TextDirection? textDirection; final TextAlign textAlign; final Color pendingColor; final Color highlightedColor; @@ -464,6 +475,7 @@ class _SweepingTimedLyricText extends StatefulWidget { required this.currentPosition, required this.repaint, required this.style, + this.textDirection, required this.textAlign, required this.pendingColor, required this.highlightedColor, @@ -567,6 +579,12 @@ class _SweepingTimedLyricTextState extends State<_SweepingTimedLyricText> { final segmentBoxes = >[]; final segmentDirections = >[]; + // Each run sweeps in the direction it is laid out in: a Latin word or a + // number in an Arabic line reads left to right, an Arabic word in a + // Latin line right to left. A word split into several runs on one row + // (a font change) takes them in its own reading order, else in the + // line's. + final lineRightToLeft = _cachedDirection == TextDirection.rtl; var segmentOffset = 0; for (final segment in widget.segments) { final segmentEnd = segmentOffset + segment.length; @@ -578,21 +596,19 @@ class _SweepingTimedLyricTextState extends State<_SweepingTimedLyricText> { boxHeightStyle: BoxHeightStyle.max, ) .toList(); - final segmentRtl = isRtlLyricText(segment); + final direction = textBoxes.firstOrNull?.direction; + final rightToLeft = textBoxes.every((box) => box.direction == direction) + ? direction == TextDirection.rtl + : lineRightToLeft; textBoxes.sort((a, b) { final row = a.top.compareTo(b.top); if (row != 0) return row; - final rtl = - segmentRtl || - a.direction == TextDirection.rtl || - b.direction == TextDirection.rtl; - return rtl ? b.left.compareTo(a.left) : a.left.compareTo(b.left); + return rightToLeft + ? b.left.compareTo(a.left) + : a.left.compareTo(b.left); }); segmentBoxes.add([for (final box in textBoxes) box.toRect()]); - segmentDirections.add([ - for (final box in textBoxes) - segmentRtl ? TextDirection.rtl : box.direction, - ]); + segmentDirections.add([for (final box in textBoxes) box.direction]); segmentOffset = segmentEnd; } // Snapshot contents: callers can rebuild equal lists or mutate boundaries @@ -614,10 +630,10 @@ class _SweepingTimedLyricTextState extends State<_SweepingTimedLyricText> { @override Widget build(BuildContext context) { - final text = widget.segments.join(); - final textDirection = lyricTextDirection(text, Directionality.of(context)); + final textDirection = widget.textDirection ?? Directionality.of(context); final textScaler = MediaQuery.textScalerOf(context); final locale = Localizations.maybeLocaleOf(context); + final text = widget.segments.join(); _ensurePainters(text, textDirection, textScaler, locale); return LayoutBuilder( diff --git a/test/aligned_lyric_pronunciation_test.dart b/test/aligned_lyric_pronunciation_test.dart index 0e853b3bd..e18714c10 100644 --- a/test/aligned_lyric_pronunciation_test.dart +++ b/test/aligned_lyric_pronunciation_test.dart @@ -91,10 +91,6 @@ void main() { }); test('does not split right-to-left lyrics into left-to-right word boxes', () { - expect(isRtlLyricText('قطة صغيرة على الشباك'), isTrue); - expect(isRtlLyricText('qitta saghira ala ashubbak'), isFalse); - expect(lyricTextDirection('قطة صغيرة على الشباك'), TextDirection.rtl); - expect(lyricTextDirection('qitta saghira ala ashubbak'), TextDirection.ltr); expect( _layout( LyricLine( diff --git a/test/player_lyric_preview_test.dart b/test/player_lyric_preview_test.dart index d04f3b721..424f57c70 100644 --- a/test/player_lyric_preview_test.dart +++ b/test/player_lyric_preview_test.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'package:audio_service/audio_service.dart'; import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:flutter/rendering.dart' show RenderParagraph; import 'package:material_ui/material_ui.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -309,6 +310,76 @@ void main() { expect(tester.takeException(), isNull); }); + for (final mornye in [true, false]) { + testWidgets('slides a long right-to-left line towards its end on the ' + 'left (mornye: $mornye)', (tester) async { + tester.view.physicalSize = const Size(320, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + // Invented: "the blue door at the end of the old garden opens onto a + // long road between the trees". + const long = + 'الباب الأزرق في آخر الحديقة القديمة يفتح على طريق طويل بين ' + 'الأشجار'; + final lyrics = LyricsParser.parse(''' +[00:00.00]Short line +[00:05.00]$long +[00:15.00] +'''); + final view = await pumpPreview( + tester, + metadata: await _metadata(lyrics), + mornye: mornye, + ); + double offset() => tester + .widget( + find.descendant( + of: find.byType(LyricLineScroller), + matching: find.byType(Transform), + ), + ) + .transform + .getTranslation() + .x; + Rect line() => tester.getRect( + find.ancestor( + of: find.text(long), + matching: find.byType(LyricLineScroller), + ), + ); + Rect text() => tester.getRect(find.text(long)); + + view.playback.add(_at(const Duration(seconds: 5))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect( + tester.renderObject(find.text(long)).textDirection, + TextDirection.rtl, + ); + // The line starts at its beginning, on the right. + expect(offset(), 0); + expect(text().right, moreOrLessEquals(line().right, epsilon: 0.5)); + expect(text().left, lessThan(line().left)); + + // Its first words sung, it moves right to bring the next ones in. + await tester.pump(const Duration(seconds: 2)); + await tester.pump(const Duration(seconds: 2)); + final sliding = offset(); + expect(sliding, greaterThan(0)); + + // Near its end the line's last words, on its left, are in view. + view.playback.add( + _at(const Duration(milliseconds: 14500), playing: false), + ); + await tester.pumpAndSettle(); + expect(offset(), greaterThan(sliding)); + expect(text().left, moreOrLessEquals(line().left, epsilon: 0.5)); + // The row around it keeps the app's direction. + expect(tester.getCenter(find.byType(Icon)).dx, greaterThan(line().right)); + expect(tester.takeException(), isNull); + }); + } + testWidgets('keeps sliding forward when playback reports a later time late', ( tester, ) async { diff --git a/test/player_lyrics_repaint_test.dart b/test/player_lyrics_repaint_test.dart index af48aa900..66aa2c92b 100644 --- a/test/player_lyrics_repaint_test.dart +++ b/test/player_lyrics_repaint_test.dart @@ -959,9 +959,16 @@ void main() { expect(_segmentBoxes(tester), isNot(equals(boxes))); await matchesFreshLayout(); + // A Latin line reads left to right in a right-to-left app too, so its + // geometry stays. + boxes = _segmentBoxes(tester); + direction = TextDirection.rtl; + await pump(); + expect(_segmentBoxes(tester), same(boxes)); + await matchesFreshLayout(); + for (final change in [ () => width = 180, - () => direction = TextDirection.rtl, () => scale = 1.4, () => fontSize = 32, () => locale = const Locale('en', 'US'), diff --git a/test/player_lyrics_rtl_test.dart b/test/player_lyrics_rtl_test.dart new file mode 100644 index 000000000..9dd10abad --- /dev/null +++ b/test/player_lyrics_rtl_test.dart @@ -0,0 +1,476 @@ +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:audio_service/audio_service.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/controllers/player_metadata_controller.dart'; +import 'package:mornye/l10n/app_localizations.dart'; +import 'package:mornye/providers/music_player_provider.dart'; +import 'package:mornye/theme/app_theme.dart'; +import 'package:mornye/theme/mornye_theme.dart'; +import 'package:mornye/utils/lyrics_parser.dart'; +import 'package:mornye/utils/playback_seek_preview.dart'; +import 'package:mornye/widgets/player_lyrics.dart'; +import 'package:mornye/widgets/player_lyrics_section.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +// Invented lines: "a small cat on the window", "a small cat", "the blue +// door", "my cat hello door". +const _arabic = 'قطة صغيرة على الشباك'; +const _arabicCat = 'قطة صغيرة'; +const _arabicDoor = 'الباب الأزرق'; +const _arabicMixed = 'قطتي hello باب'; +const _latin = 'Lanterns'; +const _latinPath = 'Garden path'; +const _viewWidth = 600.0; + +LyricWord _word(String text, int from, int to) => LyricWord( + time: Duration(seconds: from), + end: Duration(seconds: to), + text: text, +); + +ThemeData _theme(bool mornye) => + mornye ? MornyeTheme.build(Brightness.dark) : AppTheme.dark(); + +Future _pumpLyrics( + WidgetTester tester, + List lines, { + required bool mornye, + Duration at = Duration.zero, + bool showTranslation = false, + TextDirection? appDirection, +}) async { + tester.view.physicalSize = const Size(_viewWidth, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final preview = ValueNotifier(at); + addTearDown(preview.dispose); + final theme = _theme(mornye); + Widget view = SyncedLyricsView( + lyrics: ParsedLyrics( + synced: true, + wordSynced: lines.any((line) => line.hasWordTiming), + plainText: lines.map((line) => line.text).join('\n'), + lines: lines, + ), + seekPreview: preview, + colorScheme: theme.colorScheme, + isActive: true, + showPronunciation: false, + showTranslation: showTranslation, + ); + if (appDirection != null) { + view = Directionality(textDirection: appDirection, child: view); + } + await tester.pumpWidget( + ProviderScope( + overrides: [ + playbackStateProvider.overrideWith( + (ref) => Stream.value(PlaybackState()), + ), + ], + child: MaterialApp( + theme: theme, + home: Scaffold( + body: SizedBox(width: _viewWidth, child: view), + ), + ), + ), + ); + await tester.pumpAndSettle(); +} + +/// The word sweep painting [text], found by its semantics label. +Finder _sweep(String text) => find.descendant( + of: find.byWidgetPredicate( + (widget) => widget is Semantics && widget.properties.label == text, + ), + matching: find.byType(CustomPaint), +); + +typedef _SweepLayout = ({ + List> boxes, + List> directions, + RenderBox paint, +}); + +_SweepLayout _sweepLayout(WidgetTester tester, String text) { + final finder = _sweep(text); + expect(finder, findsOneWidget); + // ignore: avoid_dynamic_calls + final painter = tester.widget(finder).painter as dynamic; + return ( + // ignore: avoid_dynamic_calls + boxes: painter.segmentBoxes as List>, + // ignore: avoid_dynamic_calls + directions: painter.segmentDirections as List>, + paint: tester.renderObject(finder), + ); +} + +/// The right edge of a sweep's letters on screen. +double _sweepRight(_SweepLayout layout) => layout.paint + .localToGlobal( + Offset( + layout.boxes + .expand((boxes) => boxes) + .map((box) => box.right) + .reduce(math.max), + 0, + ), + ) + .dx; + +/// How many fully sung pixels lie in the start and end quarter of a word's +/// [box], reading in [direction], and how many letter pixels the end +/// quarter has at all. Sung letters are opaque, unsung ones translucent in +/// both styles. +Future<({int start, int end, int endLetters})> _sungInk( + WidgetTester tester, + String text, + Rect box, + TextDirection direction, +) async { + final finder = _sweep(text); + final painter = tester.widget(finder).painter!; + final size = tester.renderObject(finder).size; + final pixels = (await tester.runAsync(() async { + final recorder = ui.PictureRecorder(); + painter.paint(Canvas(recorder), size); + final picture = recorder.endRecording(); + final image = await picture.toImage(size.width.ceil(), size.height.ceil()); + final bytes = (await image.toByteData(format: ui.ImageByteFormat.rawRgba))!; + final result = bytes.buffer.asUint8List().toList(); + image.dispose(); + picture.dispose(); + return result; + }))!; + final width = size.width.ceil(); + int count(double from, double to, int alpha) { + var count = 0; + for (var y = 0; y < size.height.ceil(); y++) { + for (var x = from.ceil(); x < to.floor(); x++) { + if (pixels[(y * width + x) * 4 + 3] >= alpha) count++; + } + } + return count; + } + + final quarter = box.width / 4; + final (startFrom, endFrom) = direction == TextDirection.rtl + ? (box.right - quarter, box.left) + : (box.left, box.right - quarter); + return ( + start: count(startFrom, startFrom + quarter, 230), + end: count(endFrom, endFrom + quarter, 230), + endLetters: count(endFrom, endFrom + quarter, 40), + ); +} + +/// Where [text]'s letters sit on screen, the edges of the space it is laid +/// out in, and the direction it reads in. +({ + double left, + double right, + double boxLeft, + double boxRight, + TextDirection direction, + TextAlign align, +}) +_ink(WidgetTester tester, String text) { + final paragraph = tester.renderObject(find.text(text)); + final boxes = paragraph.getBoxesForSelection( + TextSelection(baseOffset: 0, extentOffset: text.length), + ); + // Rows away from the current line are scaled, so each edge is mapped. + double x(double local) => paragraph.localToGlobal(Offset(local, 0)).dx; + return ( + left: x(boxes.map((box) => box.left).reduce(math.min)), + right: x(boxes.map((box) => box.right).reduce(math.max)), + boxLeft: x(0), + boxRight: x(paragraph.size.width), + direction: paragraph.textDirection, + align: paragraph.textAlign, + ); +} + +void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + for (final mornye in [true, false]) { + final style = mornye ? 'Mornye' : 'Material'; + // Spaces lead the next word, so each word's box holds only letters. + final mixedLine = LyricLine( + time: Duration.zero, + end: const Duration(seconds: 30), + text: _arabicMixed, + words: [ + _word('قطتي', 0, 10), + _word(' hello', 10, 20), + _word(' باب', 20, 30), + ], + ); + Rect latinBox(_SweepLayout layout) => + layout.boxes[1][layout.directions[1].indexOf(TextDirection.ltr)]; + + testWidgets('a right-to-left word-synced line sweeps from the right ' + '($style)', (tester) async { + await _pumpLyrics( + tester, + [mixedLine], + mornye: mornye, + at: const Duration(seconds: 5), + ); + final layout = _sweepLayout(tester, _arabicMixed); + final first = layout.boxes[0].single; + final latin = latinBox(layout); + final last = layout.boxes[2].last; + // The line reads from the right: its first word is rightmost. + expect(layout.directions[0].single, TextDirection.rtl); + expect(layout.directions[2].last, TextDirection.rtl); + expect([first.top, latin.top, last.top], everyElement(first.top)); + expect(first.left, greaterThan(latin.right - 0.5)); + expect(latin.left, greaterThan(last.right - 0.5)); + expect(first.right, greaterThan(_viewWidth / 2)); + + // Halfway through the first word, its right part is sung, its left + // part not yet. + final ink = await _sungInk( + tester, + _arabicMixed, + first, + TextDirection.rtl, + ); + expect(ink.start, greaterThan(0)); + expect(ink.end, 0); + expect(ink.endLetters, greaterThan(0)); + expect(tester.takeException(), isNull); + }); + + testWidgets('a left-to-right word in a right-to-left line sweeps from ' + 'its left ($style)', (tester) async { + await _pumpLyrics( + tester, + [mixedLine], + mornye: mornye, + at: const Duration(seconds: 16), + ); + final layout = _sweepLayout(tester, _arabicMixed); + final ink = await _sungInk( + tester, + _arabicMixed, + latinBox(layout), + TextDirection.ltr, + ); + expect(ink.start, greaterThan(0)); + expect(ink.end, 0); + expect(ink.endLetters, greaterThan(0)); + // The word before it is sung through. + final done = await _sungInk( + tester, + _arabicMixed, + layout.boxes[0].single, + TextDirection.rtl, + ); + expect(done.start, greaterThan(0)); + expect(done.end, greaterThan(0)); + expect(tester.takeException(), isNull); + }); + + testWidgets('a left-to-right word-synced line still sweeps from the ' + 'left ($style)', (tester) async { + const text = 'Lanterns glow'; + await _pumpLyrics( + tester, + [ + LyricLine( + time: Duration.zero, + end: const Duration(seconds: 20), + text: text, + words: [_word('Lanterns', 0, 10), _word(' glow', 10, 20)], + ), + ], + mornye: mornye, + at: const Duration(seconds: 5), + ); + final layout = _sweepLayout(tester, text); + final first = layout.boxes[0].single; + expect(layout.directions[0].single, TextDirection.ltr); + expect(first.right, lessThan(layout.boxes[1].first.left + 0.5)); + expect(first.left, lessThan(_viewWidth / 2)); + final ink = await _sungInk(tester, text, first, TextDirection.ltr); + expect(ink.start, greaterThan(0)); + expect(ink.end, 0); + expect(ink.endLetters, greaterThan(0)); + expect(tester.takeException(), isNull); + }); + + for (final appDirection in TextDirection.values) { + testWidgets('each line of a mixed song keeps its own direction ' + '($style, ${appDirection.name} app)', (tester) async { + await _pumpLyrics( + tester, + const [ + LyricLine(time: Duration.zero, text: _arabicCat), + LyricLine(time: Duration(seconds: 5), text: _latin), + LyricLine(time: Duration(seconds: 10), text: '...'), + LyricLine( + time: Duration(seconds: 15), + text: _arabicDoor, + voice: LyricVoice(id: 'v2', index: 1), + ), + LyricLine( + time: Duration(seconds: 20), + text: _latinPath, + voice: LyricVoice(id: 'v2', index: 1), + ), + LyricLine(time: Duration(seconds: 25), text: 'qitta'), + ], + mornye: mornye, + appDirection: appDirection, + ); + // Every line is much shorter than its row, so the side it sits on + // shows. + void sits(String text, TextDirection direction, {required bool left}) { + final ink = _ink(tester, text); + expect(ink.direction, direction, reason: text); + expect( + ink.right - ink.left, + lessThan(ink.boxRight - ink.boxLeft - 80), + ); + if (left) { + expect(ink.left, moreOrLessEquals(ink.boxLeft, epsilon: 1)); + } else { + expect(ink.right, moreOrLessEquals(ink.boxRight, epsilon: 1)); + } + } + + // Lines start on their own reading side. + sits(_arabicCat, TextDirection.rtl, left: false); + sits(_latin, TextDirection.ltr, left: true); + // A line without letters reads like the line before it. + sits('...', TextDirection.ltr, left: true); + // A duet's second voice keeps the end of its own line: the left + // of a right-to-left line, the right of a left-to-right one. + sits(_arabicDoor, TextDirection.rtl, left: true); + sits(_latinPath, TextDirection.ltr, left: false); + expect(tester.takeException(), isNull); + }); + } + + testWidgets('a translation stays on the side of its right-to-left line ' + '($style)', (tester) async { + const translation = 'A small cat'; + await _pumpLyrics( + tester, + const [ + LyricLine( + time: Duration.zero, + text: _arabic, + translation: translation, + ), + LyricLine(time: Duration(seconds: 10), text: _latin), + ], + mornye: mornye, + showTranslation: true, + ); + final line = _ink(tester, _arabic); + final shown = _ink(tester, translation); + expect(shown.direction, TextDirection.ltr); + expect(shown.align, TextAlign.right); + expect(shown.right, moreOrLessEquals(line.right, epsilon: 1)); + expect(shown.left, greaterThan(_viewWidth / 2)); + expect(tester.takeException(), isNull); + }); + + testWidgets('a timed translation reads left to right on the side of its ' + 'right-to-left line ($style)', (tester) async { + const translation = 'A small cat'; + await _pumpLyrics( + tester, + [ + LyricLine( + time: Duration.zero, + end: const Duration(seconds: 20), + text: _arabicCat, + words: [_word('قطة ', 0, 10), _word('صغيرة', 10, 20)], + translation: translation, + translationWords: [ + _word('A ', 0, 5), + _word('small ', 5, 10), + _word('cat', 10, 20), + ], + ), + ], + mornye: mornye, + at: const Duration(seconds: 2), + showTranslation: true, + ); + final line = _sweepLayout(tester, _arabicCat); + final shown = _sweepLayout(tester, translation); + expect( + shown.directions.expand((directions) => directions), + everyElement(TextDirection.ltr), + ); + // Its first word is leftmost, and it ends under the line's start. + expect( + shown.boxes.first.first.right, + lessThan(shown.boxes.last.first.left + 0.5), + ); + expect( + _sweepRight(shown), + moreOrLessEquals(_sweepRight(line), epsilon: 1), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('plain lyrics mixing directions keep each line\'s own ' + '($style)', (tester) async { + final metadata = PlayerMetadataController( + readMetadata: (_) async => const { + 'lyrics': '$_arabicCat\n$_latin\n...\n$_arabicDoor', + }, + parseLyrics: (raw) async => LyricsParser.parse(raw), + ); + final preview = PlaybackSeekPreview(); + addTearDown(metadata.dispose); + addTearDown(preview.dispose); + await metadata.load( + MediaItem( + id: 'example-song', + title: 'Example Song', + artist: 'Example Artist', + extras: const {'source': '/music/example.flac'}, + ), + ); + expect(metadata.lyrics.synced, isFalse); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: _theme(mornye), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: PlayerLyricsSection( + metadata: metadata, + seekPreview: preview, + colorScheme: const ColorScheme.dark(), + isActive: true, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(_ink(tester, _arabicCat).direction, TextDirection.rtl); + expect(_ink(tester, _latin).direction, TextDirection.ltr); + expect(_ink(tester, '...').direction, TextDirection.ltr); + expect(_ink(tester, _arabicDoor).direction, TextDirection.rtl); + expect(tester.takeException(), isNull); + }); + } +} diff --git a/test/text_direction_test.dart b/test/text_direction_test.dart new file mode 100644 index 000000000..b763c7ccd --- /dev/null +++ b/test/text_direction_test.dart @@ -0,0 +1,84 @@ +import 'package:flutter/painting.dart' show TextDirection; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/utils/text_direction.dart'; + +void main() { + group('strongTextDirection', () { + test('takes the first letter of a script', () { + expect(strongTextDirection('قطة صغيرة على الشباك'), TextDirection.rtl); + expect(strongTextDirection('הדלת הכחולה בגינה'), TextDirection.rtl); + expect( + strongTextDirection('qitta saghira ala ashubbak'), + TextDirection.ltr, + ); + expect(strongTextDirection('Ein kleines Beispiel'), TextDirection.ltr); + expect(strongTextDirection('ねこ が いる'), TextDirection.ltr); + expect(strongTextDirection('Όμορφη μέρα'), TextDirection.ltr); + }); + + test('a single word of the other script does not turn the line', () { + expect( + strongTextDirection('The blue door says قطة tonight'), + TextDirection.ltr, + ); + expect(strongTextDirection('قطة صغيرة says hello'), TextDirection.rtl); + }); + + test('digits, punctuation, spaces and marks decide nothing', () { + expect(strongTextDirection(' 2026, (...) "قطة"'), TextDirection.rtl); + expect(strongTextDirection('١٢٣ - qitta'), TextDirection.ltr); + expect(strongTextDirection('\u{1F3B5} ♪ qitta'), TextDirection.ltr); + expect(strongTextDirection('\u{064E}\u{0650} qitta'), TextDirection.ltr); + }); + + test('a byte order mark is not right to left', () { + expect(strongTextDirection('\u{FEFF}qitta saghira'), TextDirection.ltr); + expect(strongTextDirection('\u{FEFF}قطة'), TextDirection.rtl); + expect(strongTextDirection('\u{FEFF}'), isNull); + }); + + test('directional marks count as their direction', () { + expect(strongTextDirection('\u{200F}123 qitta'), TextDirection.rtl); + expect(strongTextDirection('\u{200E}123 قطة'), TextDirection.ltr); + }); + + test('text without a letter has no direction', () { + for (final text in [ + '', + ' ', + '...', + '♪ ♪', + '2026', + '١٢٣', + '\u{1F3B6}', + ]) { + expect(strongTextDirection(text), isNull, reason: text); + } + }); + }); + + test('lines without a letter follow their neighbours', () { + expect( + lyricLineDirections([ + '...', + 'قطة صغيرة', + '♪', + 'qitta saghira', + '', + 'على الشباك', + '...', + ]), + [ + TextDirection.rtl, + TextDirection.rtl, + TextDirection.rtl, + TextDirection.ltr, + TextDirection.ltr, + TextDirection.rtl, + TextDirection.rtl, + ], + ); + expect(lyricLineDirections(['...', '♪']), [null, null]); + expect(lyricLineDirections(const []), isEmpty); + }); +}