Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Look up selected words in the system dictionary instead of leaving the app

Barnabasbe49a5907ddd
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index da791b69..8082cc7e 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -238,5 +238,8 @@
<action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/>
</intent>
+ <intent>
+ <action android:name="android.intent.action.DEFINE"/>
+ </intent>
</queries>
</manifest>
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
index 890413d5..d21e2a15 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
@@ -1,6 +1,7 @@
package com.barnabas.absorb
import android.content.Context
+import android.content.ActivityNotFoundException
import android.content.Intent
import android.media.AudioDeviceInfo
import android.media.AudioManager
@@ -118,6 +119,10 @@ class MainActivity : AudioServiceActivity() {
MonoController.setMonoEnabled(enabled)
result.success(true)
}
+ "defineWord" -> {
+ val word = call.argument<String>("word") ?: ""
+ result.success(if (word.isEmpty()) false else launchDefineIntent(word))
+ }
else -> result.notImplemented()
}
}
@@ -505,6 +510,36 @@ class MainActivity : AudioServiceActivity() {
eqEnabled = false
}
+ // Reader dictionary: hand the word to the system's definition UI.
+ // Android 13+ has a dedicated DEFINE action; anything older (or without a
+ // DEFINE handler) falls back to the text-processing chooser (Translate,
+ // dictionary apps). Returns false when the device has neither, so Dart
+ // can fall back to the app's own lookup sheet.
+ private fun launchDefineIntent(word: String): Boolean {
+ if (Build.VERSION.SDK_INT >= 33) {
+ val define = Intent(Intent.ACTION_DEFINE).putExtra(Intent.EXTRA_TEXT, word)
+ if (define.resolveActivity(packageManager) != null) {
+ try {
+ startActivity(define)
+ return true
+ } catch (_: ActivityNotFoundException) {
+ }
+ }
+ }
+ val process = Intent(Intent.ACTION_PROCESS_TEXT)
+ .setType("text/plain")
+ .putExtra(Intent.EXTRA_PROCESS_TEXT, word)
+ .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, true)
+ if (process.resolveActivity(packageManager) != null) {
+ try {
+ startActivity(Intent.createChooser(process, null))
+ return true
+ } catch (_: ActivityNotFoundException) {
+ }
+ }
+ return false
+ }
+
private fun isBluetoothAudioConnected(): Boolean {
val am = getSystemService(Context.AUDIO_SERVICE) as AudioManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift
index 2cce577d..abacb2f1 100644
--- a/ios/Runner/AppDelegate.swift
+++ b/ios/Runner/AppDelegate.swift
@@ -625,6 +625,31 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
MPNowPlayingInfoCenter.default().nowPlayingInfo = info
result(true)
+ case "defineWord":
+ // Reader dictionary: present the system dictionary (offline, uses the
+ // user's own downloaded dictionaries, any language). It has its own
+ // no-definition page, so present unconditionally.
+ let word = args?["word"] as? String ?? ""
+ if word.isEmpty {
+ result(false)
+ } else {
+ DispatchQueue.main.async {
+ let scene = UIApplication.shared.connectedScenes
+ .compactMap { $0 as? UIWindowScene }
+ .first { $0.activationState == .foregroundActive }
+ let window = scene?.windows.first { $0.isKeyWindow } ?? scene?.windows.first
+ guard var presenter = window?.rootViewController else {
+ result(false)
+ return
+ }
+ while let presented = presenter.presentedViewController {
+ presenter = presented
+ }
+ presenter.present(UIReferenceLibraryViewController(term: word), animated: true)
+ result(true)
+ }
+ }
+
case "init":
result([
"bands": 5,
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index dfa3954f..afb86455 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -4799,6 +4799,10 @@
"syncSettingsDownloadWarnBody": "The synced copy will overwrite the settings on this device.",
"syncSettingsDownloadWarnConfirm": "Replace",
"readerCopied": "Copied to clipboard",
+ "dictionaryNotFound": "No definition found for this word.",
+ "dictionaryError": "Couldn't reach the dictionary. Check your connection.",
+ "dictionaryRetry": "Retry",
+ "dictionarySearchWeb": "Search the web",
"readerTooltipCopy": "Copy",
"readerTooltipSearch": "Search",
"readerTooltipDefine": "Define",
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index 6c097ada..4c4571a0 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -14535,6 +14535,30 @@ abstract class AppLocalizations {
/// **'Copied to clipboard'**
String get readerCopied;
+ /// No description provided for @dictionaryNotFound.
+ ///
+ /// In en, this message translates to:
+ /// **'No definition found for this word.'**
+ String get dictionaryNotFound;
+
+ /// No description provided for @dictionaryError.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t reach the dictionary. Check your connection.'**
+ String get dictionaryError;
+
+ /// No description provided for @dictionaryRetry.
+ ///
+ /// In en, this message translates to:
+ /// **'Retry'**
+ String get dictionaryRetry;
+
+ /// No description provided for @dictionarySearchWeb.
+ ///
+ /// In en, this message translates to:
+ /// **'Search the web'**
+ String get dictionarySearchWeb;
+
/// No description provided for @readerTooltipCopy.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index 5374ac8b..e78dd877 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -8516,6 +8516,19 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get readerCopied => 'In Zwischenablage kopiert';
+ @override
+ String get dictionaryNotFound => 'No definition found for this word.';
+
+ @override
+ String get dictionaryError =>
+ 'Couldn\'t reach the dictionary. Check your connection.';
+
+ @override
+ String get dictionaryRetry => 'Retry';
+
+ @override
+ String get dictionarySearchWeb => 'Search the web';
+
@override
String get readerTooltipCopy => 'Kopieren';
diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dart
index d764a841..21ed061f 100644
--- a/lib/l10n/app_localizations_el.dart
+++ b/lib/l10n/app_localizations_el.dart
@@ -8405,6 +8405,19 @@ class AppLocalizationsEl extends AppLocalizations {
@override
String get readerCopied => 'Copied to clipboard';
+ @override
+ String get dictionaryNotFound => 'No definition found for this word.';
+
+ @override
+ String get dictionaryError =>
+ 'Couldn\'t reach the dictionary. Check your connection.';
+
+ @override
+ String get dictionaryRetry => 'Retry';
+
+ @override
+ String get dictionarySearchWeb => 'Search the web';
+
@override
String get readerTooltipCopy => 'Copy';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 03baa64c..7d6b877e 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -8405,6 +8405,19 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get readerCopied => 'Copied to clipboard';
+ @override
+ String get dictionaryNotFound => 'No definition found for this word.';
+
+ @override
+ String get dictionaryError =>
+ 'Couldn\'t reach the dictionary. Check your connection.';
+
+ @override
+ String get dictionaryRetry => 'Retry';
+
+ @override
+ String get dictionarySearchWeb => 'Search the web';
+
@override
String get readerTooltipCopy => 'Copy';
diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart
index 79806c82..09fd7925 100644
--- a/lib/l10n/app_localizations_es.dart
+++ b/lib/l10n/app_localizations_es.dart
@@ -8407,6 +8407,19 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get readerCopied => 'Copied to clipboard';
+ @override
+ String get dictionaryNotFound => 'No definition found for this word.';
+
+ @override
+ String get dictionaryError =>
+ 'Couldn\'t reach the dictionary. Check your connection.';
+
+ @override
+ String get dictionaryRetry => 'Retry';
+
+ @override
+ String get dictionarySearchWeb => 'Search the web';
+
@override
String get readerTooltipCopy => 'Copy';
diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart
index 8a955b33..79e2f46e 100644
--- a/lib/l10n/app_localizations_fr.dart
+++ b/lib/l10n/app_localizations_fr.dart
@@ -8453,6 +8453,19 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get readerCopied => 'Copied to clipboard';
+ @override
+ String get dictionaryNotFound => 'No definition found for this word.';
+
+ @override
+ String get dictionaryError =>
+ 'Couldn\'t reach the dictionary. Check your connection.';
+
+ @override
+ String get dictionaryRetry => 'Retry';
+
+ @override
+ String get dictionarySearchWeb => 'Search the web';
+
@override
String get readerTooltipCopy => 'Copier';
diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart
index d0951abe..e29a1dda 100644
--- a/lib/l10n/app_localizations_it.dart
+++ b/lib/l10n/app_localizations_it.dart
@@ -8405,6 +8405,19 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get readerCopied => 'Copied to clipboard';
+ @override
+ String get dictionaryNotFound => 'No definition found for this word.';
+
+ @override
+ String get dictionaryError =>
+ 'Couldn\'t reach the dictionary. Check your connection.';
+
+ @override
+ String get dictionaryRetry => 'Retry';
+
+ @override
+ String get dictionarySearchWeb => 'Search the web';
+
@override
String get readerTooltipCopy => 'Copy';
diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart
index 2deb587c..f8003264 100644
--- a/lib/l10n/app_localizations_ja.dart
+++ b/lib/l10n/app_localizations_ja.dart
@@ -8405,6 +8405,19 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get readerCopied => 'Copied to clipboard';
+ @override
+ String get dictionaryNotFound => 'No definition found for this word.';
+
+ @override
+ String get dictionaryError =>
+ 'Couldn\'t reach the dictionary. Check your connection.';
+
+ @override
+ String get dictionaryRetry => 'Retry';
+
+ @override
+ String get dictionarySearchWeb => 'Search the web';
+
@override
String get readerTooltipCopy => 'Copy';
diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dart
index c5fe191b..70a5146e 100644
--- a/lib/l10n/app_localizations_no.dart
+++ b/lib/l10n/app_localizations_no.dart
@@ -8405,6 +8405,19 @@ class AppLocalizationsNo extends AppLocalizations {
@override
String get readerCopied => 'Copied to clipboard';
+ @override
+ String get dictionaryNotFound => 'No definition found for this word.';
+
+ @override
+ String get dictionaryError =>
+ 'Couldn\'t reach the dictionary. Check your connection.';
+
+ @override
+ String get dictionaryRetry => 'Retry';
+
+ @override
+ String get dictionarySearchWeb => 'Search the web';
+
@override
String get readerTooltipCopy => 'Copy';
diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart
index 39634d20..8bcee0dc 100644
--- a/lib/l10n/app_localizations_pt.dart
+++ b/lib/l10n/app_localizations_pt.dart
@@ -8405,6 +8405,19 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get readerCopied => 'Copied to clipboard';
+ @override
+ String get dictionaryNotFound => 'No definition found for this word.';
+
+ @override
+ String get dictionaryError =>
+ 'Couldn\'t reach the dictionary. Check your connection.';
+
+ @override
+ String get dictionaryRetry => 'Retry';
+
+ @override
+ String get dictionarySearchWeb => 'Search the web';
+
@override
String get readerTooltipCopy => 'Copy';
diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dart
index 26634908..583440a1 100644
--- a/lib/l10n/app_localizations_ro.dart
+++ b/lib/l10n/app_localizations_ro.dart
@@ -8405,6 +8405,19 @@ class AppLocalizationsRo extends AppLocalizations {
@override
String get readerCopied => 'Copied to clipboard';
+ @override
+ String get dictionaryNotFound => 'No definition found for this word.';
+
+ @override
+ String get dictionaryError =>
+ 'Couldn\'t reach the dictionary. Check your connection.';
+
+ @override
+ String get dictionaryRetry => 'Retry';
+
+ @override
+ String get dictionarySearchWeb => 'Search the web';
+
@override
String get readerTooltipCopy => 'Copy';
diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart
index 40716445..2847a786 100644
--- a/lib/l10n/app_localizations_ru.dart
+++ b/lib/l10n/app_localizations_ru.dart
@@ -8410,6 +8410,19 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get readerCopied => 'Copied to clipboard';
+ @override
+ String get dictionaryNotFound => 'No definition found for this word.';
+
+ @override
+ String get dictionaryError =>
+ 'Couldn\'t reach the dictionary. Check your connection.';
+
+ @override
+ String get dictionaryRetry => 'Retry';
+
+ @override
+ String get dictionarySearchWeb => 'Search the web';
+
@override
String get readerTooltipCopy => 'Copy';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index 95d14d5c..cbeab7fd 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -8313,6 +8313,19 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get readerCopied => 'Copied to clipboard';
+ @override
+ String get dictionaryNotFound => 'No definition found for this word.';
+
+ @override
+ String get dictionaryError =>
+ 'Couldn\'t reach the dictionary. Check your connection.';
+
+ @override
+ String get dictionaryRetry => 'Retry';
+
+ @override
+ String get dictionarySearchWeb => 'Search the web';
+
@override
String get readerTooltipCopy => 'Copy';
diff --git a/lib/services/dictionary_service.dart b/lib/services/dictionary_service.dart
new file mode 100644
index 00000000..9295596d
--- /dev/null
+++ b/lib/services/dictionary_service.dart
@@ -0,0 +1,117 @@
+import 'dart:convert';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:http/http.dart' as http;
+
+/// The platform's own dictionary UI: UIReferenceLibraryViewController on iOS
+/// (offline, the user's own dictionaries, any language), the system DEFINE
+/// action / text-processing chooser on Android. Returns false when the
+/// platform had nothing to show, so the caller can fall back to the in-app
+/// lookup sheet.
+class NativeDictionary {
+ static const _channel = MethodChannel('com.absorb.equalizer');
+
+ static Future<bool> define(String word) async {
+ try {
+ final ok = await _channel.invokeMethod<bool>('defineWord', {'word': word});
+ return ok ?? false;
+ } catch (e) {
+ debugPrint('[Dictionary] native define failed: $e');
+ return false;
+ }
+ }
+}
+
+enum DictionaryStatus { found, notFound, error }
+
+class DictionaryDefinition {
+ final String definition;
+ final String? example;
+ const DictionaryDefinition(this.definition, this.example);
+}
+
+class DictionaryMeaning {
+ final String partOfSpeech;
+ final List<DictionaryDefinition> definitions;
+ final List<String> synonyms;
+ const DictionaryMeaning(this.partOfSpeech, this.definitions, this.synonyms);
+}
+
+class DictionaryResult {
+ final DictionaryStatus status;
+ final String word;
+ final String? phonetic;
+ final List<DictionaryMeaning> meanings;
+ const DictionaryResult(this.status, this.word,
+ {this.phonetic, this.meanings = const []});
+}
+
+/// Word lookups against the free dictionaryapi.dev endpoint (English), so a
+/// definition opens in an in-app sheet instead of bouncing to a browser.
+class DictionaryService {
+ static Future<DictionaryResult> lookup(String word) async {
+ final clean = word.trim().toLowerCase();
+ try {
+ final resp = await http
+ .get(Uri.parse(
+ 'https://api.dictionaryapi.dev/api/v2/entries/en/${Uri.encodeComponent(clean)}'))
+ .timeout(const Duration(seconds: 8));
+ if (resp.statusCode == 404) {
+ return DictionaryResult(DictionaryStatus.notFound, clean);
+ }
+ if (resp.statusCode != 200) {
+ return DictionaryResult(DictionaryStatus.error, clean);
+ }
+ final data = jsonDecode(resp.body);
+ if (data is! List || data.isEmpty) {
+ return DictionaryResult(DictionaryStatus.notFound, clean);
+ }
+
+ String? phonetic;
+ final meanings = <DictionaryMeaning>[];
+ for (final entry in data.whereType<Map<String, dynamic>>()) {
+ phonetic ??= (entry['phonetic'] as String?)?.trim();
+ if (phonetic == null || phonetic.isEmpty) {
+ final phonetics =
+ (entry['phonetics'] as List<dynamic>? ?? const [])
+ .whereType<Map<String, dynamic>>();
+ for (final p in phonetics) {
+ final t = (p['text'] as String?)?.trim();
+ if (t != null && t.isNotEmpty) {
+ phonetic = t;
+ break;
+ }
+ }
+ }
+ for (final m in (entry['meanings'] as List<dynamic>? ?? const [])
+ .whereType<Map<String, dynamic>>()) {
+ final defs = <DictionaryDefinition>[];
+ for (final d in (m['definitions'] as List<dynamic>? ?? const [])
+ .whereType<Map<String, dynamic>>()) {
+ final text = (d['definition'] as String?)?.trim();
+ if (text == null || text.isEmpty) continue;
+ defs.add(DictionaryDefinition(
+ text, (d['example'] as String?)?.trim()));
+ }
+ if (defs.isEmpty) continue;
+ final synonyms = (m['synonyms'] as List<dynamic>? ?? const [])
+ .whereType<String>()
+ .where((s) => s.trim().isNotEmpty)
+ .take(8)
+ .toList();
+ meanings.add(DictionaryMeaning(
+ (m['partOfSpeech'] as String?) ?? '', defs, synonyms));
+ }
+ }
+ if (meanings.isEmpty) {
+ return DictionaryResult(DictionaryStatus.notFound, clean);
+ }
+ return DictionaryResult(DictionaryStatus.found, clean,
+ phonetic: phonetic, meanings: meanings);
+ } catch (e) {
+ debugPrint('[Dictionary] lookup failed for "$clean": $e');
+ return DictionaryResult(DictionaryStatus.error, clean);
+ }
+ }
+}
diff --git a/lib/widgets/dictionary_sheet.dart b/lib/widgets/dictionary_sheet.dart
new file mode 100644
index 00000000..d40697ae
--- /dev/null
+++ b/lib/widgets/dictionary_sheet.dart
@@ -0,0 +1,186 @@
+import 'package:flutter/material.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../l10n/app_localizations.dart';
+import '../services/dictionary_service.dart';
+
+/// In-app word lookup: opens instantly with a spinner, then renders the
+/// definition (or a not-found / error state with a web-search escape hatch).
+/// Tapping a synonym looks that word up in place.
+Future<void> showDictionarySheet(BuildContext context, String word) {
+ return showModalBottomSheet<void>(
+ context: context,
+ showDragHandle: true,
+ isScrollControlled: true,
+ builder: (_) => _DictionarySheet(word: word),
+ );
+}
+
+class _DictionarySheet extends StatefulWidget {
+ final String word;
+ const _DictionarySheet({required this.word});
+
+ @override
+ State<_DictionarySheet> createState() => _DictionarySheetState();
+}
+
+class _DictionarySheetState extends State<_DictionarySheet> {
+ late Future<DictionaryResult> _lookup;
+ late String _word;
+
+ @override
+ void initState() {
+ super.initState();
+ _word = widget.word;
+ _lookup = DictionaryService.lookup(_word);
+ }
+
+ void _lookupWord(String word) {
+ setState(() {
+ _word = word;
+ _lookup = DictionaryService.lookup(word);
+ });
+ }
+
+ void _searchWeb() {
+ final query = Uri.encodeComponent('define $_word');
+ launchUrl(Uri.parse('https://www.google.com/search?q=$query'),
+ mode: LaunchMode.externalApplication);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+ return SafeArea(
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.sizeOf(context).height * 0.7,
+ ),
+ child: FutureBuilder<DictionaryResult>(
+ future: _lookup,
+ builder: (context, snap) {
+ final result = snap.data;
+ return SingleChildScrollView(
+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.baseline,
+ textBaseline: TextBaseline.alphabetic,
+ children: [
+ Flexible(
+ child: Text(_word,
+ style: tt.headlineSmall
+ ?.copyWith(fontWeight: FontWeight.w700)),
+ ),
+ if (result?.phonetic != null) ...[
+ const SizedBox(width: 10),
+ Text(result!.phonetic!,
+ style: tt.bodyMedium
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ ],
+ ),
+ const SizedBox(height: 12),
+ if (result == null)
+ const Padding(
+ padding: EdgeInsets.symmetric(vertical: 32),
+ child: Center(
+ child: CircularProgressIndicator(strokeWidth: 2)),
+ )
+ else if (result.status == DictionaryStatus.found)
+ ..._buildMeanings(result, cs, tt)
+ else ...[
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ child: Text(
+ result.status == DictionaryStatus.notFound
+ ? l.dictionaryNotFound
+ : l.dictionaryError,
+ style: tt.bodyMedium
+ ?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ),
+ const SizedBox(height: 8),
+ Row(children: [
+ if (result.status == DictionaryStatus.error)
+ OutlinedButton.icon(
+ icon: const Icon(Icons.refresh_rounded, size: 18),
+ label: Text(l.dictionaryRetry),
+ onPressed: () => _lookupWord(_word),
+ ),
+ if (result.status == DictionaryStatus.error)
+ const SizedBox(width: 12),
+ OutlinedButton.icon(
+ icon: const Icon(Icons.travel_explore_rounded, size: 18),
+ label: Text(l.dictionarySearchWeb),
+ onPressed: _searchWeb,
+ ),
+ ]),
+ ],
+ ],
+ ),
+ );
+ },
+ ),
+ ),
+ );
+ }
+
+ List<Widget> _buildMeanings(
+ DictionaryResult result, ColorScheme cs, TextTheme tt) {
+ final widgets = <Widget>[];
+ for (final m in result.meanings) {
+ widgets.add(Padding(
+ padding: const EdgeInsets.only(top: 10, bottom: 4),
+ child: Text(m.partOfSpeech,
+ style: tt.titleSmall?.copyWith(
+ color: cs.primary,
+ fontStyle: FontStyle.italic,
+ fontWeight: FontWeight.w600)),
+ ));
+ for (var i = 0; i < m.definitions.length; i++) {
+ final d = m.definitions[i];
+ widgets.add(Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('${i + 1}. ${d.definition}', style: tt.bodyMedium),
+ if (d.example != null && d.example!.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.only(left: 16, top: 2),
+ child: Text('"${d.example}"',
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ fontStyle: FontStyle.italic)),
+ ),
+ ],
+ ),
+ ));
+ }
+ if (m.synonyms.isNotEmpty) {
+ widgets.add(Padding(
+ padding: const EdgeInsets.only(top: 2, bottom: 6),
+ child: Wrap(
+ spacing: 6,
+ runSpacing: 6,
+ children: [
+ for (final s in m.synonyms)
+ ActionChip(
+ label: Text(s, style: tt.labelSmall),
+ visualDensity: VisualDensity.compact,
+ onPressed: () => _lookupWord(s),
+ ),
+ ],
+ ),
+ ));
+ }
+ }
+ return widgets;
+ }
+}
diff --git a/lib/widgets/ebook_reader_view.dart b/lib/widgets/ebook_reader_view.dart
index 1efb79ec..5724a6ca 100644
--- a/lib/widgets/ebook_reader_view.dart
+++ b/lib/widgets/ebook_reader_view.dart
@@ -6,6 +6,8 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_epub_viewer/flutter_epub_viewer.dart';
import 'package:url_launcher/url_launcher.dart';
+import 'dictionary_sheet.dart';
+import '../services/dictionary_service.dart';
import 'package:provider/provider.dart';
import '../l10n/app_localizations.dart';
import '../providers/auth_provider.dart';
@@ -1084,12 +1086,21 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs
_dismissSelection();
}
- void _defineSelection() {
+ Future<void> _defineSelection() async {
if (_selectionText == null) return;
- final word = _selectionText!.trim().split(RegExp(r'\s+')).first;
- final query = Uri.encodeComponent('define $word');
- launchUrl(Uri.parse('https://www.google.com/search?q=$query'), mode: LaunchMode.externalApplication);
+ // Strip surrounding punctuation so selecting "dragon," still looks up
+ // "dragon"; multi-word selections look up their first word.
+ final word = _selectionText!
+ .trim()
+ .split(RegExp(r'\s+'))
+ .first
+ .replaceAll(RegExp(r'''^[^\w'-]+|[^\w'-]+$'''), '');
_dismissSelection();
+ if (word.isEmpty) return;
+ // The platform dictionary first (offline, any language); the in-app
+ // English lookup sheet only when the device has nothing to offer.
+ if (await NativeDictionary.define(word)) return;
+ if (mounted) showDictionarySheet(context, word);
}
void _onSelection(String text, String cfi, Rect selRect, Rect vRect) {